[teiid-commits] teiid SVN: r2778 - in tags: teiid-parent-7.3.0.Alpha1 and 98 other directories.

teiid-commits at lists.jboss.org teiid-commits at lists.jboss.org
Tue Dec 14 16:33:00 EST 2010


Author: shawkins
Date: 2010-12-14 16:32:47 -0500 (Tue, 14 Dec 2010)
New Revision: 2778

Added:
   tags/teiid-parent-7.3.0.Alpha1/
   tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
   tags/teiid-parent-7.3.0.Alpha1/api/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java
   tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java
   tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
   tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html
   tags/teiid-parent-7.3.0.Alpha1/build/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java
   tags/teiid-parent-7.3.0.Alpha1/client/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd
   tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
   tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java
   tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/TestInputStreamReader.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/console/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/Facet.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/resources/META-INF/rhq-plugin.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml
   tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionMethods.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
   tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/runtime/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/resources/TransactionsRevisited.vdb
   tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml
Removed:
   tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
   tags/teiid-parent-7.3.0.Alpha1/api/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java
   tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java
   tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
   tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html
   tags/teiid-parent-7.3.0.Alpha1/build/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java
   tags/teiid-parent-7.3.0.Alpha1/client/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java
   tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd
   tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
   tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java
   tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/FakeInputStream.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-file/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-loopback/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-salesforce/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ws/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/console/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/Facet.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
   tags/teiid-parent-7.3.0.Alpha1/console/src/main/resources/META-INF/rhq-plugin.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/developer-guide/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/quick-start-example/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml
   tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml
   tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/main/resources/org/teiid/query/i18n.properties
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
   tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
   tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java
   tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/runtime/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
   tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
   tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/resources/TransactionsRevisited.vdb
   tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml
Log:
[maven-release-plugin]  copy for tag teiid-parent-7.3.0.Alpha1

Copied: tags/teiid-parent-7.3.0.Alpha1 (from rev 2760, trunk)

Deleted: tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml
===================================================================
--- trunk/adminshell/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/adminshell/pom.xml (from rev 2777, trunk/adminshell/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/adminshell/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
===================================================================
--- trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,412 +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 static
- * 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 static License for more details.
- * 
- * You should have received a copy of the GNU Lesser General public static
- * 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.adminshell;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Properties;
-import java.util.Set;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.teiid.adminapi.Admin;
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.AdminFactory;
-import org.teiid.adminapi.CacheStatistics;
-import org.teiid.adminapi.PropertyDefinition;
-import org.teiid.adminapi.Request;
-import org.teiid.adminapi.Session;
-import org.teiid.adminapi.Transaction;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.WorkerPoolStatistics;
-import org.teiid.adminapi.VDB.ConnectionType;
-import org.teiid.adminshell.Help.Doc;
-
-
-/**
- * Contextual shell wrapper around the AdminAPI, see {@link Admin}
- */
-public class AdminShell {
-	
-	protected static Logger log = Logger.getLogger(AdminShell.class.getName());
-	
-	static Properties p;
-	private static int connectionCount = 1;
-	static Admin internalAdmin;
-	private static String currentName;
-	private static HashMap<String, Admin> connections = new HashMap<String, Admin>();
-	private static Help help = new Help(AdminShell.class);
-	
-	@Doc(text="Get a named Admin connection to the specified server")
-	public static void connectAsAdmin(
-			@Doc(text = "url - URL in the format \"mm[s]://host:port\"") String url,
-			@Doc(text = "username") String username,
-			@Doc(text = "password") String password, 
-			@Doc(text = "connection name") String connectionName) throws AdminException {
-		internalAdmin = AdminFactory.getInstance().createAdmin(username, password.toCharArray(), url);
-		currentName = connectionName;
-		Admin old = connections.put(connectionName, internalAdmin);
-		if (old != null) {
-			System.out.println("Closing previous admin associated with " + connectionName); //$NON-NLS-1$
-			old.close();
-		}
-	}
-
-	@Doc(text = "Connect as Admin using the defaults from connection.properties")
-	@SuppressWarnings("nls")
-	public static void connectAsAdmin() throws AdminException {
-		loadConnectionProperties();
-		connectAsAdmin(p.getProperty("admin.url", "mm://localhost:31443"), p.getProperty("admin.user", "admin"), 
-				p.getProperty("admin.password", "admin"), "conn-" + connectionCount++);
-	}
-
-	static void loadConnectionProperties() {
-		if (p != null) {
-			return;
-		}
-	    Properties props = new Properties();
-	    FileInputStream fis = null;
-	    try {
-		    fis = new FileInputStream("connection.properties"); //$NON-NLS-1$
-	    	props.load(fis);
-	    } catch (IOException e) {
-	    	log.log(Level.WARNING, "Could not load default connection properties.", e); //$NON-NLS-1$
-	    } finally {
-	    	if (fis != null) {
-	    		try {
-					fis.close();
-				} catch (IOException e) {
-				}
-	    	}
-	    }	    
-	    p = props;
-	}
-
-	@Doc(text = "Adds a mapped role to the specified data role")
-	public static void addDataRoleMapping(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int vdbVersion,
-			@Doc(text = "dataRole name") String policyName, 
-			@Doc(text = "mapped role name") String role) throws AdminException {
-		getAdmin().addDataRoleMapping(vdbName, vdbVersion, policyName, role);
-	}
-
-	@Doc(text = "Assign a translator and data source to a source Model")
-	public static void assignToModel(
-			@Doc(text = "vdb name") String vdbName,
-			@Doc(text = "vdb version") int vdbVersion,
-			@Doc(text = "model name") String modelName, 
-			@Doc(text = "source name") String sourceName,
-			@Doc(text = "translator name") String translatorName,
-			@Doc(text = "jndi name") String jndiName)
-			throws AdminException {
-		getAdmin().assignToModel(vdbName, vdbVersion, modelName, sourceName, translatorName, jndiName);
-	}
-
-	@Doc(text = "Cancel a request")
-	public static void cancelRequest(
-			@Doc(text = "session id") String sessionId, 
-			@Doc(text = "execution id") long executionId)
-			throws AdminException {
-		getAdmin().cancelRequest(sessionId, executionId);
-	}
-
-	@Doc(text = "Clear the given cache")
-	public static void clearCache(
-			@Doc(text = "cache type") String cacheType) throws AdminException {
-		getAdmin().clearCache(cacheType);
-	}
-
-	@Doc(text = "Delete a VDB")
-	public static void deleteVDB(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int vdbVersion) throws AdminException {
-		getAdmin().deleteVDB(vdbName, vdbVersion);
-	}
-
-	@Doc(text = "Get all cache type Strings")
-	public static Collection<String> getCacheTypes() throws AdminException {
-		return getAdmin().getCacheTypes();
-	}
-	
-	@Doc(text = "Change a VDB Connection Type")
-	public static void changeVDBConnectionType(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int vdbVersion,
-			@Doc(text = "Connection Type (NONE, BY_VERSION, or ANY") String type)
-			throws AdminException {
-		getAdmin().changeVDBConnectionType(vdbName, vdbVersion, ConnectionType.valueOf(type));
-	}
-
-	@Doc(text = "Get all translator instances")
-	public static Collection<Translator> getTranslators()
-			throws AdminException {
-		return getAdmin().getTranslators();
-	}
-
-	@Doc(text = "Get the specified ConnectionFactory")
-	public static Translator getTranslator(
-			@Doc(text = "deployed name") String deployedName)
-			throws AdminException {
-		return getAdmin().getTranslator(deployedName);
-	}
-
-	@Doc(text = "Get all PropertyDefinitions for the given template")
-	public static Collection<PropertyDefinition> getTemplatePropertyDefinitions(
-			@Doc(text = "template name") String templateName) throws AdminException {
-		return getAdmin().getTemplatePropertyDefinitions(templateName);
-	}
-
-	@Doc(text = "Get all Request instances")
-	public static Collection<Request> getRequests() throws AdminException {
-		return getAdmin().getRequests();
-	}
-
-	@Doc(text = "Get all Request instances for the given session")
-	public static Collection<Request> getRequestsForSession(
-			@Doc(text = "session id") String sessionId)
-			throws AdminException {
-		return getAdmin().getRequestsForSession(sessionId);
-	}
-
-	@Doc(text = "Get all Session instances")
-	public static Collection<Session> getSessions() throws AdminException {
-		return getAdmin().getSessions();
-	}
-
-	@Doc(text = "Get all Transaction instances")
-	public static Collection<Transaction> getTransactions() throws AdminException {
-		return getAdmin().getTransactions();
-	}
-
-	@Doc(text = "Get a specific VDB")
-	public static VDB getVDB(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int vbdVersion) throws AdminException {
-		return getAdmin().getVDB(vdbName, vbdVersion);
-	}
-
-	@Doc(text = "Get all VDB instances")
-	public static Set<VDB> getVDBs() throws AdminException {
-		return getAdmin().getVDBs();
-	}
-
-	@Doc(text = "Get thread pool statistics for Teiid")
-	public static WorkerPoolStatistics getWorkerPoolStats()
-			throws AdminException {
-		return getAdmin().getWorkerPoolStats();
-	}
-	
-	@Doc(text = "Get cache statistics for given cache type")
-	public static CacheStatistics getCacheStats(@Doc(text = "cacheType") String identifier)
-			throws AdminException {
-		return getAdmin().getCacheStats(identifier);
-	}
-	
-	@Doc(text = "Remove a mapped role for the data role")
-	public static void removeDataRoleMapping(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int vdbVersion,
-			@Doc(text = "dataRole name") String policyName, 
-			@Doc(text = "mapped role name") String role) throws AdminException {
-		getAdmin()
-				.removeDataRoleMapping(vdbName, vdbVersion, policyName, role);
-	}
-
-	@Doc(text = "Set the any authenticated flag for the data role")
-    public static void setAnyAuthenticatedForDataRole(
-    		@Doc(text = "vdb name")String vdbName, 
-    		@Doc(text = "vdb version")int vdbVersion, 
-    		@Doc(text = "dataRole name")String dataRole, 
-    		@Doc(text = "any authenticated") boolean anyAuthenticated) throws AdminException {
-    	getAdmin().setAnyAuthenticatedForDataRole(vdbName, vdbVersion, dataRole, anyAuthenticated);
-    }
-
-	@Doc(text = "Terminate a session and associated requests")
-	public static void terminateSession(
-			@Doc(text = "session id") String sessionId) throws AdminException {
-		getAdmin().terminateSession(sessionId);
-	}
-
-	@Doc(text = "Terminate a transaction")
-	public static void terminateTransaction(
-			@Doc(text = "transaction id") String transactionId)
-			throws AdminException {
-		getAdmin().terminateTransaction(transactionId);
-	}
-	
-	@Doc(text = "Merge two vdbs")
-	public static void mergeVDBs(
-			@Doc(text = "source vdb name") String sourceVDBName, 
-			@Doc(text = "source vdb version") int sourceVDBVersion,
-			@Doc(text = "target vdb name") String targetVDBName, 
-			@Doc(text = "target vdb version") int targetVDBVersion) throws AdminException {
-		getAdmin().mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
-	}
-	
-	@Doc(text = "Checks if a translator exists")
-	public static boolean hasTranslator(@Doc(text = "deployed name") String factoryName) throws AdminException {
-	    Collection<Translator> bindings = getAdmin().getTranslators();
-	    
-	    for (Translator binding:bindings) {
-	        if (binding.getName().equals(factoryName)) {
-	            return true;
-	        }        
-	    }            
-	    return false;
-	}
-
-	@Doc(text = "Checks if a VDB exists")
-	public static boolean hasVDB(
-			@Doc(text = "vdb name") String vdbName) throws AdminException {
-	    Collection<VDB> vdbs = getAdmin().getVDBs();
-	    for (VDB vdb:vdbs) {
-	        if (vdb.getName().equals(vdbName)) {
-	            return true;
-	        }
-	    }
-	    return false;
-	}
-
-	@Doc(text = "Checks if a specific VDB version exists")
-	public static boolean hasVDB(
-			@Doc(text = "vdb name") String vdbName, 
-			@Doc(text = "vdb version") int version) throws AdminException {
-	    Collection<VDB> vdbs = getAdmin().getVDBs();
-	    for (VDB vdb:vdbs) {
-	        if (vdb.getName().equals(vdbName) && vdb.getVersion() == version) {
-	            return true;
-	        }
-	    }
-	    return false;
-	}
-
-	/*private static void writeFile(String deployedName, String fileName,
-			InputStream contents) throws IOException, AdminProcessingException {
-		if (contents == null) {
-	    	throw new AdminProcessingException(deployedName + " not found for exporting");//$NON-NLS-1$
-	    }
-		ObjectConverterUtil.write(contents, fileName);	
-	}*/
-	
-	@Doc(text = "Deploy a VDB from file")
-	public static void deployVDB(
-			@Doc(text = "file name") String vdbFile) throws AdminException, FileNotFoundException {
-		File file = new File(vdbFile);
-		FileInputStream fis = new FileInputStream(file);
-		try {
-			getAdmin().deployVDB(file.getName(), fis);
-		} finally {
-			try {
-				fis.close();
-			} catch (IOException e) {
-			}
-		}
-	}
-	@Doc(text = "Create a data source from supplied properties")
-	public static void createDataSource(@Doc(text = "deployed name")String deploymentName, @Doc(text = "template name")String templateName, @Doc(text = "properties")Properties properties) throws AdminException {
-		getAdmin().createDataSource(deploymentName, templateName, properties);
-	}
-	
-	@Doc(text = "Delete data source")
-	public static void deleteDataSource(@Doc(text = "deployed name")String deployedName) throws AdminException{
-		getAdmin().deleteDataSource(deployedName);
-	}
-	
-	@Doc(text = "Available data sources")
-	public static Collection<String> getDataSourceNames() throws AdminException{
-		return getAdmin().getDataSourceNames();
-	}
-
-	@Doc(text = "Available data source template names")
-	public static Set<String> getDataSourceTemplateNames() throws AdminException{
-		return getAdmin().getDataSourceTemplateNames();
-	}
-	
-	@Doc(text = "Get the current org.teiid.adminapi.Admin instance for direct use. Note: Used for advanced usecases to bypass AdminShell methods")
-	public static Admin getAdmin() {
-		if (internalAdmin == null) {
-	        throw new NullPointerException("Not connected.  You must call a \"connectAsAdmin\" method or choose an active connection via \"useConnection\"."); //$NON-NLS-1$
-	    }
-		return internalAdmin;
-	}
-	
-	@Doc(text = "Disconnect the current connection for the server")
-	public static void disconnect() {
-	    if (internalAdmin != null) {
-	    	internalAdmin.close();
-	    	internalAdmin = null;
-	    	connections.remove(currentName);
-	    	currentName = null;
-	    }  
-	}
-	
-	@Doc(text = "Disconnect all connections from the server")
-	public static void disconnectAll() {
-		for (Admin admin : connections.values()) {
-			admin.close();
-		}
-		connections.clear();
-		internalAdmin = null;
-		currentName = null;
-	}
-	
-	@Doc(text = "Use another connection")
-	public static void useConnection(
-			@Doc(text = "connection name") String name) {
-		Admin admin = connections.get(name);
-		if (admin == null) {
-			System.out.println("Warning: connection is not active for " + name); //$NON-NLS-1$
-			return;
-		}
-		internalAdmin = admin;
-		currentName = name;
-	}
-
-	@Doc(text = "Returns the current connection name")
-	public static String getConnectionName() {
-	    return currentName;
-	}
-
-	@Doc(text = "Return all connection names")
-	public static Collection<String> getAllConnections() {
-	    return connections.keySet();
-	}
-	
-	@Doc(text = "Show help for all admin methods")
-	public static void adminHelp() {
-		help.help();
-	}
-	
-	@Doc(text = "Show help for the given admin method")
-	public static void adminHelp(
-			@Doc(text = "method name") String method) {
-		help.help(method);
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java (from rev 2774, trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,420 @@
+/*
+ * 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 static
+ * 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 static License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General public static
+ * 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.adminshell;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Properties;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.AdminFactory;
+import org.teiid.adminapi.CacheStatistics;
+import org.teiid.adminapi.PropertyDefinition;
+import org.teiid.adminapi.Request;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.Transaction;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.WorkerPoolStatistics;
+import org.teiid.adminapi.VDB.ConnectionType;
+import org.teiid.adminshell.Help.Doc;
+
+
+/**
+ * Contextual shell wrapper around the AdminAPI, see {@link Admin}
+ */
+public class AdminShell {
+	
+	protected static Logger log = Logger.getLogger(AdminShell.class.getName());
+	
+	static Properties p;
+	private static int connectionCount = 1;
+	static Admin internalAdmin;
+	private static String currentName;
+	private static HashMap<String, Admin> connections = new HashMap<String, Admin>();
+	private static Help help = new Help(AdminShell.class);
+	
+	@Doc(text="Get a named Admin connection to the specified server")
+	public static void connectAsAdmin(
+			@Doc(text = "url - URL in the format \"mm[s]://host:port\"") String url,
+			@Doc(text = "username") String username,
+			@Doc(text = "password") String password, 
+			@Doc(text = "connection name") String connectionName) throws AdminException {
+		internalAdmin = AdminFactory.getInstance().createAdmin(username, password.toCharArray(), url);
+		currentName = connectionName;
+		Admin old = connections.put(connectionName, internalAdmin);
+		if (old != null) {
+			System.out.println("Closing previous admin associated with " + connectionName); //$NON-NLS-1$
+			old.close();
+		}
+	}
+
+	@Doc(text = "Connect as Admin using the defaults from connection.properties")
+	@SuppressWarnings("nls")
+	public static void connectAsAdmin() throws AdminException {
+		loadConnectionProperties();
+		connectAsAdmin(p.getProperty("admin.url", "mm://localhost:31443"), p.getProperty("admin.user", "admin"), 
+				p.getProperty("admin.password", "admin"), "conn-" + connectionCount++);
+	}
+
+	static void loadConnectionProperties() {
+		if (p != null) {
+			return;
+		}
+	    Properties props = new Properties();
+	    FileInputStream fis = null;
+	    try {
+		    fis = new FileInputStream("connection.properties"); //$NON-NLS-1$
+	    	props.load(fis);
+	    } catch (IOException e) {
+	    	log.log(Level.WARNING, "Could not load default connection properties.", e); //$NON-NLS-1$
+	    } finally {
+	    	if (fis != null) {
+	    		try {
+					fis.close();
+				} catch (IOException e) {
+				}
+	    	}
+	    }	    
+	    p = props;
+	}
+
+	@Doc(text = "Adds a mapped role to the specified data role")
+	public static void addDataRoleMapping(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vdbVersion,
+			@Doc(text = "dataRole name") String policyName, 
+			@Doc(text = "mapped role name") String role) throws AdminException {
+		getAdmin().addDataRoleMapping(vdbName, vdbVersion, policyName, role);
+	}
+
+	@Doc(text = "Assign a translator and data source to a source Model")
+	public static void assignToModel(
+			@Doc(text = "vdb name") String vdbName,
+			@Doc(text = "vdb version") int vdbVersion,
+			@Doc(text = "model name") String modelName, 
+			@Doc(text = "source name") String sourceName,
+			@Doc(text = "translator name") String translatorName,
+			@Doc(text = "jndi name") String jndiName)
+			throws AdminException {
+		getAdmin().assignToModel(vdbName, vdbVersion, modelName, sourceName, translatorName, jndiName);
+	}
+
+	@Doc(text = "Cancel a request")
+	public static void cancelRequest(
+			@Doc(text = "session id") String sessionId, 
+			@Doc(text = "execution id") long executionId)
+			throws AdminException {
+		getAdmin().cancelRequest(sessionId, executionId);
+	}
+
+	@Doc(text = "Clear the given cache")
+	public static void clearCache(
+			@Doc(text = "cache type") String cacheType) throws AdminException {
+		getAdmin().clearCache(cacheType);
+	}
+	
+	@Doc(text = "Clear the given cache for a VDB")
+	public static void clearCache(
+			@Doc(text = "cache type") String cacheType, @Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vdbVersion			
+			) throws AdminException {
+		getAdmin().clearCache(cacheType, vdbName, vdbVersion);
+	}	
+
+	@Doc(text = "Delete a VDB")
+	public static void deleteVDB(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vdbVersion) throws AdminException {
+		getAdmin().deleteVDB(vdbName, vdbVersion);
+	}
+
+	@Doc(text = "Get all cache type Strings")
+	public static Collection<String> getCacheTypes() throws AdminException {
+		return getAdmin().getCacheTypes();
+	}
+	
+	@Doc(text = "Change a VDB Connection Type")
+	public static void changeVDBConnectionType(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vdbVersion,
+			@Doc(text = "Connection Type (NONE, BY_VERSION, or ANY") String type)
+			throws AdminException {
+		getAdmin().changeVDBConnectionType(vdbName, vdbVersion, ConnectionType.valueOf(type));
+	}
+
+	@Doc(text = "Get all translator instances")
+	public static Collection<Translator> getTranslators()
+			throws AdminException {
+		return getAdmin().getTranslators();
+	}
+
+	@Doc(text = "Get the specified ConnectionFactory")
+	public static Translator getTranslator(
+			@Doc(text = "deployed name") String deployedName)
+			throws AdminException {
+		return getAdmin().getTranslator(deployedName);
+	}
+
+	@Doc(text = "Get all PropertyDefinitions for the given template")
+	public static Collection<PropertyDefinition> getTemplatePropertyDefinitions(
+			@Doc(text = "template name") String templateName) throws AdminException {
+		return getAdmin().getTemplatePropertyDefinitions(templateName);
+	}
+
+	@Doc(text = "Get all Request instances")
+	public static Collection<Request> getRequests() throws AdminException {
+		return getAdmin().getRequests();
+	}
+
+	@Doc(text = "Get all Request instances for the given session")
+	public static Collection<Request> getRequestsForSession(
+			@Doc(text = "session id") String sessionId)
+			throws AdminException {
+		return getAdmin().getRequestsForSession(sessionId);
+	}
+
+	@Doc(text = "Get all Session instances")
+	public static Collection<Session> getSessions() throws AdminException {
+		return getAdmin().getSessions();
+	}
+
+	@Doc(text = "Get all Transaction instances")
+	public static Collection<Transaction> getTransactions() throws AdminException {
+		return getAdmin().getTransactions();
+	}
+
+	@Doc(text = "Get a specific VDB")
+	public static VDB getVDB(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vbdVersion) throws AdminException {
+		return getAdmin().getVDB(vdbName, vbdVersion);
+	}
+
+	@Doc(text = "Get all VDB instances")
+	public static Set<VDB> getVDBs() throws AdminException {
+		return getAdmin().getVDBs();
+	}
+
+	@Doc(text = "Get thread pool statistics for Teiid")
+	public static WorkerPoolStatistics getWorkerPoolStats()
+			throws AdminException {
+		return getAdmin().getWorkerPoolStats();
+	}
+	
+	@Doc(text = "Get cache statistics for given cache type")
+	public static CacheStatistics getCacheStats(@Doc(text = "cacheType") String identifier)
+			throws AdminException {
+		return getAdmin().getCacheStats(identifier);
+	}
+	
+	@Doc(text = "Remove a mapped role for the data role")
+	public static void removeDataRoleMapping(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int vdbVersion,
+			@Doc(text = "dataRole name") String policyName, 
+			@Doc(text = "mapped role name") String role) throws AdminException {
+		getAdmin()
+				.removeDataRoleMapping(vdbName, vdbVersion, policyName, role);
+	}
+
+	@Doc(text = "Set the any authenticated flag for the data role")
+    public static void setAnyAuthenticatedForDataRole(
+    		@Doc(text = "vdb name")String vdbName, 
+    		@Doc(text = "vdb version")int vdbVersion, 
+    		@Doc(text = "dataRole name")String dataRole, 
+    		@Doc(text = "any authenticated") boolean anyAuthenticated) throws AdminException {
+    	getAdmin().setAnyAuthenticatedForDataRole(vdbName, vdbVersion, dataRole, anyAuthenticated);
+    }
+
+	@Doc(text = "Terminate a session and associated requests")
+	public static void terminateSession(
+			@Doc(text = "session id") String sessionId) throws AdminException {
+		getAdmin().terminateSession(sessionId);
+	}
+
+	@Doc(text = "Terminate a transaction")
+	public static void terminateTransaction(
+			@Doc(text = "transaction id") String transactionId)
+			throws AdminException {
+		getAdmin().terminateTransaction(transactionId);
+	}
+	
+	@Doc(text = "Merge two vdbs")
+	public static void mergeVDBs(
+			@Doc(text = "source vdb name") String sourceVDBName, 
+			@Doc(text = "source vdb version") int sourceVDBVersion,
+			@Doc(text = "target vdb name") String targetVDBName, 
+			@Doc(text = "target vdb version") int targetVDBVersion) throws AdminException {
+		getAdmin().mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
+	}
+	
+	@Doc(text = "Checks if a translator exists")
+	public static boolean hasTranslator(@Doc(text = "deployed name") String factoryName) throws AdminException {
+	    Collection<Translator> bindings = getAdmin().getTranslators();
+	    
+	    for (Translator binding:bindings) {
+	        if (binding.getName().equals(factoryName)) {
+	            return true;
+	        }        
+	    }            
+	    return false;
+	}
+
+	@Doc(text = "Checks if a VDB exists")
+	public static boolean hasVDB(
+			@Doc(text = "vdb name") String vdbName) throws AdminException {
+	    Collection<VDB> vdbs = getAdmin().getVDBs();
+	    for (VDB vdb:vdbs) {
+	        if (vdb.getName().equals(vdbName)) {
+	            return true;
+	        }
+	    }
+	    return false;
+	}
+
+	@Doc(text = "Checks if a specific VDB version exists")
+	public static boolean hasVDB(
+			@Doc(text = "vdb name") String vdbName, 
+			@Doc(text = "vdb version") int version) throws AdminException {
+	    Collection<VDB> vdbs = getAdmin().getVDBs();
+	    for (VDB vdb:vdbs) {
+	        if (vdb.getName().equals(vdbName) && vdb.getVersion() == version) {
+	            return true;
+	        }
+	    }
+	    return false;
+	}
+
+	/*private static void writeFile(String deployedName, String fileName,
+			InputStream contents) throws IOException, AdminProcessingException {
+		if (contents == null) {
+	    	throw new AdminProcessingException(deployedName + " not found for exporting");//$NON-NLS-1$
+	    }
+		ObjectConverterUtil.write(contents, fileName);	
+	}*/
+	
+	@Doc(text = "Deploy a VDB from file")
+	public static void deployVDB(
+			@Doc(text = "file name") String vdbFile) throws AdminException, FileNotFoundException {
+		File file = new File(vdbFile);
+		FileInputStream fis = new FileInputStream(file);
+		try {
+			getAdmin().deployVDB(file.getName(), fis);
+		} finally {
+			try {
+				fis.close();
+			} catch (IOException e) {
+			}
+		}
+	}
+	@Doc(text = "Create a data source from supplied properties")
+	public static void createDataSource(@Doc(text = "deployed name")String deploymentName, @Doc(text = "template name")String templateName, @Doc(text = "properties")Properties properties) throws AdminException {
+		getAdmin().createDataSource(deploymentName, templateName, properties);
+	}
+	
+	@Doc(text = "Delete data source")
+	public static void deleteDataSource(@Doc(text = "deployed name")String deployedName) throws AdminException{
+		getAdmin().deleteDataSource(deployedName);
+	}
+	
+	@Doc(text = "Available data sources")
+	public static Collection<String> getDataSourceNames() throws AdminException{
+		return getAdmin().getDataSourceNames();
+	}
+
+	@Doc(text = "Available data source template names")
+	public static Set<String> getDataSourceTemplateNames() throws AdminException{
+		return getAdmin().getDataSourceTemplateNames();
+	}
+	
+	@Doc(text = "Get the current org.teiid.adminapi.Admin instance for direct use. Note: Used for advanced usecases to bypass AdminShell methods")
+	public static Admin getAdmin() {
+		if (internalAdmin == null) {
+	        throw new NullPointerException("Not connected.  You must call a \"connectAsAdmin\" method or choose an active connection via \"useConnection\"."); //$NON-NLS-1$
+	    }
+		return internalAdmin;
+	}
+	
+	@Doc(text = "Disconnect the current connection for the server")
+	public static void disconnect() {
+	    if (internalAdmin != null) {
+	    	internalAdmin.close();
+	    	internalAdmin = null;
+	    	connections.remove(currentName);
+	    	currentName = null;
+	    }  
+	}
+	
+	@Doc(text = "Disconnect all connections from the server")
+	public static void disconnectAll() {
+		for (Admin admin : connections.values()) {
+			admin.close();
+		}
+		connections.clear();
+		internalAdmin = null;
+		currentName = null;
+	}
+	
+	@Doc(text = "Use another connection")
+	public static void useConnection(
+			@Doc(text = "connection name") String name) {
+		Admin admin = connections.get(name);
+		if (admin == null) {
+			System.out.println("Warning: connection is not active for " + name); //$NON-NLS-1$
+			return;
+		}
+		internalAdmin = admin;
+		currentName = name;
+	}
+
+	@Doc(text = "Returns the current connection name")
+	public static String getConnectionName() {
+	    return currentName;
+	}
+
+	@Doc(text = "Return all connection names")
+	public static Collection<String> getAllConnections() {
+	    return connections.keySet();
+	}
+	
+	@Doc(text = "Show help for all admin methods")
+	public static void adminHelp() {
+		help.help();
+	}
+	
+	@Doc(text = "Show help for the given admin method")
+	public static void adminHelp(
+			@Doc(text = "method name") String method) {
+		help.help(method);
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/api/pom.xml
===================================================================
--- trunk/api/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/api/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/api/pom.xml (from rev 2777, trunk/api/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/api/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>teiid-api</artifactId>
+  <name>Teiid Translator API</name>
+  <description>API for creating Translators and other common extenders in Teiid</description>
+  
+  <dependencies>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+        
+    <dependency>
+      <groupId>javax.resource</groupId>
+      <artifactId>connector-api</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+  </dependencies>
+</project>

Deleted: tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java
===================================================================
--- trunk/api/src/main/java/org/teiid/metadata/FunctionMethod.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,484 +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.metadata;
-
-import java.io.Serializable;
-import java.util.Arrays;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-
-import org.teiid.core.util.HashCodeUtil;
-
-
-/**
- * <p>This class represents information about a particular function signature.  
- * Function signatures are unique with respect to their name, # of arguments, 
- * and type of arguments. Return type and argument names are not uniqueness
- * factors.  This class makes no attempt to validate the data put into it, 
- * particularly with respect to null values.  The 
- * {@link FunctionMetadataValidator} can be used to validate this object.</p>
- *
- * Attributes:
- * <UL>
- * <LI>name - Name of the function</LI>
- * <LI>description - Description of the function</LI>
- * <LI>category - Function category containing this function</LI>
- * <LI>pushdown - Determine whether this function can, cannot, or must be pushed down to a source</LI>
- * <LI>invocationClass - Class containing method implementing this function</LI>
- * <LI>invocationMethod - Method implementing this function</LI>
- * <LI>inputParameters - 0 or more input parameters</LI>
- * <LI>outputParameter - 1 output parameter</LI>
- * <LI>determinism - specifies whether the function is deterministic or not. Various levels are provided
- * <LI>nullOnNull - Specifies whether the function is called if any of the input arguments is null. The result is the null value.
- * </UL>
- *
- * @see FunctionParameter
- */
-public class FunctionMethod extends AbstractMetadataRecord implements Serializable {
-	private static final long serialVersionUID = -8039086494296455152L;
-
-	private static final String NOT_ALLOWED = "NOT_ALLOWED"; //$NON-NLS-1$
-	private static final String ALLOWED = "ALLOWED"; //$NON-NLS-1$
-	private static final String REQUIRED = "REQUIRED"; //$NON-NLS-1$
-
-	/**
-	 * Function Pushdown
-	 * CAN_PUSHDOWN = If the source supports the function, then it will be pushed down. Must supply the Java impl
-	 * CANNOT_PUSHDOWN = It will not be pushed down, evaluated in Teiid. Must supply the Java impl
-	 * MUST_PUSHDOWN = Function must be pushed to source, no need to supply Java impl.
-	 * SYNTHETIC = system functions?
-	 */
-	public enum PushDown {CAN_PUSHDOWN, CANNOT_PUSHDOWN, MUST_PUSHDOWN, SYNTHETIC};
-    
-    /**
-     * DETERMINISTIC -> normal deterministic functions
-     * vdb -> lookup (however lookup values can be flushed at any time), current_database
-     * session -> env, user
-     * command -> command payload
-     * never -> rand, etc.
-     * 
-     * Anything at a session level and above is treated as deterministic.
-     * This is not quite correct for lookup or env.  Only in extremely rare
-     * circumstances would that be a problem.
-     * 
-     * For now the commandPayload function is treated as a special case, like lookup, in
-     * that it is considered deterministic, but will be delayed in its evaluation until
-     * processing time.
-     */
-    public enum Determinism{
-    	DETERMINISTIC(0),VDB_DETERMINISTIC(1),USER_DETERMINISTIC(2),SESSION_DETERMINISTIC(3),COMMAND_DETERMINISTIC(4),NONDETERMINISTIC(5);
-    	private int value;
-    	
-    	Determinism(int value){
-    		this.value = value;
-    	}
-    	
-    	public boolean isRestrictiveThan(Determinism that) {
-    		return this.value > that.value;
-    	}
-    	
-    	public boolean isRestrictiveThanOrEqual(Determinism that) {
-    		return this.value >= that.value;
-    	}    	
-    	
-    	public static Determinism restrictiveOf(Determinism scopeOne, Determinism scopeTwo) {
-    		return (scopeOne.value > scopeTwo.value)?scopeOne:scopeTwo;
-    	}
-    }
-    
-
-    private String description;
-    private String category;
-    private PushDown pushdown = PushDown.CAN_PUSHDOWN;
-    private String invocationClass;
-    private String invocationMethod;
-    private boolean nullDependent;
-    
-    private Determinism determinism = Determinism.DETERMINISTIC;
-        
-    private FunctionParameter[] inputParameters;
-    private FunctionParameter outputParameter;
-    
-    protected FunctionMethod() {
-    }
-       
-    public FunctionMethod(String name, String description, String category, FunctionParameter[] inputParams, FunctionParameter outputParam) {
-    	this(name, description, category, PushDown.MUST_PUSHDOWN, null, null, inputParams, outputParam, true, Determinism.DETERMINISTIC);
-    }
-    
-    public FunctionMethod(String name,
-                          String description,
-                          String category,
-                          PushDown pushdown,
-                          String invocationClass,
-                          String invocationMethod,
-                          FunctionParameter[] inputParams,
-                          FunctionParameter outputParam,
-                          boolean nullOnNull,
-                          Determinism deterministic) {
-        
-        setName(name);
-        setDescription(description);
-        setCategory(category);
-        setPushdown(pushdown);
-        setInvocationClass(invocationClass);
-        setInvocationMethod(invocationMethod);
-        setInputParameters(inputParams);
-        setOutputParameter(outputParam); 
-        setNullOnNull(nullOnNull);
-        setDeterminism(deterministic);
-    }
-    
-    /**
-     * Return name of method
-     * @return Name
-     */
-    @XmlAttribute
-    public String getName() {
-        return super.getName();
-    }
-    
-    /**
-     * Set name of method
-     * @param name Name
-     */
-    public void setName(String name) { 
-        super.setName(name);
-    }
-    
-    @Override
-	public String getFullName() {
-    	if (this.category != null) {
-    		return this.category + NAME_DELIM_CHAR + getName();
-    	}
-		return getName(); 
-	}
-    
-    
-    /**
-     * Get description of method
-     * @return Description
-     */
-    @XmlAttribute
-    public String getDescription() { 
-        return this.description;
-    }        
-    
-    /**
-     * Set description of method
-     * @param description Description
-     */
-    public void setDescription(String description) { 
-        this.description = description;
-    }
-
-    /**
-     * Get category of method
-     * @return Category
-     * @see FunctionCategoryConstants
-     */
-    @XmlAttribute
-    public String getCategory() { 
-        return this.category;
-    }        
-    
-    /**
-     * Set category of method
-     * @param category Category
-     * @see FunctionCategoryConstants
-     */
-    public void setCategory(String category) { 
-        this.category = category;
-    }
-    
-    /**
-     * Get pushdown property of method
-     * @return One of the FunctionMethod constants for pushdown
-     */
-    public PushDown getPushdown() {
-        return pushdown;
-    }
-
-    /**
-     * Set pushdown property of method
-     * @param pushdown One of the FunctionMethod constants for pushdown
-     */
-    public void setPushdown(PushDown pushdown) {
-        this.pushdown = pushdown;
-    }
-    
-    @XmlAttribute
-    public void setPushDown(String pushdown) {
-    	if (pushdown != null) {
-			if (pushdown.equals(REQUIRED)) {
-				this.pushdown = PushDown.MUST_PUSHDOWN;
-			} else if (pushdown.equals(ALLOWED)) {
-				this.pushdown = PushDown.CAN_PUSHDOWN;
-			} else if (pushdown.equals(NOT_ALLOWED)) {
-				this.pushdown = PushDown.CANNOT_PUSHDOWN;
-			}
-		} else {
-			this.pushdown = PushDown.CAN_PUSHDOWN;
-		}
-    }
-    
-    /**
-     * Get invocation class name
-     * @return Invocation class name
-     */
-    @XmlAttribute
-    public String getInvocationClass() { 
-        return this.invocationClass;
-    }        
-    
-    /**
-     * Set invocation class name
-     * @param invocationClass Invocation class name
-     */
-    public void setInvocationClass(String invocationClass) { 
-        this.invocationClass = invocationClass;
-    }
-    
-    /**
-     * Get invocation method name
-     * @return Invocation method name
-     */
-    @XmlAttribute
-    public String getInvocationMethod() { 
-        return this.invocationMethod;
-    }        
-    
-    /**
-     * Set invocation method name
-     * @param invocationMethod Invocation method name
-     */
-    public void setInvocationMethod(String invocationMethod) { 
-        this.invocationMethod = invocationMethod;
-    }
-    
-    /**
-     * Get a count of the input parameters.
-     * @return Number of input parameters
-     */
-    public int getInputParameterCount() {
-        if(this.inputParameters == null) { 
-            return 0;
-        }
-        return this.inputParameters.length;
-    }
-    
-    /**
-     * Get input parameters
-     * @return Array of input parameters, may be null if 0 parameters
-     */
-    @XmlElement
-    public FunctionParameter[] getInputParameters() { 
-        return this.inputParameters;
-    }
-    
-    /**
-     * Set input parameters.
-     * @param params Input parameters
-     */
-    public void setInputParameters(FunctionParameter[] params) { 
-        this.inputParameters = params;
-    }
-    
-    /**
-     * Get ouput parameter.
-     * @return Output parameter or return argument
-     */
-    @XmlElement(name="returnParameter")
-    public FunctionParameter getOutputParameter() { 
-        return this.outputParameter;
-    }
-    
-    /**
-     * Set ouput parameter.
-     * @param param Output Parameter
-     */
-    public void setOutputParameter(FunctionParameter param) {
-    	if (param != null) {
-    		param.setName(FunctionParameter.OUTPUT_PARAMETER_NAME);
-    	}
-        this.outputParameter = param;
-    }
-    
-    /**
-     * Get hash code for this object.  The hash code is based on the name 
-     * and input parameters.  <B>WARNING: Changing the name or input parameters
-     * will change the hash code.</B>  If this occurs after the object has been
-     * placed in a HashSet or HashMap, the object will be lost!!!!  In that 
-     * case, the object must be added to the hashed collection again.
-     * @return Hash code, based on name and input parameters
-     */
-    public int hashCode() { 
-        int hash = HashCodeUtil.hashCode(0, super.getName());
-        if(inputParameters != null) { 
-            hash = HashCodeUtil.hashCode(hash, Arrays.hashCode(inputParameters));
-        }             
-        return hash;
-    }
-    
-    /**
-     * Compare other object for equality.  This object is equal to another 
-     * FunctionMethod if 1) Name of function matches (case-insensitive), 
-     * 2) number of input parameters matches and 3) types of input parameters
-     * match.
-     * @return True if object equals this object according to conditions
-     */
-    public boolean equals(Object obj) {
-        if(obj == this) { 
-            return true;
-        } 
-        if(obj instanceof FunctionMethod) { 
-            FunctionMethod other = (FunctionMethod) obj;
-
-            // Compare # of parameters - do this first as it is much faster than name compare
-            if(getInputParameterCount() != other.getInputParameterCount()) {
-                return false;
-            }
-
-            // Compare function names - case insensitive
-            if(other.getName() == null || this.getName() == null) { 
-                return false;
-            }
-            if(! other.getName().equalsIgnoreCase(this.getName()) ) {
-                return false;
-            }
-            
-            // Compare types of parameters
-            FunctionParameter[] thisInputs = this.getInputParameters();
-            if(thisInputs != null && thisInputs.length > 0) { 
-                // If thisInputs is not null and >0 and other parameter
-                // count matched this parameter count, otherInputs MUST be 
-                // non null to have more than one parameter - so we don't 
-                // need to check it here.
-                FunctionParameter[] otherInputs = other.getInputParameters();
-                
-                for(int i=0; i<thisInputs.length; i++) { 
-                    boolean paramMatch = compareWithNull(thisInputs[i], otherInputs[i]);
-                    if(! paramMatch) { 
-                        return false;
-                    }    
-                }   
-            }    
-            
-            // Found no discrepancies, must be equal
-            return true;            
-        } 
-        return false;
-    }    
-    
-    /**
-     * Compare two objects that may or may not be null and consider null==null
-     * as true.
-     * @param o1 Object 1
-     * @param o2 Object 2
-     * @return True if o1 and o2 are null or if they both aren't and they are equal
-     */
-    private boolean compareWithNull(Object o1, Object o2) {
-        if(o1 == null) { 
-            if(o2 == null) { 
-                return true;
-            }
-            return false;
-        }
-        if(o2 == null) { 
-            return false;
-        }
-        return o1.equals(o2);
-    }
-    
-    /**
-     * Return string version for debugging purposes
-     * @return String representation of function method
-     */ 
-    public String toString() { 
-        StringBuffer str = new StringBuffer();
-        if(getName() != null) { 
-            str.append(getName());
-        } else {
-            str.append("<unknown>"); //$NON-NLS-1$
-        } 
-        
-        // Print parameters
-        str.append("("); //$NON-NLS-1$
-        if(inputParameters != null) { 
-            for(int i=0; i<inputParameters.length; i++) {
-                if(inputParameters[i] != null) { 
-                    str.append(inputParameters[i].toString());                   
-                } else {
-                    str.append("<unknown>"); //$NON-NLS-1$
-                }
-                
-                if(i < (inputParameters.length-1)) { 
-                    str.append(", "); //$NON-NLS-1$
-                }
-            }    
-        }                                
-        str.append(") : "); //$NON-NLS-1$
-        
-        // Print return type
-        if(outputParameter != null) { 
-            str.append(outputParameter.toString());
-        } else {
-            str.append("<unknown>"); //$NON-NLS-1$
-        }
-        
-        return str.toString();
-    }
-
-    /**
-     * Returns true if the function can produce a non-null output from a null parameter
-     */
-    public boolean isNullOnNull() {
-        return this.nullDependent;
-    }
-    
-    public void setNullOnNull(boolean nullSafe) {
-        this.nullDependent = nullSafe;
-    }
-
-    public Determinism getDeterminism() {
-        return this.determinism;
-    }
-    
-    @XmlAttribute(name="deterministic")
-    public void setDeterministicBoolean(boolean deterministic) {
-    	this.determinism = deterministic ? Determinism.DETERMINISTIC : Determinism.NONDETERMINISTIC;
-    }
-    
-    public void setDeterminism(Determinism determinism) {
-        this.determinism = determinism;
-    }
-    
-    public boolean isVarArgs() {
-    	if (this.inputParameters != null && this.inputParameters.length > 0) {
-    		return inputParameters[inputParameters.length - 1].isVarArg();
-    	}
-    	return false;
-    }
-     
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java (from rev 2764, trunk/api/src/main/java/org/teiid/metadata/FunctionMethod.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/metadata/FunctionMethod.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,471 @@
+/*
+ * 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.metadata;
+
+import java.util.Arrays;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
+import org.teiid.core.util.HashCodeUtil;
+
+
+/**
+ * <p>This class represents information about a particular function signature.  
+ * Function signatures are unique with respect to their name, # of arguments, 
+ * and type of arguments. Return type and argument names are not uniqueness
+ * factors.  This class makes no attempt to validate the data put into it, 
+ * particularly with respect to null values.  The 
+ * {@link FunctionMetadataValidator} can be used to validate this object.</p>
+ *
+ * Attributes:
+ * <UL>
+ * <LI>name - Name of the function</LI>
+ * <LI>description - Description of the function</LI>
+ * <LI>category - Function category containing this function</LI>
+ * <LI>pushdown - Determine whether this function can, cannot, or must be pushed down to a source</LI>
+ * <LI>invocationClass - Class containing method implementing this function</LI>
+ * <LI>invocationMethod - Method implementing this function</LI>
+ * <LI>inputParameters - 0 or more input parameters</LI>
+ * <LI>outputParameter - 1 output parameter</LI>
+ * <LI>determinism - specifies whether the function is deterministic or not. Various levels are provided
+ * <LI>nullOnNull - Specifies whether the function is called if any of the input arguments is null. The result is the null value.
+ * </UL>
+ *
+ * @see FunctionParameter
+ */
+public class FunctionMethod extends AbstractMetadataRecord {
+	private static final long serialVersionUID = -8039086494296455152L;
+
+	private static final String NOT_ALLOWED = "NOT_ALLOWED"; //$NON-NLS-1$
+	private static final String ALLOWED = "ALLOWED"; //$NON-NLS-1$
+	private static final String REQUIRED = "REQUIRED"; //$NON-NLS-1$
+
+	/**
+	 * Function Pushdown
+	 * CAN_PUSHDOWN = If the source supports the function, then it will be pushed down. Must supply the Java impl
+	 * CANNOT_PUSHDOWN = It will not be pushed down, evaluated in Teiid. Must supply the Java impl
+	 * MUST_PUSHDOWN = Function must be pushed to source, no need to supply Java impl.
+	 * SYNTHETIC = system functions?
+	 */
+	public enum PushDown {CAN_PUSHDOWN, CANNOT_PUSHDOWN, MUST_PUSHDOWN, SYNTHETIC};
+    
+    /**
+     * DETERMINISTIC -> normal deterministic functions
+     * vdb -> lookup (however lookup values can be flushed at any time), current_database
+     * session -> env, user
+     * command -> command payload
+     * never -> rand, etc.
+     * 
+     * Anything at a session level and above is treated as deterministic.
+     * This is not quite correct for lookup or env.  Only in extremely rare
+     * circumstances would that be a problem.
+     * 
+     * For now the commandPayload function is treated as a special case, like lookup, in
+     * that it is considered deterministic, but will be delayed in its evaluation until
+     * processing time.
+     */
+    public enum Determinism{
+    	NONDETERMINISTIC,
+    	COMMAND_DETERMINISTIC,
+    	SESSION_DETERMINISTIC,
+    	USER_DETERMINISTIC,
+    	VDB_DETERMINISTIC,
+    	DETERMINISTIC;
+    }
+    
+
+    private String description;
+    private String category;
+    private PushDown pushdown = PushDown.CAN_PUSHDOWN;
+    private String invocationClass;
+    private String invocationMethod;
+    private boolean nullOnNull;
+    
+    private Determinism determinism = Determinism.DETERMINISTIC;
+        
+    private FunctionParameter[] inputParameters;
+    private FunctionParameter outputParameter;
+    
+    protected FunctionMethod() {
+    }
+       
+    public FunctionMethod(String name, String description, String category, FunctionParameter[] inputParams, FunctionParameter outputParam) {
+    	this(name, description, category, PushDown.MUST_PUSHDOWN, null, null, inputParams, outputParam, true, Determinism.DETERMINISTIC);
+    }
+    
+    public FunctionMethod(String name,
+                          String description,
+                          String category,
+                          PushDown pushdown,
+                          String invocationClass,
+                          String invocationMethod,
+                          FunctionParameter[] inputParams,
+                          FunctionParameter outputParam,
+                          boolean nullOnNull,
+                          Determinism deterministic) {
+        
+        setName(name);
+        setDescription(description);
+        setCategory(category);
+        setPushdown(pushdown);
+        setInvocationClass(invocationClass);
+        setInvocationMethod(invocationMethod);
+        setInputParameters(inputParams);
+        setOutputParameter(outputParam); 
+        setNullOnNull(nullOnNull);
+        setDeterminism(deterministic);
+    }
+    
+    /**
+     * Return name of method
+     * @return Name
+     */
+    @XmlAttribute
+    public String getName() {
+        return super.getName();
+    }
+    
+    /**
+     * Set name of method
+     * @param name Name
+     */
+    public void setName(String name) { 
+        super.setName(name);
+    }
+    
+    @Override
+	public String getFullName() {
+    	if (this.category != null) {
+    		return this.category + NAME_DELIM_CHAR + getName();
+    	}
+		return getName(); 
+	}
+    
+    
+    /**
+     * Get description of method
+     * @return Description
+     */
+    @XmlAttribute
+    public String getDescription() { 
+        return this.description;
+    }        
+    
+    /**
+     * Set description of method
+     * @param description Description
+     */
+    public void setDescription(String description) { 
+        this.description = description;
+    }
+
+    /**
+     * Get category of method
+     * @return Category
+     * @see FunctionCategoryConstants
+     */
+    @XmlAttribute
+    public String getCategory() { 
+        return this.category;
+    }        
+    
+    /**
+     * Set category of method
+     * @param category Category
+     * @see FunctionCategoryConstants
+     */
+    public void setCategory(String category) { 
+        this.category = category;
+    }
+    
+    /**
+     * Get pushdown property of method
+     * @return One of the FunctionMethod constants for pushdown
+     */
+    public PushDown getPushdown() {
+        return pushdown;
+    }
+
+    /**
+     * Set pushdown property of method
+     * @param pushdown One of the FunctionMethod constants for pushdown
+     */
+    public void setPushdown(PushDown pushdown) {
+        this.pushdown = pushdown;
+    }
+    
+    @XmlAttribute
+    public void setPushDown(String pushdown) {
+    	if (pushdown != null) {
+			if (pushdown.equals(REQUIRED)) {
+				this.pushdown = PushDown.MUST_PUSHDOWN;
+			} else if (pushdown.equals(ALLOWED)) {
+				this.pushdown = PushDown.CAN_PUSHDOWN;
+			} else if (pushdown.equals(NOT_ALLOWED)) {
+				this.pushdown = PushDown.CANNOT_PUSHDOWN;
+			}
+		} else {
+			this.pushdown = PushDown.CAN_PUSHDOWN;
+		}
+    }
+    
+    /**
+     * Get invocation class name
+     * @return Invocation class name
+     */
+    @XmlAttribute
+    public String getInvocationClass() { 
+        return this.invocationClass;
+    }        
+    
+    /**
+     * Set invocation class name
+     * @param invocationClass Invocation class name
+     */
+    public void setInvocationClass(String invocationClass) { 
+        this.invocationClass = invocationClass;
+    }
+    
+    /**
+     * Get invocation method name
+     * @return Invocation method name
+     */
+    @XmlAttribute
+    public String getInvocationMethod() { 
+        return this.invocationMethod;
+    }        
+    
+    /**
+     * Set invocation method name
+     * @param invocationMethod Invocation method name
+     */
+    public void setInvocationMethod(String invocationMethod) { 
+        this.invocationMethod = invocationMethod;
+    }
+    
+    /**
+     * Get a count of the input parameters.
+     * @return Number of input parameters
+     */
+    public int getInputParameterCount() {
+        if(this.inputParameters == null) { 
+            return 0;
+        }
+        return this.inputParameters.length;
+    }
+    
+    /**
+     * Get input parameters
+     * @return Array of input parameters, may be null if 0 parameters
+     */
+    @XmlElement
+    public FunctionParameter[] getInputParameters() { 
+        return this.inputParameters;
+    }
+    
+    /**
+     * Set input parameters.
+     * @param params Input parameters
+     */
+    public void setInputParameters(FunctionParameter[] params) { 
+        this.inputParameters = params;
+    }
+    
+    /**
+     * Get ouput parameter.
+     * @return Output parameter or return argument
+     */
+    @XmlElement(name="returnParameter")
+    public FunctionParameter getOutputParameter() { 
+        return this.outputParameter;
+    }
+    
+    /**
+     * Set ouput parameter.
+     * @param param Output Parameter
+     */
+    public void setOutputParameter(FunctionParameter param) {
+    	if (param != null) {
+    		param.setName(FunctionParameter.OUTPUT_PARAMETER_NAME);
+    	}
+        this.outputParameter = param;
+    }
+    
+    /**
+     * Get hash code for this object.  The hash code is based on the name 
+     * and input parameters.  <B>WARNING: Changing the name or input parameters
+     * will change the hash code.</B>  If this occurs after the object has been
+     * placed in a HashSet or HashMap, the object will be lost!!!!  In that 
+     * case, the object must be added to the hashed collection again.
+     * @return Hash code, based on name and input parameters
+     */
+    public int hashCode() { 
+        int hash = HashCodeUtil.hashCode(0, super.getName());
+        if(inputParameters != null) { 
+            hash = HashCodeUtil.hashCode(hash, Arrays.hashCode(inputParameters));
+        }             
+        return hash;
+    }
+    
+    /**
+     * Compare other object for equality.  This object is equal to another 
+     * FunctionMethod if 1) Name of function matches (case-insensitive), 
+     * 2) number of input parameters matches and 3) types of input parameters
+     * match.
+     * @return True if object equals this object according to conditions
+     */
+    public boolean equals(Object obj) {
+        if(obj == this) { 
+            return true;
+        } 
+        if(obj instanceof FunctionMethod) { 
+            FunctionMethod other = (FunctionMethod) obj;
+
+            // Compare # of parameters - do this first as it is much faster than name compare
+            if(getInputParameterCount() != other.getInputParameterCount()) {
+                return false;
+            }
+
+            // Compare function names - case insensitive
+            if(other.getName() == null || this.getName() == null) { 
+                return false;
+            }
+            if(! other.getName().equalsIgnoreCase(this.getName()) ) {
+                return false;
+            }
+            
+            // Compare types of parameters
+            FunctionParameter[] thisInputs = this.getInputParameters();
+            if(thisInputs != null && thisInputs.length > 0) { 
+                // If thisInputs is not null and >0 and other parameter
+                // count matched this parameter count, otherInputs MUST be 
+                // non null to have more than one parameter - so we don't 
+                // need to check it here.
+                FunctionParameter[] otherInputs = other.getInputParameters();
+                
+                for(int i=0; i<thisInputs.length; i++) { 
+                    boolean paramMatch = compareWithNull(thisInputs[i], otherInputs[i]);
+                    if(! paramMatch) { 
+                        return false;
+                    }    
+                }   
+            }    
+            
+            // Found no discrepancies, must be equal
+            return true;            
+        } 
+        return false;
+    }    
+    
+    /**
+     * Compare two objects that may or may not be null and consider null==null
+     * as true.
+     * @param o1 Object 1
+     * @param o2 Object 2
+     * @return True if o1 and o2 are null or if they both aren't and they are equal
+     */
+    private boolean compareWithNull(Object o1, Object o2) {
+        if(o1 == null) { 
+            if(o2 == null) { 
+                return true;
+            }
+            return false;
+        }
+        if(o2 == null) { 
+            return false;
+        }
+        return o1.equals(o2);
+    }
+    
+    /**
+     * Return string version for debugging purposes
+     * @return String representation of function method
+     */ 
+    public String toString() { 
+        StringBuffer str = new StringBuffer();
+        if(getName() != null) { 
+            str.append(getName());
+        } else {
+            str.append("<unknown>"); //$NON-NLS-1$
+        } 
+        
+        // Print parameters
+        str.append("("); //$NON-NLS-1$
+        if(inputParameters != null) { 
+            for(int i=0; i<inputParameters.length; i++) {
+                if(inputParameters[i] != null) { 
+                    str.append(inputParameters[i].toString());                   
+                } else {
+                    str.append("<unknown>"); //$NON-NLS-1$
+                }
+                
+                if(i < (inputParameters.length-1)) { 
+                    str.append(", "); //$NON-NLS-1$
+                }
+            }    
+        }                                
+        str.append(") : "); //$NON-NLS-1$
+        
+        // Print return type
+        if(outputParameter != null) { 
+            str.append(outputParameter.toString());
+        } else {
+            str.append("<unknown>"); //$NON-NLS-1$
+        }
+        
+        return str.toString();
+    }
+
+    /**
+     * Returns true if the function returns null on any null input
+     */
+    public boolean isNullOnNull() {
+        return this.nullOnNull;
+    }
+    
+    public void setNullOnNull(boolean nullOnNull) {
+        this.nullOnNull = nullOnNull;
+    }
+
+    public Determinism getDeterminism() {
+        return this.determinism;
+    }
+    
+    @XmlAttribute(name="deterministic")
+    public void setDeterministicBoolean(boolean deterministic) {
+    	this.determinism = deterministic ? Determinism.DETERMINISTIC : Determinism.NONDETERMINISTIC;
+    }
+    
+    public void setDeterminism(Determinism determinism) {
+        this.determinism = determinism;
+    }
+    
+    public boolean isVarArgs() {
+    	if (this.inputParameters != null && this.inputParameters.length > 0) {
+    		return inputParameters[inputParameters.length - 1].isVarArg();
+    	}
+    	return false;
+    }
+     
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java
===================================================================
--- trunk/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,148 +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;
-
-/**
- * Constants for all the possible standard system push down functions.
- * The names and function forms follow the Open Group CLI functions, with a few exceptions
- * (such as lpad, rpad, bitand, bitor, etc. which are most notably supported by Oracle).
- * 
- */
-public class SourceSystemFunctions {
-	
-	//arithmetic
-	public static final String MULTIPLY_OP = "*"; //$NON-NLS-1$
-	public static final String ADD_OP = "+"; //$NON-NLS-1$
-	public static final String SUBTRACT_OP = "-"; //$NON-NLS-1$
-	public static final String DIVIDE_OP = "/"; //$NON-NLS-1$
-	
-	//String
-	public static final String ASCII = "ascii"; //$NON-NLS-1$
-	public static final String CHAR = "char"; //$NON-NLS-1$
-	public static final String CONCAT = "concat"; //$NON-NLS-1$
-	//public static final String DIFFERENCE = "difference";
-	public static final String INITCAP = "initcap"; //$NON-NLS-1$
-	public static final String INSERT = "insert"; //$NON-NLS-1$
-	public static final String LCASE = "lcase"; //$NON-NLS-1$
-	public static final String LPAD = "lpad"; //$NON-NLS-1$
-	public static final String LEFT = "left"; //$NON-NLS-1$
-	public static final String LENGTH = "length"; //$NON-NLS-1$
-	public static final String LOCATE = "locate"; //$NON-NLS-1$
-	public static final String LTRIM = "ltrim"; //$NON-NLS-1$
-	public static final String REPEAT = "repeat"; //$NON-NLS-1$
-	public static final String REPLACE = "replace"; //$NON-NLS-1$
-	public static final String RIGHT = "right"; //$NON-NLS-1$
-	public static final String RPAD = "rpad"; //$NON-NLS-1$
-	public static final String RTRIM = "rtrim"; //$NON-NLS-1$
-	//public static final String SOUNDEX = "soundex";
-	public static final String SUBSTRING = "substring"; //$NON-NLS-1$
-	public static final String TO_BYTES = "to_bytes"; //$NON-NLS-1$
-	public static final String TO_CHARS = "to_chars"; //$NON-NLS-1$
-	public static final String UCASE = "ucase"; //$NON-NLS-1$
-	
-	//numeric
-	public static final String ABS = "abs"; //$NON-NLS-1$
-	public static final String ACOS = "acos"; //$NON-NLS-1$
-	public static final String ASIN = "asin"; //$NON-NLS-1$
-	public static final String ATAN = "atan"; //$NON-NLS-1$
-	public static final String ATAN2 = "atan2"; //$NON-NLS-1$
-	public static final String CEILING = "ceiling"; //$NON-NLS-1$
-	public static final String COS = "cos"; //$NON-NLS-1$
-	public static final String COT = "cot"; //$NON-NLS-1$
-	public static final String DEGREES = "degrees"; //$NON-NLS-1$
-	public static final String EXP = "exp"; //$NON-NLS-1$
-	public static final String FLOOR = "floor"; //$NON-NLS-1$
-	public static final String FORMATINTEGER = "formatinteger"; //$NON-NLS-1$
-	public static final String FORMATLONG = "formatlong"; //$NON-NLS-1$
-	public static final String FORMATDOUBLE = "formatdouble"; //$NON-NLS-1$
-	public static final String FORMATFLOAT = "formatfloat"; //$NON-NLS-1$
-	public static final String FORMATBIGINTEGER = "formatbiginteger"; //$NON-NLS-1$
-	public static final String FORMATBIGDECIMAL = "formatbigdecimal"; //$NON-NLS-1$
-	public static final String LOG = "log"; //$NON-NLS-1$
-	public static final String LOG10 = "log10"; //$NON-NLS-1$
-	public static final String MOD = "mod"; //$NON-NLS-1$
-	public static final String PARSEINTEGER = "parseinteger"; //$NON-NLS-1$
-	public static final String PARSELONG = "parselong"; //$NON-NLS-1$
-	public static final String PARSEDOUBLE = "parsedouble"; //$NON-NLS-1$
-	public static final String PARSEFLOAT = "parsefloat"; //$NON-NLS-1$
-	public static final String PARSEBIGINTEGER = "parsebiginteger"; //$NON-NLS-1$
-	public static final String PARSEBIGDECIMAL = "parsebigdecimal"; //$NON-NLS-1$
-	public static final String PI = "pi"; //$NON-NLS-1$
-	public static final String POWER = "power"; //$NON-NLS-1$
-	public static final String RADIANS = "radians"; //$NON-NLS-1$
-	public static final String RAND = "rand"; //$NON-NLS-1$
-	public static final String ROUND = "round"; //$NON-NLS-1$
-	public static final String SIGN = "sign"; //$NON-NLS-1$
-	public static final String SIN = "sin"; //$NON-NLS-1$
-	public static final String SQRT = "sqrt"; //$NON-NLS-1$
-	public static final String TAN = "tan"; //$NON-NLS-1$
-	public static final String TRANSLATE = "translate"; //$NON-NLS-1$
-	public static final String TRUNCATE = "truncate"; //$NON-NLS-1$
-	
-	//bit
-	public static final String BITAND = "bitand"; //$NON-NLS-1$
-	public static final String BITOR = "bitor"; //$NON-NLS-1$
-	public static final String BITNOT = "bitnot"; //$NON-NLS-1$
-	public static final String BITXOR = "bitxor"; //$NON-NLS-1$
-	
-	//date functions
-	public static final String CURDATE = "curdate"; //$NON-NLS-1$
-	public static final String CURTIME = "curtime"; //$NON-NLS-1$
-	public static final String DAYNAME = "dayname"; //$NON-NLS-1$
-	public static final String DAYOFMONTH = "dayofmonth"; //$NON-NLS-1$
-	public static final String DAYOFWEEK = "dayofweek"; //$NON-NLS-1$
-	public static final String DAYOFYEAR = "dayofyear"; //$NON-NLS-1$
-	public static final String FORMATTIMESTAMP = "formattimestamp"; //$NON-NLS-1$
-	public static final String HOUR = "hour"; //$NON-NLS-1$
-	public static final String MINUTE = "minute"; //$NON-NLS-1$
-	public static final String MODIFYTIMEZONE = "modifytimezone"; //$NON-NLS-1$
-	public static final String MONTH = "month"; //$NON-NLS-1$
-	public static final String MONTHNAME = "monthname"; //$NON-NLS-1$
-	public static final String NOW = "now"; //$NON-NLS-1$
-	public static final String PARSETIMESTAMP = "parsetimestamp"; //$NON-NLS-1$
-	public static final String QUARTER = "quarter"; //$NON-NLS-1$
-	public static final String SECOND = "second"; //$NON-NLS-1$
-	public static final String TIMESTAMPADD = "timestampadd"; //$NON-NLS-1$
-	public static final String TIMESTAMPCREATE = "timestampcreate"; //$NON-NLS-1$
-	public static final String TIMESTAMPDIFF = "timestampdiff"; //$NON-NLS-1$
-	public static final String WEEK = "week"; //$NON-NLS-1$
-	public static final String YEAR = "year"; //$NON-NLS-1$
-	
-	//system functions
-	public static final String IFNULL = "ifnull"; //$NON-NLS-1$
-	public static final String COALESCE = "coalesce"; //$NON-NLS-1$
-	public static final String NULLIF = "nullif"; //$NON-NLS-1$
-	
-	//conversion functions
-	public static final String CONVERT = "convert"; //$NON-NLS-1$
-	
-	//xml
-	public static final String XPATHVALUE = "xpathvalue"; //$NON-NLS-1$
-	public static final String XSLTRANSFORM = "xsltransform"; //$NON-NLS-1$
-	public static final String XMLCONCAT = "xmlconcat"; //$NON-NLS-1$
-	public static final String XMLCOMMENT = "xmlcomment"; //$NON-NLS-1$
-	public static final String XMLPI = "xmlpi"; //$NON-NLS-1$
-	
-	public static final String JSONTOXML = "jsontoxml"; //$NON-NLS-1$
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java (from rev 2765, trunk/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,149 @@
+/*
+ * 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;
+
+/**
+ * Constants for all the possible standard system push down functions.
+ * The names and function forms follow the Open Group CLI functions, with a few exceptions
+ * (such as lpad, rpad, bitand, bitor, etc. which are most notably supported by Oracle).
+ * 
+ */
+public class SourceSystemFunctions {
+	
+	//arithmetic
+	public static final String MULTIPLY_OP = "*"; //$NON-NLS-1$
+	public static final String ADD_OP = "+"; //$NON-NLS-1$
+	public static final String SUBTRACT_OP = "-"; //$NON-NLS-1$
+	public static final String DIVIDE_OP = "/"; //$NON-NLS-1$
+	
+	//String
+	public static final String ASCII = "ascii"; //$NON-NLS-1$
+	public static final String CHAR = "char"; //$NON-NLS-1$
+	public static final String CONCAT = "concat"; //$NON-NLS-1$
+	//public static final String DIFFERENCE = "difference";
+	public static final String INITCAP = "initcap"; //$NON-NLS-1$
+	public static final String INSERT = "insert"; //$NON-NLS-1$
+	public static final String LCASE = "lcase"; //$NON-NLS-1$
+	public static final String LPAD = "lpad"; //$NON-NLS-1$
+	public static final String LEFT = "left"; //$NON-NLS-1$
+	public static final String LENGTH = "length"; //$NON-NLS-1$
+	public static final String LOCATE = "locate"; //$NON-NLS-1$
+	public static final String LTRIM = "ltrim"; //$NON-NLS-1$
+	public static final String REPEAT = "repeat"; //$NON-NLS-1$
+	public static final String REPLACE = "replace"; //$NON-NLS-1$
+	public static final String RIGHT = "right"; //$NON-NLS-1$
+	public static final String RPAD = "rpad"; //$NON-NLS-1$
+	public static final String RTRIM = "rtrim"; //$NON-NLS-1$
+	//public static final String SOUNDEX = "soundex";
+	public static final String SUBSTRING = "substring"; //$NON-NLS-1$
+	public static final String TO_BYTES = "to_bytes"; //$NON-NLS-1$
+	public static final String TO_CHARS = "to_chars"; //$NON-NLS-1$
+	public static final String UCASE = "ucase"; //$NON-NLS-1$
+	public static final String UNESCAPE = "unescape"; //$NON-NLS-1$
+	
+	//numeric
+	public static final String ABS = "abs"; //$NON-NLS-1$
+	public static final String ACOS = "acos"; //$NON-NLS-1$
+	public static final String ASIN = "asin"; //$NON-NLS-1$
+	public static final String ATAN = "atan"; //$NON-NLS-1$
+	public static final String ATAN2 = "atan2"; //$NON-NLS-1$
+	public static final String CEILING = "ceiling"; //$NON-NLS-1$
+	public static final String COS = "cos"; //$NON-NLS-1$
+	public static final String COT = "cot"; //$NON-NLS-1$
+	public static final String DEGREES = "degrees"; //$NON-NLS-1$
+	public static final String EXP = "exp"; //$NON-NLS-1$
+	public static final String FLOOR = "floor"; //$NON-NLS-1$
+	public static final String FORMATINTEGER = "formatinteger"; //$NON-NLS-1$
+	public static final String FORMATLONG = "formatlong"; //$NON-NLS-1$
+	public static final String FORMATDOUBLE = "formatdouble"; //$NON-NLS-1$
+	public static final String FORMATFLOAT = "formatfloat"; //$NON-NLS-1$
+	public static final String FORMATBIGINTEGER = "formatbiginteger"; //$NON-NLS-1$
+	public static final String FORMATBIGDECIMAL = "formatbigdecimal"; //$NON-NLS-1$
+	public static final String LOG = "log"; //$NON-NLS-1$
+	public static final String LOG10 = "log10"; //$NON-NLS-1$
+	public static final String MOD = "mod"; //$NON-NLS-1$
+	public static final String PARSEINTEGER = "parseinteger"; //$NON-NLS-1$
+	public static final String PARSELONG = "parselong"; //$NON-NLS-1$
+	public static final String PARSEDOUBLE = "parsedouble"; //$NON-NLS-1$
+	public static final String PARSEFLOAT = "parsefloat"; //$NON-NLS-1$
+	public static final String PARSEBIGINTEGER = "parsebiginteger"; //$NON-NLS-1$
+	public static final String PARSEBIGDECIMAL = "parsebigdecimal"; //$NON-NLS-1$
+	public static final String PI = "pi"; //$NON-NLS-1$
+	public static final String POWER = "power"; //$NON-NLS-1$
+	public static final String RADIANS = "radians"; //$NON-NLS-1$
+	public static final String RAND = "rand"; //$NON-NLS-1$
+	public static final String ROUND = "round"; //$NON-NLS-1$
+	public static final String SIGN = "sign"; //$NON-NLS-1$
+	public static final String SIN = "sin"; //$NON-NLS-1$
+	public static final String SQRT = "sqrt"; //$NON-NLS-1$
+	public static final String TAN = "tan"; //$NON-NLS-1$
+	public static final String TRANSLATE = "translate"; //$NON-NLS-1$
+	public static final String TRUNCATE = "truncate"; //$NON-NLS-1$
+	
+	//bit
+	public static final String BITAND = "bitand"; //$NON-NLS-1$
+	public static final String BITOR = "bitor"; //$NON-NLS-1$
+	public static final String BITNOT = "bitnot"; //$NON-NLS-1$
+	public static final String BITXOR = "bitxor"; //$NON-NLS-1$
+	
+	//date functions
+	public static final String CURDATE = "curdate"; //$NON-NLS-1$
+	public static final String CURTIME = "curtime"; //$NON-NLS-1$
+	public static final String DAYNAME = "dayname"; //$NON-NLS-1$
+	public static final String DAYOFMONTH = "dayofmonth"; //$NON-NLS-1$
+	public static final String DAYOFWEEK = "dayofweek"; //$NON-NLS-1$
+	public static final String DAYOFYEAR = "dayofyear"; //$NON-NLS-1$
+	public static final String FORMATTIMESTAMP = "formattimestamp"; //$NON-NLS-1$
+	public static final String HOUR = "hour"; //$NON-NLS-1$
+	public static final String MINUTE = "minute"; //$NON-NLS-1$
+	public static final String MODIFYTIMEZONE = "modifytimezone"; //$NON-NLS-1$
+	public static final String MONTH = "month"; //$NON-NLS-1$
+	public static final String MONTHNAME = "monthname"; //$NON-NLS-1$
+	public static final String NOW = "now"; //$NON-NLS-1$
+	public static final String PARSETIMESTAMP = "parsetimestamp"; //$NON-NLS-1$
+	public static final String QUARTER = "quarter"; //$NON-NLS-1$
+	public static final String SECOND = "second"; //$NON-NLS-1$
+	public static final String TIMESTAMPADD = "timestampadd"; //$NON-NLS-1$
+	public static final String TIMESTAMPCREATE = "timestampcreate"; //$NON-NLS-1$
+	public static final String TIMESTAMPDIFF = "timestampdiff"; //$NON-NLS-1$
+	public static final String WEEK = "week"; //$NON-NLS-1$
+	public static final String YEAR = "year"; //$NON-NLS-1$
+	
+	//system functions
+	public static final String IFNULL = "ifnull"; //$NON-NLS-1$
+	public static final String COALESCE = "coalesce"; //$NON-NLS-1$
+	public static final String NULLIF = "nullif"; //$NON-NLS-1$
+	
+	//conversion functions
+	public static final String CONVERT = "convert"; //$NON-NLS-1$
+	
+	//xml
+	public static final String XPATHVALUE = "xpathvalue"; //$NON-NLS-1$
+	public static final String XSLTRANSFORM = "xsltransform"; //$NON-NLS-1$
+	public static final String XMLCONCAT = "xmlconcat"; //$NON-NLS-1$
+	public static final String XMLCOMMENT = "xmlcomment"; //$NON-NLS-1$
+	public static final String XMLPI = "xmlpi"; //$NON-NLS-1$
+	
+	public static final String JSONTOXML = "jsontoxml"; //$NON-NLS-1$
+
+}

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

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

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

Copied: tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html (from rev 2775, trunk/build/kits/jboss-container/teiid-releasenotes.html)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/build/kits/jboss-container/teiid-releasenotes.html	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,209 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML>
+<HEAD>
+	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8">
+	<TITLE>Teiid ${project.version} Release Notes</TITLE>
+	<META NAME="CHANGEDBY" CONTENT="Steve Hawkins">
+	</STYLE>
+</HEAD>
+<BODY LANG="en-US" DIR="LTR">
+<P><A HREF="http://www.teiid.org/"><IMG SRC="https://www.jboss.org/dms/teiid/images/teiid-banner.png" NAME="graphics1" ALT="Teiid" ALIGN=BOTTOM WIDTH=800></A>
+
+<H1>Teiid ${project.version} Release Notes</H1>
+<P>Teiid ${project.version} adds performance and integration features. 
+
+<H2>Overview</H2>
+<UL>
+	<LI><A HREF="#Highlights">Highlights</A>
+	<LI><A HREF="#Compatibility">Compatibility Issues</A> 
+	<LI><A HREF="#Configuration">Configuration Issues</A> 
+	<LI><A HREF="#Other">Other Issues</A> 
+	<LI><A HREF="#LibraryUpdates">Thirdparty Library Updates</A> 
+	<LI><A HREF="#Details">Detailed Release Notes</A> 
+	<LI><A HREF="#Documentation">Additional Docs and Help</A> 
+	<LI><A HREF="#Licenses">Licenses</A> 
+	<LI><A HREF="#About">About JBoss</A> 
+</UL>
+<H2><A NAME="Highlights"></A>Highlights</H2>
+<UL>
+	<LI><B>Subquery Optimization</B> - added rewrite to INNER JOIN for applicable WHERE clause subqueries. Also added cost based SEMI and ANTI-SEMI join handling for applicable non-pushed WHERE and HAVING subqueries.
+	<LI><B>Updatable Views</B>
+	    <UL>
+	        <LI>Added support to perform simple pass-through and more complicated updates through views by default.
+	        <LI>Added support for "FOR EACH ROW" update procedure handling (similar to INSTEAD OF triggers in other DBMS's), which should be used instead of the deprecated TRANSLATE criteria approach.
+	    </UL>                     
+	<LI><B>UDF</B> - new API objects added to teiid-api to support user defined functions that are capable of pushdown to source.
+	<LI><B>Unescape Function</B> - a new system function, unescape, was added to handle common \ escaping in strings including octal, hex/unicode, \b, \r, \n, \f, and \t.
+	<LI><B>Predicate Optimization<B> - expanded optimizations for detecting always false conditions when using IS NULL, IN, or comparison predicates with literal values.
+</UL>
+
+<h2><a name="Compatibility">Compatibility Issues</a></h2>
+<ul>
+  <li>TRANSLATE/HAS CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.
+  <li>Support for named parameter syntax using param=value has been deprecated, since it is ambiguous with a comparison predicate boolean value expression.  param<b>=></b>value should be used instead.  
+</ul>
+<h4>from 7.1</h4>
+<ul>
+  <li>Subqueries are no longer allowed to be SELECT INTO.
+  <li>INSERT/UPDATE/DELETE cannot be used to create implicit return cursors in non-update virtual procedures.  You can instead use "UPDATE ...; SELECT VARIABLES.ROWCOUNT;".  
+  <li>The SYSADMIN schema was created to hold procedures and tables that should not be generally accessible.  SYS and pg_catalog are now always accessible - permissions do not apply to these schemas.  The SYS.getBinaryVDBResource, SYS.getCharacterVDBResource, and SYS.getVDBResourcePaths have been replaced with the
+ SYSADMIN.VDBResources table.  The Matviews table and the refreshMatView/refreshMatViewRow procedures were also moved into SYSADMIN.
+  <li>Overwriting an existing VDB will cause old connections to be terminated.  Production systems should rely on VDB versioning.
+  <li>The jdbc:metamatrix JDBC URL prefix is no longer accepted.  Use jdbc:teiid instead.
+  <li>Model visibility no longer restricts access to tables and procedures.  Setting visible to false will only hide entries from system tables.  Data roles should be used to restrict data access.
+  <li>Admin API "getWorkManagerStats" methods renamed to "getWorkerPoolStats". Also, "setRuntimeProperty" and "getProcesses" methods were removed.
+  <li>By default the "ENV" system function is now turned off. To enable it, edit the teiid-jboss-beans.xml configuration file.
+  <li>The use of VARIABLES.ROWCOUNT is now reserved.
+  <li>Exec statements of the form "var = EXEC foo()" are only valid if the procedure foo has a return parameter.
+  <li>Cache hint now supports "scope" definition. For ex: /* cache(scope:user) */ select * from T1; This hint will override the computed scope based on the query.  
+</ul>
+<h4>from 7.0</h4>
+<ul>
+  <li>The term data policy was replaced with data role.  The AdminAPI methods for adding role mappings have changed from addRoleToDataPolicy and removeRoleFromDataPolicy to addDataRoleMapping and removeDataRoleMapping respectively.
+</ul>
+<h4>from 6.2</h4>
+<ul>
+  <li>The connector API has changed substantially.  Custom connectors need to be retargeted to the new Translator API.  See <a href="https://jira.jboss.org/browse/TEIID-1003">TEIID-1003</a> and the <a href="teiid-docs/teiid_developers_guide.pdf">Developer's Guide</a> for more information.
+  <li>Connector bindings are no longer valid.  Use the Designer Tooling or see the AdminShell download for a migration utility.
+  <li>Calling out to web services and xml processing has been dramatically simplified and improved, but is a breaking change from prior releases.
+  XML/Relational processing has been replaced by XMLTABLE, retrieving XML from file has been replaced by the File Translator/Resource Adapter, and
+  web service calls have been replaced by the WS Translator/Resource Adapter.  See <a href="https://jira.jboss.org/browse/TEIID-1118">TEIID-1118</a>, <a href="https://jira.jboss.org/browse/TEIID-1114">TEIID-1114</a>, and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>The direct usage of XQuery has been replaced with the XMLQuery function.
+  <li>The text connector file processing has been replaced with the TEXTTABLE function.  See <a href="https://jira.jboss.org/browse/TEIID-1102">TEIID-1102</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information
+  <li>Double quoted values are now parsed as identifiers by default.  See <a href="https://jira.jboss.org/browse/TEIID-145">TEIID-145</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>The system information schema has changed from System to SYS.  The tables and table structures have also changed.  See <a href="https://jira.jboss.org/browse/TEIID-871">TEIID-871</a> and the <a href="teiid-docs/teiid_reference.pdf">Reference</a> guide for more information.
+  <li>Client control over query plans has changed.  OPTION PLANONLY, DEBUG, and SHOWPLAN are no longer allowed.  This behavior should not be controlled by the SET statement, SET SHOWPLAN (ON|OFF|DEBUG) and SET NOEXEC (ON|OFF).  Usage of the client PlanNode class will also need to be updated.   
+  <li>Teiid specific JDBC client interfaces and methods have changed.  In general these custom features have mostly been moved to other more standard locations or been removed. See <a href="https://jira.jboss.org/browse/TEIID-1020">TEIID-1020</a> and the <a href="teiid-docs/teiid_client_developers_guide.pdf">Client Developers</a> guide for more information.  
+  <li>Teiid's reserved words have changed.  Many of the Teiid specific reserved words have become non-reserved words.  All of SQL Foundation and SQL/MED 2003, and SQL/XML from SQL 2006 reserved words have been added as reserved words.  It is generally required to double quote all reserved words.  It is advisable to double quote all non-reserved words as well.  The use of the INPUT qualifier for procedure inputs has been deprecated in favor of INPUTS.  The use of the USING qualifier for dynamic SQL inputs has been deprecated in favor of DVARS.
+  <li>The AdminApi has been redesigned for use with the new Translator/JCA split and for deployment in JBoss AS.
+  <li>The AdminShell is based on Groovy.  Most BeanShell syntax is also valid in Groovy, but there are extensive changes in the AdminAPI that may necessitate rewriting scripts.
+  <li>OPTION NO CACHE &lt;table list&gt; will now only by-pass cache for the given tables at their immediate view layer.  Previously all caches would have transitively been skipped.  See <a href="https://jira.jboss.org/browse/TEIID-900">TEIID-900</a> for more information.
+  <li>Nan and +-Infinity are no longer allowed as numerical results by default.  This may be changed via the system property org.teiid.allowNanInfinity.
+  <li>The scale of BigDecimal values is now adjusted to allow for more intuitive results.  Conversion from floating numeric types will preserve the approximate scale and division results will allow for additional scale.  See <a href="https://jira.jboss.org/browse/TEIID-159">TEIID-159</a> for more information.
+  <li>The 7.0 client is not compatible with 6.x or vice versa.  It is expected that 7.0 clients will be compatible with 7.x releases for standard JDBC operations.
+</ul>
+
+<h2><a name="Configuration">Configuration Issues</a></h2>
+
+See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
+
+<h4>from 7.2</h4>
+<ul>
+  <LI>Temporary tables can now be restricted by data roles.  Use the data-role attribute allow-create-temporary-tables to explicitly enable or disable the usage of temporary tables.  
+There is also a allowCreateTemporaryTablesByDefault property in the teiid-jboss-beans.xml to control whether usage is allowed by default.  For compatibility with prior 7.x releases, the default is to allow
+temporary table access.  	
+</ul>
+
+<h4>from 7.1</h4>
+<ul>
+    <li>Teiid clients now allow the usage of anonymous SSL by default.  
+    This changes allows the admin port (default 31443) to use anonymous SSL by default, rather than just securing login traffic.  
+    Admin clients should therefore use the mms protocol instead of mm.  This will encrypt all admin traffic and ensure that any passwords in configuration files will
+    be encrypted in transit.  See the Admin Guide to upgrade from anonymous SSL to 1-way or 2-way authentication.
+    The config properties sslEnabled and clientEncryptionEnabled for SSLConfiguration beans have been combined to a single property mode, that can have the values disabled|login|enabled.
+	<li>Apache CXF is now expected to be used as the web services stack provider through JBossWS-CXF.  See the Admin Guide for instructions on 
+	installing CXF for use with Teiid's Salesforce and web service connectors.  The WS Resource Adapter's -ds.xml files should no longer use 
+	WSSecurityConfigURL and WSSecurityConfigName, rather they should be ConfigFile and ConfigName respectively.  The property values should no longer
+	refer to jboss-wsse-client.xml, but instead they should reference a CXF Spring configuration file and particular port configuration.  See the Admin Guide
+	for more on using CXF configuration files. 
+	<li>The default for data role checking is now "true".  However only VDBs with data roles will have roles enforced.
+	<li>The default prepared plan cache size was increased to 512, since it is targeted by internal plans as well.
+</ul>
+
+<h4>from 7.0</h4>
+<ul>
+    <li>The property to enable data roles in teiid-jboss-beans.xml has changed from useEntitlements to useDataRoles.
+	<li>Rar file names no longer contain version numbers.  -ds.xml files should be updated from connector-XXX-version.rar to teiid-connector-XXX.rar
+	<li>Code table relate configuration properties have been removed.  Code tables are now implemented as materialized views.
+</ul>
+
+<h4>from 6.2</h4>
+<ul>
+  <li>A JBoss AS instance is now required.  Embedded mode is also currently not supported.</li>
+  <li>Engine configuration is now handled through the admin console or deploy/teiid/teiid-jboss-beans.xml 
+  <li>Logging is now done through the container's log4j instance.  Any Teiid specific logging changes, see the conf/jboss-teiid-log4j.xml, need to be incorporated into the master jboss-log4j.xml.
+</ul>
+
+<h2><a name="Other">Other Issues</a></h2>
+<ul>
+	<li>For compatibility with the 7.0 release if a stored procedure parameter list begins with identifier=, then it will be parsed as a named parameter invocation even if the intent was to use a comparison predicate 
+	as the first parameter value.  The workaround is to use nesting parens, e.g. call proc((identifier=value), ...), which clarifies that this is positional value.  This workaround will not be needed in later releases.  
+</ul>
+<h4>from 7.0</h4>
+<ul>
+  <li>Fixed xsd type handling for SQL/XML and XML document models.  xsd:date, xsd:dateTime, and xsd:time types will now all be displayed using the GMT timezone (Z).  SQL types, such as timestamp, used for an XMLTABLE column will now expect their values to be in the form of the corresponding xsd type.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+  <li>Start time is now significantly longer due to the container deployment.  However many operations can be performed on configruation files that will trigger a redeployment without the need for a restart.
+  <li>Inversion of parse, format, and convert system functions is not used if it can be narrowing.  In situations where a predicate has the form: parseTime(column, 'format') = {t 'time value'} may lead to reduced performance, since
+      the parseTime function cannot be pushed down.  This should be addressed in future releases.   
+</ul>
+
+<h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
+
+The following components have been updated:
+<h4>From 7.1</h4>
+<ul>
+    <li>json-simple 1.1 was added.
+	<li>Netty was upgraded to 3.2.1	
+</ul>
+<h4>From 7.0</h4>
+<ul>
+	<li>Direct integration of JBossCache jars was removed.
+	<li>Netty was upgraded to 3.2.0	
+	<li>JDOM was removed.
+</ul>
+<h4>From 6.2</h4>
+<ul>
+	<li>Netty was upgraded to 3.1.5
+	<li>Saxon was upgraded to 9.1.0.8
+    <li>A 5.1 container's version of Arjuna is newer than what was previously included in Teiid 6.x.
+	<li>Various other dependencies have been removed as they are no longer needed or now provided by the container.
+</ul> 
+
+<h2><a name="Details">Detailed Release Notes</a></h2>
+        Detailed Release Notes - Teiid - Version ${project.version}
+    
+<h2><a name="Documentation">Documentation and Help</a></h2>
+
+The <a href="http://www.jboss.org/teiid/">Teiid community project</a> is hosted on jboss.org.
+Documentation and help may be obtained from the local distribution under <a href="teiid-docs">teiid-docs</a> or the following locations.
+<ul>
+
+<li><a href="http://www.jboss.org/teiid/docs">Online Documentation</a></li>
+<li><a href="https://community.jboss.org/wiki/TheTeiidProject">Wiki</a></li>
+<li><a href="http://jira.jboss.org/jira/browse/TEIID">JIRA</a></li>
+<li><a href="http://community.jboss.org/en/teiid?view=discussions">Forums</a></li>
+</ul>
+
+
+<h2><a name="Licenses">Licenses</a></h2>
+
+<p>Teiid is licensed under the <a href="LICENSE-lgpl-2.1.txt">LGPL</a>. The
+license texts for Teiid and the thirdparty components it uses may be found in the teiid-docs/licenses
+directory of the distribution. <a href="teiid-docs/licenses">Browse
+Licenses</a>
+
+</p>
+
+<h2><a name="About">About JBoss, a
+division of Red Hat</a></h2>
+
+<p>JBoss, a division of <a href="http://www.redhat.com/jboss/">Red
+Hat</a>, is in the business of
+providing
+superior technical support to our customers. Our goal is to make
+Professional Open Source&trade; the <b>SAFE
+CHOICE</b>
+for you. We accomplish this by backing up our open source Java products
+with technical support services that are delivered by the core
+developers themselves. We can help you to train your staff and provide
+you with support at every stage of the application lifecycle - from
+development and integration through deployment and maintenance. Visit
+the <a href="http://www.jboss.com/services/index">JBoss
+Services</a> page for more
+information.</p>
+
+</BODY>
+</HTML>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/build/pom.xml
===================================================================
--- trunk/build/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/build/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/build/pom.xml (from rev 2777, trunk/build/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/build/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/build/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/cache-jbosscache/pom.xml
===================================================================
--- trunk/cache-jbosscache/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/cache-jbosscache/pom.xml (from rev 2777, trunk/cache-jbosscache/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java
===================================================================
--- trunk/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,121 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.cache.jboss;
-
-import java.io.Serializable;
-
-import org.jboss.cache.CacheManager;
-import org.jboss.cache.Fqn;
-import org.jboss.cache.Node;
-import org.jboss.cache.Region;
-import org.jboss.cache.config.EvictionAlgorithmConfig;
-import org.jboss.cache.config.EvictionRegionConfig;
-import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
-import org.jboss.cache.eviction.LRUAlgorithmConfig;
-import org.jboss.cache.eviction.RemoveOnEvictActionPolicy;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.Cache.Type;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.core.TeiidRuntimeException;
-
-
-public class JBossCacheFactory implements CacheFactory, Serializable{
-	private static final long serialVersionUID = -2767452034178675653L;
-	private transient org.jboss.cache.Cache cacheStore;
-	private volatile boolean destroyed = false;
-	
-
-	public JBossCacheFactory(String name, Object cm) throws Exception {
-		CacheManager cachemanager = (CacheManager)cm;
-		this.cacheStore = cachemanager.getCache(name, true);
-	}
-	
-	/**
-	 * {@inheritDoc}
-	 */
-	public Cache get(Type type, CacheConfiguration config) {
-		if (!destroyed) {
-			
-			if (!this.cacheStore.getCacheStatus().allowInvocations()) {
-				this.cacheStore.start();
-			}
-			
-			Node cacheRoot = this.cacheStore.getRoot().addChild(Fqn.fromString("Teiid")); //$NON-NLS-1$
-			Node node = cacheRoot.addChild(Fqn.fromString(type.location()));
-			node.put(ExpirationAlgorithmConfig.EXPIRATION_KEY, Long.MAX_VALUE);
-			node.setResident(true);
-			
-			Region cacheRegion = this.cacheStore.getRegion(node.getFqn(), true);
-			cacheRegion.setEvictionRegionConfig(buildEvictionConfig(node.getFqn(), config));
-						
-			JBossCache jc = null;
-			if (config != null && config.getPolicy().equals(Policy.EXPIRATION)) {
-				jc = new ExpirationAwareCache(this.cacheStore, node.getFqn());
-			}
-			else {
-				jc = new JBossCache(this.cacheStore, node.getFqn());	
-			}
-			
-			jc.setCacheConfiguration(config);
-			return jc;
-		}
-		throw new TeiidRuntimeException("Cache system has been shutdown"); //$NON-NLS-1$
-	}
-	
-	private EvictionRegionConfig  buildEvictionConfig(Fqn rootFqn, CacheConfiguration config) {
-		EvictionAlgorithmConfig  evictionConfig = null;
-		
-		if (config.getPolicy() == Policy.LRU) {
-			LRUAlgorithmConfig lru = new LRUAlgorithmConfig();
-			lru.setMaxNodes(config.getMaxEntries());
-			lru.setMaxAge(config.getMaxAgeInSeconds()*1000);
-			lru.setTimeToLive(-1); // -1 no limit
-			evictionConfig = lru;
-		}
-		else if (config.getPolicy() == Policy.EXPIRATION) {
-			ExpirationAlgorithmConfig lfu  = new ExpirationAlgorithmConfig();
-			lfu.setMaxNodes(config.getMaxEntries());
-			evictionConfig = lfu;
-		}
-		
-		EvictionRegionConfig erc = new EvictionRegionConfig(rootFqn, evictionConfig);
-		erc.setEvictionActionPolicyClassName(RemoveOnEvictActionPolicy.class.getName());
-		return erc;
-	}	
-	
-	public void destroy() {
-		this.destroyed = true;		
-	}	
-	
-	// this will be called by microcontainer.
-	public void stop() {
-		destroy();
-	}
-	
-	@Override
-	public boolean isReplicated() {
-		return true;
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java (from rev 2774, trunk/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,120 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.cache.jboss;
+
+import java.io.Serializable;
+
+import org.jboss.cache.CacheManager;
+import org.jboss.cache.Fqn;
+import org.jboss.cache.Node;
+import org.jboss.cache.Region;
+import org.jboss.cache.config.EvictionAlgorithmConfig;
+import org.jboss.cache.config.EvictionRegionConfig;
+import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
+import org.jboss.cache.eviction.LRUAlgorithmConfig;
+import org.jboss.cache.eviction.RemoveOnEvictActionPolicy;
+import org.teiid.cache.Cache;
+import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheFactory;
+import org.teiid.cache.Cache.Type;
+import org.teiid.cache.CacheConfiguration.Policy;
+import org.teiid.core.TeiidRuntimeException;
+
+
+public class JBossCacheFactory implements CacheFactory, Serializable{
+	private static final long serialVersionUID = -2767452034178675653L;
+	private transient org.jboss.cache.Cache cacheStore;
+	private volatile boolean destroyed = false;
+	
+
+	public JBossCacheFactory(String name, Object cm) throws Exception {
+		CacheManager cachemanager = (CacheManager)cm;
+		this.cacheStore = cachemanager.getCache(name, true);
+	}
+	
+	/**
+	 * {@inheritDoc}
+	 */
+	public Cache get(Type type, CacheConfiguration config) {
+		if (!destroyed) {
+			
+			if (!this.cacheStore.getCacheStatus().allowInvocations()) {
+				this.cacheStore.start();
+			}
+			
+			Node cacheRoot = this.cacheStore.getRoot().addChild(Fqn.fromString("Teiid")); //$NON-NLS-1$
+			Node node = cacheRoot.addChild(Fqn.fromString(type.location()));
+			node.setResident(true);
+			
+			Region cacheRegion = this.cacheStore.getRegion(node.getFqn(), true);
+			cacheRegion.setEvictionRegionConfig(buildEvictionConfig(node.getFqn(), config));
+						
+			JBossCache jc = null;
+			if (config != null && config.getPolicy().equals(Policy.EXPIRATION)) {
+				jc = new ExpirationAwareCache(this.cacheStore, node.getFqn());
+			}
+			else {
+				jc = new JBossCache(this.cacheStore, node.getFqn());	
+			}
+			
+			jc.setCacheConfiguration(config);
+			return jc;
+		}
+		throw new TeiidRuntimeException("Cache system has been shutdown"); //$NON-NLS-1$
+	}
+	
+	private EvictionRegionConfig  buildEvictionConfig(Fqn rootFqn, CacheConfiguration config) {
+		EvictionAlgorithmConfig  evictionConfig = null;
+		
+		if (config.getPolicy() == Policy.LRU) {
+			LRUAlgorithmConfig lru = new LRUAlgorithmConfig();
+			lru.setMaxNodes(config.getMaxEntries());
+			lru.setMaxAge(config.getMaxAgeInSeconds()*1000);
+			lru.setTimeToLive(-1); // -1 no limit
+			evictionConfig = lru;
+		}
+		else if (config.getPolicy() == Policy.EXPIRATION) {
+			ExpirationAlgorithmConfig lfu  = new ExpirationAlgorithmConfig();
+			lfu.setMaxNodes(config.getMaxEntries());
+			evictionConfig = lfu;
+		}
+		
+		EvictionRegionConfig erc = new EvictionRegionConfig(rootFqn, evictionConfig);
+		erc.setEvictionActionPolicyClassName(RemoveOnEvictActionPolicy.class.getName());
+		return erc;
+	}	
+	
+	public void destroy() {
+		this.destroyed = true;		
+	}	
+	
+	// this will be called by microcontainer.
+	public void stop() {
+		destroy();
+	}
+	
+	@Override
+	public boolean isReplicated() {
+		return true;
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/pom.xml
===================================================================
--- trunk/client/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/client/pom.xml (from rev 2777, trunk/client/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/Admin.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,281 +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.adminapi;
-
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.Properties;
-import java.util.Set;
-
-import org.teiid.adminapi.VDB.ConnectionType;
-
-public interface Admin {
-
-	public enum Cache {PREPARED_PLAN_CACHE, QUERY_SERVICE_RESULT_SET_CACHE};
-    
-    /**
-     * Assign a {@link Translator} and Data source to a {@link VDB}'s Model
-     *
-     * @param vdbName Name of the VDB
-     * @param vdbVersion Version of the VDB
-     * @param modelName  Name of the Model to map Connection Factory
-     * @param sourceName sourceName for the model
-     * @param translatorName 
-     * @param dsName data source name that can found in the JNDI map.
-     * @throws AdminException
-     */
-    void assignToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String translatorName, String dsName) throws AdminException;
-    
-    /**
-     * Change the {@link ConnectionType} of the {@link VDB}.
-     * @param vdbName Name of the VDB
-     * @param vdbVersion Version of the VDB
-     * @param type
-     * @throws AdminException 
-     */
-    void changeVDBConnectionType(String vdbName, int vdbVersion, ConnectionType type) throws AdminException;
-    
-    /**
-     * Deploy a {@link VDB} file.
-     * @param name  Name of the VDB file to save under
-     * @param VDB 	VDB.
-     * @throws AdminException
-     *             
-     * @return the {@link VDB} representing the current property values and runtime state.
-     */
-    public void deployVDB(String fileName, InputStream vdb) throws AdminException;
-    
-    
-    /**
-     * Delete the VDB with the given name and version
-     * @param vdbName
-     * @param version
-     * @throws AdminException
-     */
-    void deleteVDB(String vdbName, int vdbVersion) throws AdminException;
-    
-    /**
-     * Get the VDBs that currently deployed in the system
-     *
-     * @return Collection of {@link VDB}s.  There could be multiple VDBs with the
-     * same name in the Collection but they will differ by VDB version.
-     * @throws AdminException 
-     */
-    Set<VDB> getVDBs() throws AdminException;
-    
-    /**
-     * Get the VDB
-     * @param vdbName
-     * @param vbdVersion
-     * @throws AdminException 
-     * @return
-     */
-    VDB getVDB(String vdbName, int vbdVersion) throws AdminException;
-
-    /**
-     * Get the translators that are available in the configuration
-     *
-     * @return Collection of {@link Translator}
-     * @throws AdminException 
-     */
-    Collection<Translator> getTranslators() throws AdminException;
-    
-    /**
-     * Get the translator by the given the deployed name.
-     * @param deployedName - name of the deployed translator
-     * @return null if not found
-     * @throws AdminException 
-     */
-    Translator getTranslator(String deployedName) throws AdminException;
-
-    /**
-     * Get the Worker Pool statistics in runtime engine.
-     *
-     * @return {@link WorkerPoolStatistics}
-     * @throws AdminException 
-     */
-    WorkerPoolStatistics getWorkerPoolStats() throws AdminException;
-    
-    /**
-     * Get the Caches that correspond to the specified identifier pattern
-     * @return Collection of {@link String}
-     * @throws AdminException 
-     */
-    Collection<String> getCacheTypes() throws AdminException;
-
-    /**
-     * Get all the current Sessions.
-     * @return Collection of {@link Session}
-     * @throws AdminException 
-     */
-    Collection<Session> getSessions() throws AdminException;
-
-    /**
-     * Get the all Requests that are currently in process
-     * @return Collection of {@link Request}
-     * @throws AdminException 
-     */
-    Collection<Request> getRequests() throws AdminException;
-    
-    /**
-     * Get the Requests for the given session
-     * @return Collection of {@link Request}
-     * @throws AdminException 
-     */
-    Collection<Request> getRequestsForSession(String sessionId) throws AdminException;
-    
-
-    /**
-     * Get all of the available configuration Properties for the specified connector
-     * @param templateName - Name of the connector
-     * @return
-     * @throws AdminException
-     */
-    Collection<PropertyDefinition> getTemplatePropertyDefinitions(String templateName) throws AdminException;
-    
-    
-    /**
-     * Get all transaction matching the identifier.
-     * @return
-     * @throws AdminException
-     */
-    Collection<Transaction> getTransactions() throws AdminException;
-    
-    /**
-     * Clear the cache or caches specified by the cacheIdentifier.
-     * @param cacheType Cache Type
-     * No wild cards currently supported, must be explicit
-     * @throws AdminException  
-     */
-    void clearCache(String cacheType) throws AdminException;
-
-    
-    /**
-     * Get the Cache Statistics for the given type
-     * @param cacheType Cache Type
-     * @return {@link CacheStatistics} 
-     * @throws AdminException  
-     */
-    CacheStatistics getCacheStats(String cacheType) throws AdminException;
-    
-    /**
-     * Terminate the Session
-     *
-     * @param identifier  Session Identifier {@link org.teiid.adminapi.Session}.
-     * No wild cards currently supported, must be explicit
-     * @throws AdminException  
-     */
-    void terminateSession(String sessionId) throws AdminException;
-
-    /**
-     * Cancel Request
-     *
-     * @param sessionId session Identifier for the request.
-     * @param executionId request Identifier
-     * 
-     * @throws AdminException  
-     */
-    void cancelRequest(String sessionId, long executionId) throws AdminException;
-  
-    /**
-     * Mark the given global transaction as rollback only.
-     * @param transactionId
-     * @throws AdminException
-     */
-    void terminateTransaction(String transactionId) throws AdminException;
-    
-    /**
-     * Closes the admin connection
-     */
-    void close();
-    
-    /**
-     * Assign a Role name to the Data Role in a given VDB
-     *  
-     * @param vdbName
-     * @param vdbVersion
-     * @param dataRole
-     * @param mappedRoleName
-     */
-    void addDataRoleMapping(String vdbName, int vdbVersion, String dataRole, String mappedRoleName) throws AdminException;
-    
-    /**
-     * Remove a Role name to the Data Role in a given VDB
-     *  
-     * @param vdbName
-     * @param vdbVersion
-     * @param dataRole
-     * @param mappedRoleName
-     */
-    void removeDataRoleMapping(String vdbName, int vdbVersion, String dataRole, String mappedRoleName) throws AdminException;
-    
-    /**
-     * Set the any authenticated flag on the Data Role in a given VDB
-     *  
-     * @param vdbName
-     * @param vdbVersion
-     * @param dataRole
-     * @param anyAuthenticated
-     */
-    void setAnyAuthenticatedForDataRole(String vdbName, int vdbVersion, String dataRole, boolean anyAuthenticated) throws AdminException;
-    
-    /**
-     * Merge the Source VDB into Target VDB. Both Source and Target VDBs must be present for this method to
-     * succeed. The changes will not be persistent between server restarts.
-     * @param sourceVDBName
-     * @param sourceVDBVersion
-     * @param targetVDBName
-     * @param targetVDBVersion
-     */
-    void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException;
-
-    
-    /**
-     * Creates a JCA data source
-     * @param deploymentName - name of the source
-     * @param templateName - template of data source
-     * @param properties - properties
-     * @throws AdminException
-     */
-    void createDataSource(String deploymentName, String templateName, Properties properties) throws AdminException;
-    
-    /**
-     * Delete data source. 
-     * @param deployedName
-     * @throws AdminException
-     */
-    void deleteDataSource(String deployedName) throws AdminException;
-    
-    /**
-     * Returns the all names of all the data sources available in the configuration.
-     */
-    Collection<String> getDataSourceNames() throws AdminException;
-    
-    /**
-     * Get the Datasource templates  available in the configuration.
-     *
-     * @return Set of template names.
-     * @throws AdminException 
-     */
-    Set<String> getDataSourceTemplateNames() throws AdminException;
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java (from rev 2774, trunk/client/src/main/java/org/teiid/adminapi/Admin.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/Admin.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,291 @@
+/*
+ * 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.adminapi;
+
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.Properties;
+import java.util.Set;
+
+import org.teiid.adminapi.VDB.ConnectionType;
+
+public interface Admin {
+
+	public enum Cache {PREPARED_PLAN_CACHE, QUERY_SERVICE_RESULT_SET_CACHE};
+    
+    /**
+     * Assign a {@link Translator} and Data source to a {@link VDB}'s Model
+     *
+     * @param vdbName Name of the VDB
+     * @param vdbVersion Version of the VDB
+     * @param modelName  Name of the Model to map Connection Factory
+     * @param sourceName sourceName for the model
+     * @param translatorName 
+     * @param dsName data source name that can found in the JNDI map.
+     * @throws AdminException
+     */
+    void assignToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String translatorName, String dsName) throws AdminException;
+    
+    /**
+     * Change the {@link ConnectionType} of the {@link VDB}.
+     * @param vdbName Name of the VDB
+     * @param vdbVersion Version of the VDB
+     * @param type
+     * @throws AdminException 
+     */
+    void changeVDBConnectionType(String vdbName, int vdbVersion, ConnectionType type) throws AdminException;
+    
+    /**
+     * Deploy a {@link VDB} file.
+     * @param name  Name of the VDB file to save under
+     * @param VDB 	VDB.
+     * @throws AdminException
+     *             
+     * @return the {@link VDB} representing the current property values and runtime state.
+     */
+    public void deployVDB(String fileName, InputStream vdb) throws AdminException;
+    
+    
+    /**
+     * Delete the VDB with the given name and version
+     * @param vdbName
+     * @param version
+     * @throws AdminException
+     */
+    void deleteVDB(String vdbName, int vdbVersion) throws AdminException;
+    
+    /**
+     * Get the VDBs that currently deployed in the system
+     *
+     * @return Collection of {@link VDB}s.  There could be multiple VDBs with the
+     * same name in the Collection but they will differ by VDB version.
+     * @throws AdminException 
+     */
+    Set<VDB> getVDBs() throws AdminException;
+    
+    /**
+     * Get the VDB
+     * @param vdbName
+     * @param vbdVersion
+     * @throws AdminException 
+     * @return
+     */
+    VDB getVDB(String vdbName, int vbdVersion) throws AdminException;
+
+    /**
+     * Get the translators that are available in the configuration
+     *
+     * @return Collection of {@link Translator}
+     * @throws AdminException 
+     */
+    Collection<Translator> getTranslators() throws AdminException;
+    
+    /**
+     * Get the translator by the given the deployed name.
+     * @param deployedName - name of the deployed translator
+     * @return null if not found
+     * @throws AdminException 
+     */
+    Translator getTranslator(String deployedName) throws AdminException;
+
+    /**
+     * Get the Worker Pool statistics in runtime engine.
+     *
+     * @return {@link WorkerPoolStatistics}
+     * @throws AdminException 
+     */
+    WorkerPoolStatistics getWorkerPoolStats() throws AdminException;
+    
+    /**
+     * Get the Caches that correspond to the specified identifier pattern
+     * @return Collection of {@link String}
+     * @throws AdminException 
+     */
+    Collection<String> getCacheTypes() throws AdminException;
+
+    /**
+     * Get all the current Sessions.
+     * @return Collection of {@link Session}
+     * @throws AdminException 
+     */
+    Collection<Session> getSessions() throws AdminException;
+
+    /**
+     * Get the all Requests that are currently in process
+     * @return Collection of {@link Request}
+     * @throws AdminException 
+     */
+    Collection<Request> getRequests() throws AdminException;
+    
+    /**
+     * Get the Requests for the given session
+     * @return Collection of {@link Request}
+     * @throws AdminException 
+     */
+    Collection<Request> getRequestsForSession(String sessionId) throws AdminException;
+    
+
+    /**
+     * Get all of the available configuration Properties for the specified connector
+     * @param templateName - Name of the connector
+     * @return
+     * @throws AdminException
+     */
+    Collection<PropertyDefinition> getTemplatePropertyDefinitions(String templateName) throws AdminException;
+    
+    
+    /**
+     * Get all transaction matching the identifier.
+     * @return
+     * @throws AdminException
+     */
+    Collection<Transaction> getTransactions() throws AdminException;
+    
+    /**
+     * Clear the cache or caches specified by the cacheIdentifier.
+     * @param cacheType Cache Type
+     * No wild cards currently supported, must be explicit
+     * @throws AdminException  
+     */
+    void clearCache(String cacheType) throws AdminException;
+    
+    /**
+     * Clear the cache of the given VDB for provided cache type
+     * @param cacheType Cache Type
+     * No wild cards currently supported, must be explicit
+     * @param vdbName - Name of the VDB
+     * @param vdbVersion - VDB version
+     * @throws AdminException  
+     */
+    void clearCache(String cacheType, String vdbName, int vdbVersion) throws AdminException;    
+
+    
+    /**
+     * Get the Cache Statistics for the given type
+     * @param cacheType Cache Type
+     * @return {@link CacheStatistics} 
+     * @throws AdminException  
+     */
+    CacheStatistics getCacheStats(String cacheType) throws AdminException;
+    
+    /**
+     * Terminate the Session
+     *
+     * @param identifier  Session Identifier {@link org.teiid.adminapi.Session}.
+     * No wild cards currently supported, must be explicit
+     * @throws AdminException  
+     */
+    void terminateSession(String sessionId) throws AdminException;
+
+    /**
+     * Cancel Request
+     *
+     * @param sessionId session Identifier for the request.
+     * @param executionId request Identifier
+     * 
+     * @throws AdminException  
+     */
+    void cancelRequest(String sessionId, long executionId) throws AdminException;
+  
+    /**
+     * Mark the given global transaction as rollback only.
+     * @param transactionId
+     * @throws AdminException
+     */
+    void terminateTransaction(String transactionId) throws AdminException;
+    
+    /**
+     * Closes the admin connection
+     */
+    void close();
+    
+    /**
+     * Assign a Role name to the Data Role in a given VDB
+     *  
+     * @param vdbName
+     * @param vdbVersion
+     * @param dataRole
+     * @param mappedRoleName
+     */
+    void addDataRoleMapping(String vdbName, int vdbVersion, String dataRole, String mappedRoleName) throws AdminException;
+    
+    /**
+     * Remove a Role name to the Data Role in a given VDB
+     *  
+     * @param vdbName
+     * @param vdbVersion
+     * @param dataRole
+     * @param mappedRoleName
+     */
+    void removeDataRoleMapping(String vdbName, int vdbVersion, String dataRole, String mappedRoleName) throws AdminException;
+    
+    /**
+     * Set the any authenticated flag on the Data Role in a given VDB
+     *  
+     * @param vdbName
+     * @param vdbVersion
+     * @param dataRole
+     * @param anyAuthenticated
+     */
+    void setAnyAuthenticatedForDataRole(String vdbName, int vdbVersion, String dataRole, boolean anyAuthenticated) throws AdminException;
+    
+    /**
+     * Merge the Source VDB into Target VDB. Both Source and Target VDBs must be present for this method to
+     * succeed. The changes will not be persistent between server restarts.
+     * @param sourceVDBName
+     * @param sourceVDBVersion
+     * @param targetVDBName
+     * @param targetVDBVersion
+     */
+    void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException;
+
+    
+    /**
+     * Creates a JCA data source
+     * @param deploymentName - name of the source
+     * @param templateName - template of data source
+     * @param properties - properties
+     * @throws AdminException
+     */
+    void createDataSource(String deploymentName, String templateName, Properties properties) throws AdminException;
+    
+    /**
+     * Delete data source. 
+     * @param deployedName
+     * @throws AdminException
+     */
+    void deleteDataSource(String deployedName) throws AdminException;
+    
+    /**
+     * Returns the all names of all the data sources available in the configuration.
+     */
+    Collection<String> getDataSourceNames() throws AdminException;
+    
+    /**
+     * Get the Datasource templates  available in the configuration.
+     *
+     * @return Set of template names.
+     * @throws AdminException 
+     */
+    Set<String> getDataSourceTemplateNames() throws AdminException;
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/DataPolicy.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.adminapi;
-
-import java.util.List;
-
-public interface DataPolicy {
-	
-	public enum PermissionType {CREATE, READ, UPDATE, DELETE};
-	
-	/**
-	 * Get the Name of the Data Policy
-	 * @return
-	 */
-	String getName();
-	
-	/**
-	 * Get the description of the Data Policy
-	 * @return
-	 */
-	String getDescription();
-	
-	/**
-	 * Get the List of Permissions for this Data Policy.
-	 * @return
-	 */
-	List<DataPermission> getPermissions();
-	
-	/**
-	 * Mapped Container Role names for this Data Policy
-	 * @return
-	 */
-	List<String> getMappedRoleNames();
-	
-	boolean isAnyAuthenticated();
-	
-	interface DataPermission {
-		/**
-		 * Get the Resource Name that Data Permission representing
-		 * @return
-		 */
-		String getResourceName();
-		
-		/**
-		 * Is "CREATE" allowed?
-		 * @return
-		 */
-		Boolean getAllowCreate();
-		
-		/**
-		 * Is "SELECT" allowed?
-		 * @return
-		 */
-		Boolean getAllowRead();
-		
-		/**
-		 * Is "INSERT/UPDATE" allowed?
-		 * @return
-		 */
-		Boolean getAllowUpdate();
-		
-		/**
-		 * Is "DELETE" allowed?
-		 * @return
-		 */
-		Boolean getAllowDelete();		
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java (from rev 2765, trunk/client/src/main/java/org/teiid/adminapi/DataPolicy.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/DataPolicy.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,97 @@
+/*
+ * 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.adminapi;
+
+import java.util.List;
+
+public interface DataPolicy {
+	
+	public enum PermissionType {CREATE, READ, UPDATE, DELETE};
+	
+	/**
+	 * Get the Name of the Data Policy
+	 * @return
+	 */
+	String getName();
+	
+	/**
+	 * Get the description of the Data Policy
+	 * @return
+	 */
+	String getDescription();
+	
+	/**
+	 * Get the List of Permissions for this Data Policy.
+	 * @return
+	 */
+	List<DataPermission> getPermissions();
+	
+	/**
+	 * Mapped Container Role names for this Data Policy
+	 * @return
+	 */
+	List<String> getMappedRoleNames();
+	
+	/**
+	 * If the policy applies to any authenticated user
+	 * @return
+	 */
+	boolean isAnyAuthenticated();
+	
+	/**
+	 * If the policy allows for temporary table usage
+	 * @return
+	 */
+	Boolean isAllowCreateTemporaryTables();
+	
+	interface DataPermission {
+		/**
+		 * Get the Resource Name that Data Permission representing
+		 * @return
+		 */
+		String getResourceName();
+		
+		/**
+		 * Is "CREATE" allowed?
+		 * @return
+		 */
+		Boolean getAllowCreate();
+		
+		/**
+		 * Is "SELECT" allowed?
+		 * @return
+		 */
+		Boolean getAllowRead();
+		
+		/**
+		 * Is "INSERT/UPDATE" allowed?
+		 * @return
+		 */
+		Boolean getAllowUpdate();
+		
+		/**
+		 * Is "DELETE" allowed?
+		 * @return
+		 */
+		Boolean getAllowDelete();		
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,47 +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.adminapi.impl;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.teiid.adminapi.AdminException;
-
-
-public interface DQPManagement {
-    List<RequestMetadata> getRequestsForSession(String sessionId) ;
-    List<RequestMetadata> getRequests();
-    WorkerPoolStatisticsMetadata getWorkerPoolStatistics();
-    void terminateSession(String terminateeId);
-    boolean cancelRequest(String sessionId, long requestId) throws AdminException;
-    Collection<String> getCacheTypes();
-    void clearCache(String cacheType);
-    Collection<SessionMetadata> getActiveSessions() throws AdminException;
-    int getActiveSessionsCount() throws AdminException;
-    Collection<org.teiid.adminapi.Transaction> getTransactions();
-    void terminateTransaction(String xid) throws AdminException ;
-    void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException;
-    List<RequestMetadata> getLongRunningRequests();
-    List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException;
-    CacheStatisticsMetadata getCacheStatistics(String cacheType);
-    List<List> executeQuery(String vdbName, int version, String command, long timoutInMilli) throws AdminException;
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java (from rev 2774, trunk/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DQPManagement.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,48 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.adminapi.impl;
+
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.adminapi.AdminException;
+
+
+public interface DQPManagement {
+    List<RequestMetadata> getRequestsForSession(String sessionId) ;
+    List<RequestMetadata> getRequests();
+    WorkerPoolStatisticsMetadata getWorkerPoolStatistics();
+    void terminateSession(String terminateeId);
+    boolean cancelRequest(String sessionId, long requestId) throws AdminException;
+    Collection<String> getCacheTypes();
+    void clearCache(String cacheType);
+    void clearCache(String cacheType, String vdbName, int version);
+    Collection<SessionMetadata> getActiveSessions() throws AdminException;
+    int getActiveSessionsCount() throws AdminException;
+    Collection<org.teiid.adminapi.Transaction> getTransactions();
+    void terminateTransaction(String xid) throws AdminException ;
+    void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException;
+    List<RequestMetadata> getLongRunningRequests();
+    List<RequestMetadata> getRequestsUsingVDB(String vdbName, int vdbVersion) throws AdminException;
+    CacheStatisticsMetadata getCacheStatistics(String cacheType);
+    List<List> executeQuery(String vdbName, int version, String command, long timoutInMilli) throws AdminException;
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,267 +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.adminapi.impl;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
-
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementObjectID;
-import org.jboss.managed.api.annotation.ManagementProperties;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.adminapi.DataPolicy;
-
-
- at XmlAccessorType(XmlAccessType.NONE)
- at XmlType(name = "", propOrder = {
-    "description",
-    "permissions",
-    "mappedRoleNames"
-})
- at ManagementObject(properties=ManagementProperties.EXPLICIT)
-public class DataPolicyMetadata implements DataPolicy, Serializable {
-	private static final long serialVersionUID = -4119646357275977190L;
-	
-	@XmlAttribute(name = "name", required = true)
-    protected String name;
-	@XmlElement(name = "description")
-    protected String description;
-	@XmlAttribute(name = "any-authenticated")
-	protected boolean anyAuthenticated;
-
-    @XmlElement(name = "permission")
-    protected PermissionMap permissions = new PermissionMap(new KeyBuilder<PermissionMetaData>() {
-		private static final long serialVersionUID = -6992984146431492449L;
-		@Override
-		public String getKey(PermissionMetaData entry) {
-			return entry.getResourceName().toLowerCase();
-		}
-	});
-    
-    @XmlElement(name = "mapped-role-name")
-    protected List<String> mappedRoleNames = new ArrayList<String>();
-
-	@Override
-	@ManagementProperty(description="Policy Name")
-	@ManagementObjectID(type="policy")
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String value) {
-        this.name = value;
-    }
-    
-    @Override
-    @ManagementProperty(description="Policy Description")
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String value) {
-        this.description = value;
-    }
-
-	@Override
-	@ManagementProperty(description="Permissions in a Data Policy", managed=true)
-	public List<DataPermission> getPermissions() {
-		return new ArrayList<DataPermission>(this.permissions.getMap().values());
-	}
-	
-	public void setPermissions(List<DataPermission> permissions) {
-		this.permissions.getMap().clear();
-		for (DataPermission permission:permissions) {
-			this.permissions.add((PermissionMetaData)permission);
-		}
-	}	
-	
-	public void addPermission(PermissionMetaData... permissions) {
-		for (PermissionMetaData permission:permissions) {
-			this.permissions.add(permission);
-		}
-	}
-	
-    @Override
-    @ManagementProperty(description="Mapped Container role names mapped to this policy")    
-    public List<String> getMappedRoleNames() {
-		return mappedRoleNames;
-	}
-
-	public void setMappedRoleNames(List<String> names) {
-		this.mappedRoleNames.clear();
-		this.mappedRoleNames.addAll(names);
-	}    
-	
-	public void addMappedRoleName(String name) {
-		this.mappedRoleNames.add(name);
-	}  	
-	
-	public boolean allows(String resourceName, DataPolicy.PermissionType type) {
-		resourceName = resourceName.toLowerCase();
-		while (resourceName.length() > 0) {
-			PermissionMetaData p = this.permissions.getMap().get(resourceName);
-			if (p != null) {
-				Boolean allowed = p.allows(type);
-				if (allowed != null) {
-					return allowed;
-				}
-			}
-			resourceName = resourceName.substring(0, Math.max(0, resourceName.lastIndexOf('.')));
-		}
-		return false;
-	}
-	
-	
-    @XmlAccessorType(XmlAccessType.NONE)
-    @XmlType(name = "", propOrder = {
-        "resourceName",
-        "allowCreate",
-        "allowRead",
-        "allowUpdate",
-        "allowDelete"
-    })	
-    @ManagementObject(properties=ManagementProperties.EXPLICIT)
-	public static class PermissionMetaData implements DataPermission, Serializable {
-		private static final long serialVersionUID = 7034744531663164277L;
-        
-        // XML based fields
-        private String resourceName;
-        @XmlElement(name = "allow-create")
-        protected Boolean allowCreate;
-        @XmlElement(name = "allow-read")
-        protected Boolean allowRead;
-        @XmlElement(name = "allow-update")
-        protected Boolean allowUpdate;
-        @XmlElement(name = "allow-delete")
-        protected Boolean allowDelete;
-        
-        @Override
-        @ManagementProperty(description="Resource Name, for which permission defined")
-        //@ManagementObjectID(type="permission")
-        @XmlElement(name = "resource-name", required = true)
-        public String getResourceName() {
-            return resourceName;
-        }
-
-        public void setResourceName(String value) {
-            this.resourceName = value;
-        }
-
-        @Override
-        @ManagementProperty(description="Allows Create")
-        public Boolean getAllowCreate() {
-            return allowCreate;
-        }
-
-        public void setAllowCreate(Boolean value) {
-            this.allowCreate = value;
-        }
-
-        @Override
-        @ManagementProperty(description="Allows Read")
-        public Boolean getAllowRead() {
-            return allowRead;
-        }
-
-        public void setAllowRead(Boolean value) {
-            this.allowRead = value;
-        }
-
-        @Override
-        @ManagementProperty(description="Allows Update")
-        public Boolean getAllowUpdate() {
-            return allowUpdate;
-        }
-
-        public void setAllowUpdate(Boolean value) {
-            this.allowUpdate = value;
-        }
-
-        @Override
-        @ManagementProperty(description="Allows Delete")
-        public Boolean getAllowDelete() {
-            return allowDelete;
-        }
-
-        public void setAllowDelete(Boolean value) {
-            this.allowDelete = value;
-        }
-        
-        public String getType() {
-        	StringBuilder sb = new StringBuilder();
-        	if (Boolean.TRUE.equals(getAllowCreate())) {
-        		sb.append("C");//$NON-NLS-1$
-        	}
-        	if (Boolean.TRUE.equals(getAllowRead())) {
-        		sb.append("R");//$NON-NLS-1$
-        	}
-        	if (Boolean.TRUE.equals(getAllowUpdate())) {
-        		sb.append("U");//$NON-NLS-1$
-        	}
-        	if (Boolean.TRUE.equals(getAllowDelete())) {
-        		sb.append("D");//$NON-NLS-1$
-        	}     
-        	return sb.toString();
-        }
-        
-        public Boolean allows(PermissionType type) {
-            switch (type) {
-            case CREATE:
-            	return getAllowCreate();
-            case READ:
-            	return getAllowRead();
-            case UPDATE:
-            	return getAllowUpdate();
-            case DELETE:
-            	return getAllowDelete();
-            }        	
-            throw new AssertionError();
-        }
-        
-        public String toString() {
-        	StringBuilder sb = new StringBuilder();
-        	sb.append(getResourceName());
-        	sb.append("["); //$NON-NLS-1$
-        	sb.append(getType());
-        	sb.append("]");//$NON-NLS-1$
-        	return sb.toString();
-        }
-	}
-
-
-    @Override
-    @ManagementProperty(description="Indicates if the role is mapped to any authenticated user.")
-	public boolean isAnyAuthenticated() {
-		return this.anyAuthenticated;
-	}
-    
-    public void setAnyAuthenticated(boolean anyAuthenticated) {
-		this.anyAuthenticated = anyAuthenticated;
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java (from rev 2765, trunk/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/adminapi/impl/DataPolicyMetadata.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,277 @@
+/*
+ * 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.adminapi.impl;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementObjectID;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.adminapi.DataPolicy;
+
+
+ at XmlAccessorType(XmlAccessType.NONE)
+ at XmlType(name = "", propOrder = {
+    "description",
+    "permissions",
+    "mappedRoleNames"
+})
+ at ManagementObject(properties=ManagementProperties.EXPLICIT)
+public class DataPolicyMetadata implements DataPolicy, Serializable {
+	private static final long serialVersionUID = -4119646357275977190L;
+	
+	@XmlAttribute(name = "name", required = true)
+    protected String name;
+	@XmlElement(name = "description")
+    protected String description;
+	@XmlAttribute(name = "any-authenticated")
+	protected boolean anyAuthenticated;
+	@XmlAttribute(name = "allow-create-temporary-tables")
+	protected Boolean allowCreateTemporaryTables;
+
+    @XmlElement(name = "permission")
+    protected PermissionMap permissions = new PermissionMap(new KeyBuilder<PermissionMetaData>() {
+		private static final long serialVersionUID = -6992984146431492449L;
+		@Override
+		public String getKey(PermissionMetaData entry) {
+			return entry.getResourceName().toLowerCase();
+		}
+	});
+    
+    @XmlElement(name = "mapped-role-name")
+    protected List<String> mappedRoleNames = new ArrayList<String>();
+
+	@Override
+	@ManagementProperty(description="Policy Name")
+	@ManagementObjectID(type="policy")
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String value) {
+        this.name = value;
+    }
+    
+    @Override
+    @ManagementProperty(description="Policy Description")
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String value) {
+        this.description = value;
+    }
+
+	@Override
+	@ManagementProperty(description="Permissions in a Data Policy", managed=true)
+	public List<DataPermission> getPermissions() {
+		return new ArrayList<DataPermission>(this.permissions.getMap().values());
+	}
+	
+	public void setPermissions(List<DataPermission> permissions) {
+		this.permissions.getMap().clear();
+		for (DataPermission permission:permissions) {
+			this.permissions.add((PermissionMetaData)permission);
+		}
+	}	
+	
+	public void addPermission(PermissionMetaData... permissions) {
+		for (PermissionMetaData permission:permissions) {
+			this.permissions.add(permission);
+		}
+	}
+	
+    @Override
+    @ManagementProperty(description="Mapped Container role names mapped to this policy")    
+    public List<String> getMappedRoleNames() {
+		return mappedRoleNames;
+	}
+
+	public void setMappedRoleNames(List<String> names) {
+		this.mappedRoleNames.clear();
+		this.mappedRoleNames.addAll(names);
+	}    
+	
+	public void addMappedRoleName(String name) {
+		this.mappedRoleNames.add(name);
+	}  	
+	
+	public boolean allows(String resourceName, DataPolicy.PermissionType type) {
+		resourceName = resourceName.toLowerCase();
+		while (resourceName.length() > 0) {
+			PermissionMetaData p = this.permissions.getMap().get(resourceName);
+			if (p != null) {
+				Boolean allowed = p.allows(type);
+				if (allowed != null) {
+					return allowed;
+				}
+			}
+			resourceName = resourceName.substring(0, Math.max(0, resourceName.lastIndexOf('.')));
+		}
+		return false;
+	}
+	
+	
+    @XmlAccessorType(XmlAccessType.NONE)
+    @XmlType(name = "", propOrder = {
+        "resourceName",
+        "allowCreate",
+        "allowRead",
+        "allowUpdate",
+        "allowDelete"
+    })	
+    @ManagementObject(properties=ManagementProperties.EXPLICIT)
+	public static class PermissionMetaData implements DataPermission, Serializable {
+		private static final long serialVersionUID = 7034744531663164277L;
+        
+        // XML based fields
+        private String resourceName;
+        @XmlElement(name = "allow-create")
+        protected Boolean allowCreate;
+        @XmlElement(name = "allow-read")
+        protected Boolean allowRead;
+        @XmlElement(name = "allow-update")
+        protected Boolean allowUpdate;
+        @XmlElement(name = "allow-delete")
+        protected Boolean allowDelete;
+        
+        @Override
+        @ManagementProperty(description="Resource Name, for which permission defined")
+        //@ManagementObjectID(type="permission")
+        @XmlElement(name = "resource-name", required = true)
+        public String getResourceName() {
+            return resourceName;
+        }
+
+        public void setResourceName(String value) {
+            this.resourceName = value;
+        }
+
+        @Override
+        @ManagementProperty(description="Allows Create")
+        public Boolean getAllowCreate() {
+            return allowCreate;
+        }
+
+        public void setAllowCreate(Boolean value) {
+            this.allowCreate = value;
+        }
+
+        @Override
+        @ManagementProperty(description="Allows Read")
+        public Boolean getAllowRead() {
+            return allowRead;
+        }
+
+        public void setAllowRead(Boolean value) {
+            this.allowRead = value;
+        }
+
+        @Override
+        @ManagementProperty(description="Allows Update")
+        public Boolean getAllowUpdate() {
+            return allowUpdate;
+        }
+
+        public void setAllowUpdate(Boolean value) {
+            this.allowUpdate = value;
+        }
+
+        @Override
+        @ManagementProperty(description="Allows Delete")
+        public Boolean getAllowDelete() {
+            return allowDelete;
+        }
+
+        public void setAllowDelete(Boolean value) {
+            this.allowDelete = value;
+        }
+        
+        public String getType() {
+        	StringBuilder sb = new StringBuilder();
+        	if (Boolean.TRUE.equals(getAllowCreate())) {
+        		sb.append("C");//$NON-NLS-1$
+        	}
+        	if (Boolean.TRUE.equals(getAllowRead())) {
+        		sb.append("R");//$NON-NLS-1$
+        	}
+        	if (Boolean.TRUE.equals(getAllowUpdate())) {
+        		sb.append("U");//$NON-NLS-1$
+        	}
+        	if (Boolean.TRUE.equals(getAllowDelete())) {
+        		sb.append("D");//$NON-NLS-1$
+        	}     
+        	return sb.toString();
+        }
+        
+        public Boolean allows(PermissionType type) {
+            switch (type) {
+            case CREATE:
+            	return getAllowCreate();
+            case READ:
+            	return getAllowRead();
+            case UPDATE:
+            	return getAllowUpdate();
+            case DELETE:
+            	return getAllowDelete();
+            }        	
+            throw new AssertionError();
+        }
+        
+        public String toString() {
+        	StringBuilder sb = new StringBuilder();
+        	sb.append(getResourceName());
+        	sb.append("["); //$NON-NLS-1$
+        	sb.append(getType());
+        	sb.append("]");//$NON-NLS-1$
+        	return sb.toString();
+        }
+	}
+
+    public Boolean isAllowCreateTemporaryTables() {
+		return allowCreateTemporaryTables;
+	}
+    
+    public void setAllowCreateTemporaryTables(Boolean allowCreateTemporaryTables) {
+		this.allowCreateTemporaryTables = allowCreateTemporaryTables;
+	}
+
+    @Override
+    @ManagementProperty(description="Indicates if the role is mapped to any authenticated user.")
+	public boolean isAnyAuthenticated() {
+		return this.anyAuthenticated;
+	}
+    
+    public void setAnyAuthenticated(boolean anyAuthenticated) {
+		this.anyAuthenticated = anyAuthenticated;
+	}
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java
===================================================================
--- trunk/client/src/main/java/org/teiid/net/HostInfo.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,146 +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;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-
-import org.teiid.core.util.ArgCheck;
-import org.teiid.core.util.HashCodeUtil;
-
-
-/**
- * Defines the hostname/port or {@link InetAddress} to connect to a host.
- * 
- * Similar to an {@link InetSocketAddress} except that it can be constructed
- * fully resolved, with an {@link InetAddress} and a hostname.
- * 
- * @since 4.2
- */
-public class HostInfo {
-    // Host Name and Port Number
-    private String hostName;
-    private int portNumber = 0;
-    private InetAddress inetAddress;
-    private boolean ssl;
-    
-    /**
-     * Construct a fully resolved {@link HostInfo}.
-     * @param hostName
-     * @param addr
-     */
-    public HostInfo(String hostName, InetSocketAddress addr) {
-    	this.hostName = hostName;
-    	this.portNumber = addr.getPort();
-    	this.inetAddress = addr.getAddress();
-    }
-    
-    /**
-     * Construct a {@link HostInfo} that can resolve each
-     * time an {@link InetAddress} is asked for.
-     * @param host
-     * @param port
-     */
-    public HostInfo (String host, int port) {
-    	ArgCheck.isNotNull(host);
-		this.hostName = host.toLowerCase();
-    	this.portNumber = port;
-    	
-    	//only cache inetaddresses if they represent the ip. 
-    	try {
-			InetAddress addr = InetAddress.getByName(this.hostName);
-			if (addr.getHostAddress().equalsIgnoreCase(this.hostName)) {
-				this.inetAddress = addr;
-			}
-		} catch (UnknownHostException e) {
-		}
-    }
-    
-    public InetAddress getInetAddress() throws UnknownHostException {
-    	if (inetAddress != null) {
-    		return inetAddress;
-    	}
-    	return InetAddress.getByName(this.hostName);
-    }
-    
-    public String getHostName() {
-        return hostName;
-    }
-
-    public int getPortNumber() {
-        return portNumber;
-    }
-    
-	public String toString() {
-        StringBuffer sb = new StringBuffer();
-        sb.append(hostName).append(":").append(portNumber); //$NON-NLS-1$
-        return sb.toString();
-    }
-    
-    /** 
-     * @see java.lang.Object#equals(java.lang.Object)
-     * @since 4.2
-     */
-    public boolean equals(Object obj) {
-    	if (obj == this) {
-    		return true;
-    	}
-    	if (!(obj instanceof HostInfo)) {
-    		return false;
-    	}
-        HostInfo hostInfo = (HostInfo) obj;
-        if (portNumber != hostInfo.getPortNumber()) {
-        	return false;
-        }
-        if (inetAddress != null && hostInfo.inetAddress != null) {
-        	return inetAddress.equals(hostInfo.inetAddress);
-        }
-        if (ssl != hostInfo.ssl) {
-        	return false;
-        }
-        return hostName.equals(hostInfo.getHostName());
-    }
-
-    /** 
-     * @see java.lang.Object#hashCode()
-     * @since 4.2
-     */
-    public int hashCode() {
-        int hc = HashCodeUtil.hashCode(0, hostName);
-        return HashCodeUtil.hashCode(hc, portNumber);
-    }
-    
-    public boolean isResolved() {
-    	return this.inetAddress != null;
-    }
-    
-    public boolean isSsl() {
-		return ssl;
-	}
-    
-    public void setSsl(boolean ssl) {
-		this.ssl = ssl;
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java (from rev 2774, trunk/client/src/main/java/org/teiid/net/HostInfo.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/java/org/teiid/net/HostInfo.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,146 @@
+/*
+ * 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;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+
+import org.teiid.core.util.ArgCheck;
+import org.teiid.core.util.HashCodeUtil;
+
+
+/**
+ * Defines the hostname/port or {@link InetAddress} to connect to a host.
+ * 
+ * Similar to an {@link InetSocketAddress} except that it can be constructed
+ * fully resolved, with an {@link InetAddress} and a hostname.
+ * 
+ * @since 4.2
+ */
+public class HostInfo {
+    // Host Name and Port Number
+    private String hostName;
+    private int portNumber = 0;
+    private InetAddress inetAddress;
+    private boolean ssl;
+    
+    /**
+     * Construct a fully resolved {@link HostInfo}.
+     * @param hostName
+     * @param addr
+     */
+    public HostInfo(String hostName, InetSocketAddress addr) {
+    	this.hostName = hostName;
+    	this.portNumber = addr.getPort();
+    	this.inetAddress = addr.getAddress();
+    }
+    
+    /**
+     * Construct a {@link HostInfo} that can resolve each
+     * time an {@link InetAddress} is asked for.
+     * @param host
+     * @param port
+     */
+    public HostInfo (String host, int port) {
+    	ArgCheck.isNotNull(host);
+		this.hostName = host.toLowerCase();
+    	this.portNumber = port;
+    	
+    	//only cache inetaddresses if they represent the ip. 
+    	try {
+			InetAddress addr = InetAddress.getByName(this.hostName);
+			if (addr.getHostAddress().equalsIgnoreCase(this.hostName)) {
+				this.inetAddress = addr;
+			}
+		} catch (UnknownHostException e) {
+		}
+    }
+    
+    public InetAddress getInetAddress() throws UnknownHostException {
+    	if (inetAddress != null) {
+    		return inetAddress;
+    	}
+    	return InetAddress.getByName(this.hostName);
+    }
+    
+    public String getHostName() {
+        return hostName;
+    }
+
+    public int getPortNumber() {
+        return portNumber;
+    }
+    
+	public String toString() {
+        StringBuffer sb = new StringBuffer();
+        sb.append(hostName).append(":").append(portNumber); //$NON-NLS-1$
+        return sb.toString();
+    }
+    
+    /** 
+     * @see java.lang.Object#equals(java.lang.Object)
+     * @since 4.2
+     */
+    public boolean equals(Object obj) {
+    	if (obj == this) {
+    		return true;
+    	}
+    	if (!(obj instanceof HostInfo)) {
+    		return false;
+    	}
+        HostInfo hostInfo = (HostInfo) obj;
+        if (portNumber != hostInfo.getPortNumber()) {
+        	return false;
+        }
+        if (ssl != hostInfo.ssl) {
+        	return false;
+        }
+        if (inetAddress != null && hostInfo.inetAddress != null) {
+        	return inetAddress.equals(hostInfo.inetAddress);
+        }
+        return hostName.equals(hostInfo.getHostName());
+    }
+
+    /** 
+     * @see java.lang.Object#hashCode()
+     * @since 4.2
+     */
+    public int hashCode() {
+        int hc = HashCodeUtil.hashCode(0, hostName);
+        return HashCodeUtil.hashCode(hc, portNumber);
+    }
+    
+    public boolean isResolved() {
+    	return this.inetAddress != null;
+    }
+    
+    public boolean isSsl() {
+		return ssl;
+	}
+    
+    public void setSsl(boolean ssl) {
+		this.ssl = ssl;
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd
===================================================================
--- trunk/client/src/main/resources/vdb-deployer.xsd	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,130 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
-	<xs:element name="vdb">
-		<xs:annotation>
-			<xs:documentation>Describes the configuration for a VDB</xs:documentation>
-		</xs:annotation>
-		<xs:complexType>
-			<xs:sequence>
-				<xs:element name="description" type="xs:string" minOccurs="0"/>
-				<xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
-				<xs:element name="model" maxOccurs="unbounded" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>A model defines the alias for the Schema the data being integrated. In the Designer
-                        built VDB, the Schema for this model is defined by external index files. In the "Dynamic VDB"
-                        this defines the importer properties along with "source" information the Schema 
-                        is generated at deploy time.</xs:documentation>
-                    </xs:annotation>                
-					<xs:complexType>
-						<xs:sequence>
-                            <xs:element name="description" type="xs:string" minOccurs="0"/>
-							<xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
-							<xs:element name="source" minOccurs="0" maxOccurs="unbounded">
-                                <xs:annotation>
-                                    <xs:documentation>A source defines access to physical data source with its connection-jndi-name.
-                                    translator-name defines a translator. Translator is a layer between Teiid engine and data source
-                                    that knows how to convert and execute commands native to source. Teiid offers various 
-                                    pre-built translators.</xs:documentation>
-                                </xs:annotation>
-								<xs:complexType>
-									<xs:attribute name="name" type="xs:string" use="required"/>
-                                    <xs:attribute name="translator-name" type="xs:string" use="required"/>
-									<xs:attribute name="connection-jndi-name" type="xs:string"/>
-								</xs:complexType>
-							</xs:element>
-							<xs:element name="validation-error" minOccurs="0" maxOccurs="unbounded">
-                                <xs:annotation>
-                                    <xs:documentation>When Schema files for model defined by Designer, the validation-errors define
-                                    any errors in the schema. This is not applicable in the Dynamic VDB scenario.</xs:documentation>
-                                </xs:annotation>                            
-								<xs:complexType>
-									<xs:simpleContent>
-										<xs:extension base="xs:string">
-											<xs:attribute name="severity" use="required">
-												<xs:simpleType>
-													<xs:restriction base="xs:string">
-														<xs:enumeration value="ERROR"/>
-														<xs:enumeration value="WARNING"/>
-													</xs:restriction>
-												</xs:simpleType>
-											</xs:attribute>
-                                            <xs:attribute name="path" type="xs:string"/>
-										</xs:extension>
-									</xs:simpleContent>
-								</xs:complexType>
-							</xs:element>
-						</xs:sequence>
-						<xs:attribute name="name" type="xs:string" use="required"/>
-						<xs:attribute name="type" type="xs:string" default="PHYSICAL"/>
-						<xs:attribute name="visible" type="xs:boolean" default="true"/>
-                        <xs:attribute name="path" type="xs:string"/>
-					</xs:complexType>
-				</xs:element>
-                <xs:element name="translator" maxOccurs="unbounded" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>When the pre-built translator's behavior need to be altered, this optional element need to
-                         be used to override them.</xs:documentation>
-                    </xs:annotation>                 
-                    <xs:complexType>
-                        <xs:sequence>
-                            <xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
-                        </xs:sequence>
-                        <xs:attribute name="name" type="xs:string" use="required"/>
-                        <xs:attribute name="type" type="xs:string" use="required"/>
-                        <xs:attribute name="description" type="xs:string"/>
-                    </xs:complexType>
-                </xs:element>                
-				<xs:element name="data-role" minOccurs="0" maxOccurs="unbounded">
-                    <xs:annotation>
-                        <xs:documentation>This defines a data role. The "resource-name" element defines fully qualified 
-                        name for a Schema, Table, Procedure, etc.  The "allows-*" elements define the security access, which are applied to the resource
-                        and all child resources.  The "mapped-role-name" defines the "role" name that user must have before they have access to this data. 
-                        The "role" name matches to the JAAS based role that user has.</xs:documentation>
-                    </xs:annotation>                 
-                
-					<xs:complexType>
-						<xs:sequence>
-							<xs:element name="description" type="xs:string" minOccurs="0"/>
-                            <xs:element name="permission" minOccurs="1" maxOccurs="unbounded">
-                                <xs:complexType>
-                                    <xs:sequence>                            
-							             <xs:element name="resource-name" type="xs:string"/>
-							             <xs:element name="allow-create" type="xs:boolean" minOccurs="0"/>
-							             <xs:element name="allow-read" type="xs:boolean" minOccurs="0"/>
-							             <xs:element name="allow-update" type="xs:boolean" minOccurs="0"/>
-							             <xs:element name="allow-delete" type="xs:boolean" minOccurs="0"/>
-                                   </xs:sequence>      
-                                </xs:complexType>
-                            </xs:element>                                                                      
-                            <xs:element name="mapped-role-name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
-						</xs:sequence>
-						<xs:attribute name="name" type="xs:string" use="required"/>
-						<xs:attribute name="any-authenticated" type="xs:boolean"/>
-					</xs:complexType>
-				</xs:element>
-                <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">
-                    <xs:annotation>
-                        <xs:documentation>With Designer based VDBs, this element is used to define extra files that are
-                        defined inside the VDB archive. Not applicable for Dynamic VDBs</xs:documentation>
-                    </xs:annotation>                 
-                    <xs:complexType>
-                        <xs:sequence>
-                            <xs:element name="description" type="xs:string" minOccurs="0"/>
-                            <xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
-                        </xs:sequence>
-                        <xs:attribute name="path" type="xs:string" use="required"/>
-                    </xs:complexType>
-                </xs:element>
-			</xs:sequence>
-			<xs:attribute name="name" type="xs:string" use="required"/>
-			<xs:attribute name="version" type="xs:int" use="required"/>
-		</xs:complexType>
-	</xs:element>
-	<xs:complexType name="property">
-		<xs:annotation>
-			<xs:documentation> property</xs:documentation>
-		</xs:annotation>
-		<xs:attribute name="name" type="xs:string" use="required"/>
-		<xs:attribute name="value" type="xs:string" use="required"/>
-	</xs:complexType>
-</xs:schema>

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd (from rev 2765, trunk/client/src/main/resources/vdb-deployer.xsd)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/main/resources/vdb-deployer.xsd	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
+	<xs:element name="vdb">
+		<xs:annotation>
+			<xs:documentation>Describes the configuration for a VDB</xs:documentation>
+		</xs:annotation>
+		<xs:complexType>
+			<xs:sequence>
+				<xs:element name="description" type="xs:string" minOccurs="0"/>
+				<xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
+				<xs:element name="model" maxOccurs="unbounded" minOccurs="0">
+                    <xs:annotation>
+                        <xs:documentation>A model defines the alias for the Schema the data being integrated. In the Designer
+                        built VDB, the Schema for this model is defined by external index files. In the "Dynamic VDB"
+                        this defines the importer properties along with "source" information the Schema 
+                        is generated at deploy time.</xs:documentation>
+                    </xs:annotation>                
+					<xs:complexType>
+						<xs:sequence>
+                            <xs:element name="description" type="xs:string" minOccurs="0"/>
+							<xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
+							<xs:element name="source" minOccurs="0" maxOccurs="unbounded">
+                                <xs:annotation>
+                                    <xs:documentation>A source defines access to physical data source with its connection-jndi-name.
+                                    translator-name defines a translator. Translator is a layer between Teiid engine and data source
+                                    that knows how to convert and execute commands native to source. Teiid offers various 
+                                    pre-built translators.</xs:documentation>
+                                </xs:annotation>
+								<xs:complexType>
+									<xs:attribute name="name" type="xs:string" use="required"/>
+                                    <xs:attribute name="translator-name" type="xs:string" use="required"/>
+									<xs:attribute name="connection-jndi-name" type="xs:string"/>
+								</xs:complexType>
+							</xs:element>
+							<xs:element name="validation-error" minOccurs="0" maxOccurs="unbounded">
+                                <xs:annotation>
+                                    <xs:documentation>When Schema files for model defined by Designer, the validation-errors define
+                                    any errors in the schema. This is not applicable in the Dynamic VDB scenario.</xs:documentation>
+                                </xs:annotation>                            
+								<xs:complexType>
+									<xs:simpleContent>
+										<xs:extension base="xs:string">
+											<xs:attribute name="severity" use="required">
+												<xs:simpleType>
+													<xs:restriction base="xs:string">
+														<xs:enumeration value="ERROR"/>
+														<xs:enumeration value="WARNING"/>
+													</xs:restriction>
+												</xs:simpleType>
+											</xs:attribute>
+                                            <xs:attribute name="path" type="xs:string"/>
+										</xs:extension>
+									</xs:simpleContent>
+								</xs:complexType>
+							</xs:element>
+						</xs:sequence>
+						<xs:attribute name="name" type="xs:string" use="required"/>
+						<xs:attribute name="type" type="xs:string" default="PHYSICAL"/>
+						<xs:attribute name="visible" type="xs:boolean" default="true"/>
+                        <xs:attribute name="path" type="xs:string"/>
+					</xs:complexType>
+				</xs:element>
+                <xs:element name="translator" maxOccurs="unbounded" minOccurs="0">
+                    <xs:annotation>
+                        <xs:documentation>When the pre-built translator's behavior need to be altered, this optional element need to
+                         be used to override them.</xs:documentation>
+                    </xs:annotation>                 
+                    <xs:complexType>
+                        <xs:sequence>
+                            <xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
+                        </xs:sequence>
+                        <xs:attribute name="name" type="xs:string" use="required"/>
+                        <xs:attribute name="type" type="xs:string" use="required"/>
+                        <xs:attribute name="description" type="xs:string"/>
+                    </xs:complexType>
+                </xs:element>                
+				<xs:element name="data-role" minOccurs="0" maxOccurs="unbounded">
+                    <xs:annotation>
+                        <xs:documentation>This defines a data role. The "resource-name" element defines fully qualified 
+                        name for a Schema, Table, Procedure, etc.  The "allows-*" elements define the security access, which are applied to the resource
+                        and all child resources.  The "mapped-role-name" defines the "role" name that user must have before they have access to this data. 
+                        The "role" name matches to the JAAS based role that user has.</xs:documentation>
+                    </xs:annotation>                 
+                
+					<xs:complexType>
+						<xs:sequence>
+							<xs:element name="description" type="xs:string" minOccurs="0"/>
+                            <xs:element name="permission" minOccurs="1" maxOccurs="unbounded">
+                                <xs:complexType>
+                                    <xs:sequence>                            
+							             <xs:element name="resource-name" type="xs:string"/>
+							             <xs:element name="allow-create" type="xs:boolean" minOccurs="0"/>
+							             <xs:element name="allow-read" type="xs:boolean" minOccurs="0"/>
+							             <xs:element name="allow-update" type="xs:boolean" minOccurs="0"/>
+							             <xs:element name="allow-delete" type="xs:boolean" minOccurs="0"/>
+                                   </xs:sequence>      
+                                </xs:complexType>
+                            </xs:element>                                                                      
+                            <xs:element name="mapped-role-name" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+						</xs:sequence>
+						<xs:attribute name="name" type="xs:string" use="required"/>
+						<xs:attribute name="any-authenticated" type="xs:boolean"/>
+						<xs:attribute name="allow-create-temporary-tables" type="xs:boolean"/>
+					</xs:complexType>
+				</xs:element>
+                <xs:element name="entry" minOccurs="0" maxOccurs="unbounded">
+                    <xs:annotation>
+                        <xs:documentation>With Designer based VDBs, this element is used to define extra files that are
+                        defined inside the VDB archive. Not applicable for Dynamic VDBs</xs:documentation>
+                    </xs:annotation>                 
+                    <xs:complexType>
+                        <xs:sequence>
+                            <xs:element name="description" type="xs:string" minOccurs="0"/>
+                            <xs:element name="property" type="property" minOccurs="0" maxOccurs="unbounded"/>
+                        </xs:sequence>
+                        <xs:attribute name="path" type="xs:string" use="required"/>
+                    </xs:complexType>
+                </xs:element>
+			</xs:sequence>
+			<xs:attribute name="name" type="xs:string" use="required"/>
+			<xs:attribute name="version" type="xs:int" use="required"/>
+		</xs:complexType>
+	</xs:element>
+	<xs:complexType name="property">
+		<xs:annotation>
+			<xs:documentation> property</xs:documentation>
+		</xs:annotation>
+		<xs:attribute name="name" type="xs:string" use="required"/>
+		<xs:attribute name="value" type="xs:string" use="required"/>
+	</xs:complexType>
+</xs:schema>

Deleted: tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
===================================================================
--- trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,205 +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.adminapi.impl;
-
-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.assertTrue;
-
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.xml.XMLConstants;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-
-import org.junit.Test;
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
-import org.teiid.core.util.PropertiesUtils;
-
- at SuppressWarnings("nls")
-public class TestVDBMetaData {
-
-	@Test
-	public void testMarshellUnmarshell() throws Exception {
-		
-		VDBMetaData vdb = new VDBMetaData();
-		vdb.setName("myVDB"); //$NON-NLS-1$
-		vdb.setDescription("vdb description"); //$NON-NLS-1$
-		vdb.setVersion(1);
-		vdb.addProperty("vdb-property", "vdb-value"); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		ModelMetaData modelOne = new ModelMetaData();
-		modelOne.setName("model-one"); //$NON-NLS-1$
-		modelOne.addSourceMapping("s1", "translator", "java:mybinding"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelOne.setModelType(Model.Type.PHYSICAL); //$NON-NLS-1$
-		modelOne.addProperty("model-prop", "model-value"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelOne.addProperty("model-prop", "model-value-override"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelOne.setVisible(false);
-		modelOne.addError("ERROR", "There is an error in VDB"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelOne.setDescription("model description");
-		
-		vdb.addModel(modelOne);
-		
-		ModelMetaData modelTwo = new ModelMetaData();
-		modelTwo.setName("model-two"); //$NON-NLS-1$
-		modelTwo.addSourceMapping("s1", "translator", "java:binding-one"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelTwo.addSourceMapping("s2", "translator", "java:binding-two"); //$NON-NLS-1$ //$NON-NLS-2$
-		modelTwo.setModelType(Model.Type.VIRTUAL); //$NON-NLS-1$
-		modelTwo.addProperty("model-prop", "model-value"); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		vdb.addModel(modelTwo);
-		
-		TranslatorMetaData t1 = new TranslatorMetaData();
-		t1.setName("oracleOverride");
-		t1.setType("oracle");
-		t1.setDescription("hello world");
-		t1.addProperty("my-property", "my-value");
-		List<Translator> list = new ArrayList<Translator>();
-		list.add(t1);
-		vdb.setOverrideTranslators(list);
-		
-		DataPolicyMetadata roleOne = new DataPolicyMetadata();
-		roleOne.setName("roleOne"); //$NON-NLS-1$
-		roleOne.setDescription("roleOne described"); //$NON-NLS-1$
-		
-		PermissionMetaData perm1 = new PermissionMetaData();
-		perm1.setResourceName("myTable.T1"); //$NON-NLS-1$
-		perm1.setAllowRead(true);
-		roleOne.addPermission(perm1);
-		
-		PermissionMetaData perm2 = new PermissionMetaData();
-		perm2.setResourceName("myTable.T2"); //$NON-NLS-1$
-		perm2.setAllowRead(false);
-		perm2.setAllowDelete(true);
-		roleOne.addPermission(perm2);
-		
-		roleOne.setMappedRoleNames(Arrays.asList("ROLE1", "ROLE2")); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		vdb.addDataPolicy(roleOne);
-		
-		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-        Schema schema = schemaFactory.newSchema(VDBMetaData.class.getResource("/vdb-deployer.xsd")); 		 //$NON-NLS-1$
-		JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {VDBMetaData.class});
-		Marshaller marshell = jc.createMarshaller();
-		marshell.setSchema(schema);
-		marshell.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
-		
-		StringWriter sw = new StringWriter();
-		marshell.marshal(vdb, sw);
-				
-		//System.out.println(sw.toString());
-
-		// UnMarshell
-		Unmarshaller un = jc.createUnmarshaller();
-		un.setSchema(schema);
-		vdb = (VDBMetaData)un.unmarshal(new StringReader(sw.toString()));
-		
-		assertEquals("myVDB", vdb.getName()); //$NON-NLS-1$
-		assertEquals("vdb description", vdb.getDescription()); //$NON-NLS-1$
-		assertEquals(1, vdb.getVersion());
-		assertEquals("vdb-value", vdb.getPropertyValue("vdb-property")); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		assertNotNull(vdb.getModel("model-one")); //$NON-NLS-1$
-		assertNotNull(vdb.getModel("model-two")); //$NON-NLS-1$
-		assertNull(vdb.getModel("model-unknown")); //$NON-NLS-1$
-		
-		modelOne = vdb.getModel("model-one"); //$NON-NLS-1$
-		assertEquals("model-one", modelOne.getName()); //$NON-NLS-1$
-		assertEquals("s1", modelOne.getSourceNames().get(0)); //$NON-NLS-1$
-		assertEquals(Model.Type.PHYSICAL, modelOne.getModelType()); 
-		assertEquals("model-value-override", modelOne.getPropertyValue("model-prop")); //$NON-NLS-1$ //$NON-NLS-2$
-		assertFalse(modelOne.isVisible());
-		assertEquals("model description", modelOne.getDescription());
-		
-		modelTwo = vdb.getModel("model-two"); //$NON-NLS-1$
-		assertEquals("model-two", modelTwo.getName()); //$NON-NLS-1$
-		assertTrue(modelTwo.getSourceNames().contains("s1")); //$NON-NLS-1$
-		assertTrue(modelTwo.getSourceNames().contains("s2")); //$NON-NLS-1$
-		assertEquals(Model.Type.VIRTUAL, modelTwo.getModelType()); // this is not persisted in the XML
-		assertEquals("model-value", modelTwo.getPropertyValue("model-prop")); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		
-		assertTrue(vdb.getValidityErrors().contains("There is an error in VDB")); //$NON-NLS-1$
-		
-		List<Translator> translators = vdb.getOverrideTranslators();
-		assertTrue(translators.size() == 1);
-		
-		Translator translator = translators.get(0);
-		assertEquals("oracleOverride", translator.getName());
-		assertEquals("oracle", translator.getType());
-		assertEquals("my-value", translator.getPropertyValue("my-property"));
-		assertEquals("hello world", translator.getDescription());
-		List<DataPolicy> roles = vdb.getDataPolicies();
-		
-		assertTrue(roles.size() == 1);
-		
-		DataPolicyMetadata role = vdb.getDataPolicy("roleOne"); //$NON-NLS-1$
-		assertEquals("roleOne described", role.getDescription()); //$NON-NLS-1$
-		assertNotNull(role.getMappedRoleNames());
-		assertTrue(role.getMappedRoleNames().contains("ROLE1")); //$NON-NLS-1$
-		assertTrue(role.getMappedRoleNames().contains("ROLE2")); //$NON-NLS-1$
-		
-		List<DataPolicy.DataPermission> permissions = role.getPermissions();
-		assertEquals(2, permissions.size());
-		
-		for (DataPolicy.DataPermission p: permissions) {
-			if (p.getResourceName().equalsIgnoreCase("myTable.T1")) { //$NON-NLS-1$
-				assertTrue(p.getAllowRead());
-				assertNull(p.getAllowDelete());
-			}
-			else {
-				assertFalse(p.getAllowRead());
-				assertTrue(p.getAllowDelete());
-			}
-		}
-	}
-	
-	@Test
-	public void testAdminMOCreation() {
-		VDBMetaData vdb = new VDBMetaData();
-		
-		PropertiesUtils.setBeanProperty(vdb, "url", "http://teiid.org/myvdb.vdb");
-		
-		assertEquals("http://teiid.org/myvdb.vdb", vdb.getUrl());
-	}
-	
-	@Test public void testSetUrlVersion() throws MalformedURLException {
-		VDBMetaData vdb = new VDBMetaData();
-		vdb.setName("foo");
-		vdb.setUrl(new URL("file:///x/foo.2.vdb"));
-		assertEquals(2, vdb.getVersion());
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java (from rev 2765, trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,206 @@
+/*
+ * 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.adminapi.impl;
+
+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.assertTrue;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.xml.XMLConstants;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.junit.Test;
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
+import org.teiid.core.util.PropertiesUtils;
+
+ at SuppressWarnings("nls")
+public class TestVDBMetaData {
+
+	@Test
+	public void testMarshellUnmarshell() throws Exception {
+		
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("myVDB"); //$NON-NLS-1$
+		vdb.setDescription("vdb description"); //$NON-NLS-1$
+		vdb.setVersion(1);
+		vdb.addProperty("vdb-property", "vdb-value"); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		ModelMetaData modelOne = new ModelMetaData();
+		modelOne.setName("model-one"); //$NON-NLS-1$
+		modelOne.addSourceMapping("s1", "translator", "java:mybinding"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelOne.setModelType(Model.Type.PHYSICAL); //$NON-NLS-1$
+		modelOne.addProperty("model-prop", "model-value"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelOne.addProperty("model-prop", "model-value-override"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelOne.setVisible(false);
+		modelOne.addError("ERROR", "There is an error in VDB"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelOne.setDescription("model description");
+		
+		vdb.addModel(modelOne);
+		
+		ModelMetaData modelTwo = new ModelMetaData();
+		modelTwo.setName("model-two"); //$NON-NLS-1$
+		modelTwo.addSourceMapping("s1", "translator", "java:binding-one"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelTwo.addSourceMapping("s2", "translator", "java:binding-two"); //$NON-NLS-1$ //$NON-NLS-2$
+		modelTwo.setModelType(Model.Type.VIRTUAL); //$NON-NLS-1$
+		modelTwo.addProperty("model-prop", "model-value"); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		vdb.addModel(modelTwo);
+		
+		TranslatorMetaData t1 = new TranslatorMetaData();
+		t1.setName("oracleOverride");
+		t1.setType("oracle");
+		t1.setDescription("hello world");
+		t1.addProperty("my-property", "my-value");
+		List<Translator> list = new ArrayList<Translator>();
+		list.add(t1);
+		vdb.setOverrideTranslators(list);
+		
+		DataPolicyMetadata roleOne = new DataPolicyMetadata();
+		roleOne.setName("roleOne"); //$NON-NLS-1$
+		roleOne.setDescription("roleOne described"); //$NON-NLS-1$
+		roleOne.setAllowCreateTemporaryTables(true);
+		PermissionMetaData perm1 = new PermissionMetaData();
+		perm1.setResourceName("myTable.T1"); //$NON-NLS-1$
+		perm1.setAllowRead(true);
+		roleOne.addPermission(perm1);
+		
+		PermissionMetaData perm2 = new PermissionMetaData();
+		perm2.setResourceName("myTable.T2"); //$NON-NLS-1$
+		perm2.setAllowRead(false);
+		perm2.setAllowDelete(true);
+		roleOne.addPermission(perm2);
+		
+		roleOne.setMappedRoleNames(Arrays.asList("ROLE1", "ROLE2")); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		vdb.addDataPolicy(roleOne);
+		
+		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+        Schema schema = schemaFactory.newSchema(VDBMetaData.class.getResource("/vdb-deployer.xsd")); 		 //$NON-NLS-1$
+		JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {VDBMetaData.class});
+		Marshaller marshell = jc.createMarshaller();
+		marshell.setSchema(schema);
+		marshell.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
+		
+		StringWriter sw = new StringWriter();
+		marshell.marshal(vdb, sw);
+				
+		//System.out.println(sw.toString());
+
+		// UnMarshell
+		Unmarshaller un = jc.createUnmarshaller();
+		un.setSchema(schema);
+		vdb = (VDBMetaData)un.unmarshal(new StringReader(sw.toString()));
+		
+		assertEquals("myVDB", vdb.getName()); //$NON-NLS-1$
+		assertEquals("vdb description", vdb.getDescription()); //$NON-NLS-1$
+		assertEquals(1, vdb.getVersion());
+		assertEquals("vdb-value", vdb.getPropertyValue("vdb-property")); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		assertNotNull(vdb.getModel("model-one")); //$NON-NLS-1$
+		assertNotNull(vdb.getModel("model-two")); //$NON-NLS-1$
+		assertNull(vdb.getModel("model-unknown")); //$NON-NLS-1$
+		
+		modelOne = vdb.getModel("model-one"); //$NON-NLS-1$
+		assertEquals("model-one", modelOne.getName()); //$NON-NLS-1$
+		assertEquals("s1", modelOne.getSourceNames().get(0)); //$NON-NLS-1$
+		assertEquals(Model.Type.PHYSICAL, modelOne.getModelType()); 
+		assertEquals("model-value-override", modelOne.getPropertyValue("model-prop")); //$NON-NLS-1$ //$NON-NLS-2$
+		assertFalse(modelOne.isVisible());
+		assertEquals("model description", modelOne.getDescription());
+		
+		modelTwo = vdb.getModel("model-two"); //$NON-NLS-1$
+		assertEquals("model-two", modelTwo.getName()); //$NON-NLS-1$
+		assertTrue(modelTwo.getSourceNames().contains("s1")); //$NON-NLS-1$
+		assertTrue(modelTwo.getSourceNames().contains("s2")); //$NON-NLS-1$
+		assertEquals(Model.Type.VIRTUAL, modelTwo.getModelType()); // this is not persisted in the XML
+		assertEquals("model-value", modelTwo.getPropertyValue("model-prop")); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		
+		assertTrue(vdb.getValidityErrors().contains("There is an error in VDB")); //$NON-NLS-1$
+		
+		List<Translator> translators = vdb.getOverrideTranslators();
+		assertTrue(translators.size() == 1);
+		
+		Translator translator = translators.get(0);
+		assertEquals("oracleOverride", translator.getName());
+		assertEquals("oracle", translator.getType());
+		assertEquals("my-value", translator.getPropertyValue("my-property"));
+		assertEquals("hello world", translator.getDescription());
+		List<DataPolicy> roles = vdb.getDataPolicies();
+		
+		assertTrue(roles.size() == 1);
+		
+		DataPolicyMetadata role = vdb.getDataPolicy("roleOne"); //$NON-NLS-1$
+		assertTrue(role.isAllowCreateTemporaryTables());
+		assertEquals("roleOne described", role.getDescription()); //$NON-NLS-1$
+		assertNotNull(role.getMappedRoleNames());
+		assertTrue(role.getMappedRoleNames().contains("ROLE1")); //$NON-NLS-1$
+		assertTrue(role.getMappedRoleNames().contains("ROLE2")); //$NON-NLS-1$
+		
+		List<DataPolicy.DataPermission> permissions = role.getPermissions();
+		assertEquals(2, permissions.size());
+		
+		for (DataPolicy.DataPermission p: permissions) {
+			if (p.getResourceName().equalsIgnoreCase("myTable.T1")) { //$NON-NLS-1$
+				assertTrue(p.getAllowRead());
+				assertNull(p.getAllowDelete());
+			}
+			else {
+				assertFalse(p.getAllowRead());
+				assertTrue(p.getAllowDelete());
+			}
+		}
+	}
+	
+	@Test
+	public void testAdminMOCreation() {
+		VDBMetaData vdb = new VDBMetaData();
+		
+		PropertiesUtils.setBeanProperty(vdb, "url", "http://teiid.org/myvdb.vdb");
+		
+		assertEquals("http://teiid.org/myvdb.vdb", vdb.getUrl());
+	}
+	
+	@Test public void testSetUrlVersion() throws MalformedURLException {
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("foo");
+		vdb.setUrl(new URL("file:///x/foo.2.vdb"));
+		assertEquals(2, vdb.getVersion());
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml
===================================================================
--- trunk/common-core/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/common-core/pom.xml (from rev 2777, trunk/common-core/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java
===================================================================
--- trunk/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,104 +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.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.Channels;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CoderResult;
-
-import org.teiid.core.types.DataTypeManager;
-
-/**
- * Replacement for the standard {@link java.io.InputStreamReader}, 
- * which suffers from a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4744247">bug</a> in sun.nio.cs.StreamDecoder
- */
-public class InputStreamReader extends Reader {
-
-	private CharsetDecoder cd;
-	private ReadableByteChannel rbc;
-	private ByteBuffer bb;
-	private CharBuffer cb;
-	private boolean done;
-	
-	public InputStreamReader(InputStream in, CharsetDecoder cd) {
-		this(in, cd, DataTypeManager.MAX_LOB_MEMORY_BYTES);
-	}
-	
-	public InputStreamReader(InputStream in, CharsetDecoder cd, int bufferSize) {
-		this.cd = cd;
-		this.rbc = Channels.newChannel(in);
-		this.bb = ByteBuffer.allocate(bufferSize);
-		this.cb = CharBuffer.allocate((int)(bufferSize * (double)cd.maxCharsPerByte()));
-		this.cb.limit(0);
-	}
-	
-	@Override
-	public void close() throws IOException {
-		rbc.close();
-		cd.reset();
-	}
-
-	@Override
-	public int read(char[] cbuf, int off, int len) throws IOException {
-		if ((off < 0) || (off > cbuf.length) || (len < 0) ||
-            ((off + len) > cbuf.length) || ((off + len) < 0)) {
-            throw new IndexOutOfBoundsException();
-        } else if (len == 0) {
-            return 0;
-        }
-		while (!done && !cb.hasRemaining()) {
-			int read = 0;
-	    	while ((read = rbc.read(bb)) == 0) {
-	    		//blocking read
-	    	}
-	    	bb.flip();
-	    	cb.clear();
-			CoderResult cr = cd.decode(bb, cb, read == -1);
-			if (!cr.isUnderflow()) {
-			    cr.throwException();
-			}
-	    	if (read == -1) {
-	    		cr = cd.flush(cb);
-	    		if (!cr.isUnderflow()) {
-	    			cr.throwException();
-	    		}
-	    		done = true;
-	    	} 
-			bb.clear();
-    		cb.flip();
-		}
-		len = Math.min(len, cb.remaining());
-		if (len == 0 && done) {
-			return -1;
-		}
-		cb.get(cbuf, off, len);
-		return len;
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java (from rev 2774, trunk/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/src/main/java/org/teiid/core/util/InputStreamReader.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,108 @@
+/*
+ * 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.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.charset.CharsetDecoder;
+import java.nio.charset.CoderResult;
+
+import org.teiid.core.types.DataTypeManager;
+
+/**
+ * Replacement for the standard {@link java.io.InputStreamReader}, 
+ * which suffers from a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4744247">bug</a> in sun.nio.cs.StreamDecoder
+ */
+public class InputStreamReader extends Reader {
+
+	private CharsetDecoder cd;
+	private ReadableByteChannel rbc;
+	private ByteBuffer bb;
+	private CharBuffer cb;
+	private boolean done;
+	
+	public InputStreamReader(InputStream in, CharsetDecoder cd) {
+		this(in, cd, DataTypeManager.MAX_LOB_MEMORY_BYTES);
+	}
+	
+	public InputStreamReader(InputStream in, CharsetDecoder cd, int bufferSize) {
+		this.cd = cd;
+		this.rbc = Channels.newChannel(in);
+		this.bb = ByteBuffer.allocate(bufferSize);
+		this.cb = CharBuffer.allocate((int)(bufferSize * (double)cd.maxCharsPerByte()));
+		this.cb.limit(0);
+	}
+	
+	@Override
+	public void close() throws IOException {
+		rbc.close();
+		cd.reset();
+	}
+
+	@Override
+	public int read(char[] cbuf, int off, int len) throws IOException {
+		if ((off < 0) || (off > cbuf.length) || (len < 0) ||
+            ((off + len) > cbuf.length) || ((off + len) < 0)) {
+            throw new IndexOutOfBoundsException();
+        } else if (len == 0) {
+            return 0;
+        }
+		while (!done && !cb.hasRemaining()) {
+			int read = 0;
+	    	while ((read = rbc.read(bb)) == 0) {
+	    		//blocking read
+	    	}
+	    	bb.flip();
+	    	cb.clear();
+			CoderResult cr = cd.decode(bb, cb, read == -1);
+			if (!cr.isUnderflow()) {
+			    cr.throwException();
+			}
+	    	if (read == -1) {
+	    		cr = cd.flush(cb);
+	    		if (!cr.isUnderflow()) {
+	    			cr.throwException();
+	    		}
+	    		done = true;
+	    	}
+	    	if (bb.position() != read) {
+	    		bb.compact();
+	    	} else {
+	    		bb.clear();
+	    	}
+    		cb.flip();
+		}
+		len = Math.min(len, cb.remaining());
+		if (len == 0 && done) {
+			return -1;
+		}
+		cb.get(cbuf, off, len);
+		return len;
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/FakeInputStream.java
===================================================================
--- trunk/common-core/src/test/java/org/teiid/core/util/FakeInputStream.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/FakeInputStream.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,68 +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.ByteArrayInputStream;
-
-/**
- * This test input stream overrides the <code>available</code>
- * to return "1" until <i>after</i> the {@link #read} method returns
- * "-1" to indicate EOF, which is how java.util.zip.ZipInputStream
- * works, which is what is used by ExtensionSourceManager to retrieve
- * Class files from JAR files.  The <code>available</code> method
- * therefore can't be relied on by ByteArrayHelper to either
- * indicate how many bytes can be read, or if more are
- * available or not.  In the latter case, ByteArrayHelper
- * relies on the <code>read</code> method returning "-1".
- */
-public class FakeInputStream extends ByteArrayInputStream {
-
-    private int available = 1;
-
-    public FakeInputStream(byte[] buf) {
-        super(buf);
-    }
-
-    /**
-     * Overriden to return "1" <i>until</i> the <code>read</code> method
-     * has returned "-1" to indicate EOF.
-     */
-    public int available(){
-        super.available();
-        return available;
-    }
-
-    /**
-     * Overriden - basically calls to super method, but checks returned
-     * number of bytes read; if "-1", then the next call to
-     * {@link #available} will return "0".
-     */
-    public int read(byte b[], int off, int len) {
-        int result = super.read(b, off, len);
-        if (result<0){
-            available = 0;
-        }
-        return result;
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/TestInputStreamReader.java (from rev 2774, trunk/common-core/src/test/java/org/teiid/core/util/TestInputStreamReader.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/TestInputStreamReader.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/common-core/src/test/java/org/teiid/core/util/TestInputStreamReader.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,18 @@
+package org.teiid.core.util;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.Charset;
+
+import org.junit.Test;
+
+ at SuppressWarnings("nls")
+public class TestInputStreamReader {
+
+	@Test public void testMultiByte() throws Exception {
+		InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(new byte[] {(byte)80, (byte)-61, (byte)-70}), Charset.forName("UTF-8").newDecoder(), 2);
+		assertEquals(80, isr.read());
+		assertEquals(250, isr.read());
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml
===================================================================
--- trunk/connectors/connector-file/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/connector-file/pom.xml (from rev 2777, trunk/connectors/connector-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-file/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/connector-ldap/pom.xml
===================================================================
--- trunk/connectors/connector-ldap/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ldap/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/connector-ldap/pom.xml (from rev 2777, trunk/connectors/connector-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ldap/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/connector-salesforce/pom.xml
===================================================================
--- trunk/connectors/connector-salesforce/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/connector-salesforce/pom.xml (from rev 2777, trunk/connectors/connector-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,106 +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.MalformedURLException;
-import java.net.URL;
-
-import javax.resource.ResourceException;
-
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.resource.spi.BasicConnectionFactory;
-import org.teiid.resource.spi.BasicManagedConnectionFactory;
-
-
-public class SalesForceManagedConnectionFactory extends BasicManagedConnectionFactory {
-	private static final long serialVersionUID = 5298591275313314698L;
-	
-	private String username;
-	private String connectorStateClass;
-	private String password;
-	private URL URL;
-	private long sourceConnectionTestInterval = -1;
-	private int sourceConnectionTimeout = -1;
-	private boolean auditModelFields = false;
-	
-	public String getUsername() {
-		return username;
-	}
-	public void setUsername(String username) {
-		if (username.trim().length() == 0) {
-			throw new TeiidRuntimeException("Name can not be null");
-		}
-		this.username = username;
-	}
-	public String getConnectorStateClass() {
-		return this.connectorStateClass;
-	}
-	public void setConnectorStateClass(String connectorStateClass) {
-		this.connectorStateClass = connectorStateClass;
-	}
-	public String getPassword() {
-		return this.password;
-	}
-	public void setPassword(String password) {
-		this.password = password;
-	}
-	public URL getURL() {
-		return this.URL;
-	}
-	
-	public void setURL(String uRL) {
-		try {
-			this.URL = new URL(uRL);
-		} catch (MalformedURLException e) {
-			throw new TeiidRuntimeException("URL Supplied is not valid URL"+ e.getMessage());
-		}
-	}
-	
-	public long getSourceConnectionTestInterval() {
-		return sourceConnectionTestInterval;
-	}
-	public void setSourceConnectionTestInterval(Long sourceConnectionTestInterval) {
-		this.sourceConnectionTestInterval = sourceConnectionTestInterval.longValue();
-	}
-	public int getSourceConnectionTimeout() {
-		return sourceConnectionTimeout;
-	}
-	public void setSourceConnectionTimeout(Integer sourceConnectionTimeout) {
-		this.sourceConnectionTimeout = sourceConnectionTimeout.intValue();
-	}
-	public void setModelAuditFields(Boolean modelAuditFields) {
-		this.auditModelFields = modelAuditFields.booleanValue();
-	}
-	public boolean isModelAuditFields() {
-		return this.auditModelFields;
-	}	
-	
-	@Override
-	public BasicConnectionFactory createConnectionFactory() throws ResourceException {
-		return new BasicConnectionFactory() {
-			@Override
-			public SalesforceConnectionImpl getConnection() throws ResourceException {
-				return new SalesforceConnectionImpl(getUsername(), getPassword(), getURL(), getSourceConnectionTestInterval(), getSourceConnectionTimeout());
-			}
-		};
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java (from rev 2774, trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceManagedConnectionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,80 @@
+/*
+ * 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.MalformedURLException;
+import java.net.URL;
+
+import javax.resource.ResourceException;
+
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
+
+public class SalesForceManagedConnectionFactory extends BasicManagedConnectionFactory {
+	private static final long serialVersionUID = 5298591275313314698L;
+	
+	private String username;
+	private String password;
+	private URL URL;
+	
+	public String getUsername() {
+		return username;
+	}
+	public void setUsername(String username) {
+		if (username.trim().length() == 0) {
+			throw new TeiidRuntimeException("Name can not be null"); //$NON-NLS-1$
+		}
+		this.username = username;
+	}
+
+	public String getPassword() {
+		return this.password;
+	}
+	public void setPassword(String password) {
+		this.password = password;
+	}
+	public URL getURL() {
+		return this.URL;
+	}
+	
+	public void setURL(String uRL) {
+		try {
+			this.URL = new URL(uRL);
+		} catch (MalformedURLException e) {
+			throw new TeiidRuntimeException("URL Supplied is not valid URL"+ e.getMessage());//$NON-NLS-1$
+		}
+	}
+	
+	@Override
+	public BasicConnectionFactory createConnectionFactory() throws ResourceException {
+		return new BasicConnectionFactory() {
+			private static final long serialVersionUID = 5028356110047329135L;
+
+			@Override
+			public SalesforceConnectionImpl getConnection() throws ResourceException {
+				return new SalesforceConnectionImpl(getUsername(), getPassword(), getURL());
+			}
+		};
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/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-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,380 +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, long pingInterval, int timeout) throws ResourceException {
-		login(username, password, url, timeout);
-	}
-	
-	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, int timeout) throws ResourceException {
-		if (!isValid()) {
-			LoginResult loginResult = null;
-			sfSoap = null;
-			sfService = null;
-			co = new CallOptions();
-			co.setClient("RedHat/MetaMatrix/"); //$NON-NLS-1$
-
-			try {
-				/*
-				if(null != url) {
-					sfService = new SforceService(url);
-					sfSoap = sfService.getSoap();
-				} else {
-					*/
-					sfService = new SforceService();
-					sfSoap = sfService.getSoap();
-				//}
-				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 {
-		
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java (from rev 2774, trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnectionImpl.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.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();
+	}	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<connector xmlns="http://java.sun.com/xml/ns/j2ee"
-           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-           xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
-           http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd"
-           version="1.5">
-
-   <vendor-name>Red Hat Middleware LLC</vendor-name>
-   <eis-type>Teiid Sales Force Connector</eis-type>
-   <resourceadapter-version>1.0</resourceadapter-version>
-   <license>
-      <description>
- JBoss, Home of Professional Open Source.
- Copyright 2006, Red Hat Middleware LLC, and individual contributors
- as indicated by the @author tags. See the copyright.txt file 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.
-      </description>
-      <license-required>true</license-required>
-   </license>
-   <resourceadapter>
-      <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
-
-      <outbound-resourceadapter>
-         <connection-definition>
-            <managedconnectionfactory-class>org.teiid.resource.adapter.salesforce.SalesForceManagedConnectionFactory</managedconnectionfactory-class>
-
-            <config-property>
-               <description>{$display:"User Name",$description:"Name value for Salesforce authentication",$required:"true"}</description>
-               <config-property-name>username</config-property-name>
-               <config-property-type>java.lang.String</config-property-type>
-            </config-property>
-         
-             <config-property>
-               <description>{$display:"Password",$description:"Password value for Salesforce authentication",$required:"true",$masked:"true"}</description>
-               <config-property-name>password</config-property-name>
-               <config-property-type>java.lang.String</config-property-type>
-            </config-property>
-            
-            <config-property>
-               <description>{$display:"Salesforce URL",$description:"URL for connecting to Salesforce",$advanced:"true"}</description>
-               <config-property-name>URL</config-property-name>
-               <config-property-type>java.lang.String</config-property-type>
-            </config-property>     
-            
-            <config-property>
-               <description>{$display:"Source Connection Test Interval",$advanced:"true"}</description>
-               <config-property-name>SourceConnectionTestInterval</config-property-name>
-               <config-property-type>java.lang.Long</config-property-type>
-               <config-property-value>5000</config-property-value>
-            </config-property>   
-            
-            <config-property>
-               <description>{$display:"Source Connection Timeout",$advanced:"true"}</description>
-               <config-property-name>SourceConnectionTimeout</config-property-name>
-               <config-property-type>java.lang.Integer</config-property-type>
-               <config-property-value>120000</config-property-value>
-            </config-property>           
-            
-            <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
-            <connectionfactory-impl-class>org.teiid.resource.spi.WrappedConnectionFactory</connectionfactory-impl-class>
-            <connection-interface>javax.resource.cci.Connection</connection-interface>
-            <connection-impl-class>org.teiid.resource.spi.WrappedConnection</connection-impl-class>
-
-         </connection-definition>
-         
-         <transaction-support>NoTransaction</transaction-support>
-        
-        <authentication-mechanism>
-            <authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
-            <credential-interface>javax.resource.spi.security.PasswordCredential</credential-interface>
-        </authentication-mechanism>
-        <reauthentication-support>false</reauthentication-support>
-      </outbound-resourceadapter>
-   </resourceadapter>
-</connector>

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml (from rev 2774, trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<connector xmlns="http://java.sun.com/xml/ns/j2ee"
+           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+           xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
+           http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd"
+           version="1.5">
+
+   <vendor-name>Red Hat Middleware LLC</vendor-name>
+   <eis-type>Teiid Sales Force Connector</eis-type>
+   <resourceadapter-version>1.0</resourceadapter-version>
+   <license>
+      <description>
+ JBoss, Home of Professional Open Source.
+ Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ as indicated by the @author tags. See the copyright.txt file 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.
+      </description>
+      <license-required>true</license-required>
+   </license>
+   <resourceadapter>
+      <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
+
+      <outbound-resourceadapter>
+         <connection-definition>
+            <managedconnectionfactory-class>org.teiid.resource.adapter.salesforce.SalesForceManagedConnectionFactory</managedconnectionfactory-class>
+
+            <config-property>
+               <description>{$display:"User Name",$description:"Name value for Salesforce authentication",$required:"true"}</description>
+               <config-property-name>username</config-property-name>
+               <config-property-type>java.lang.String</config-property-type>
+            </config-property>
+         
+             <config-property>
+               <description>{$display:"Password",$description:"Password value for Salesforce authentication",$required:"true",$masked:"true"}</description>
+               <config-property-name>password</config-property-name>
+               <config-property-type>java.lang.String</config-property-type>
+            </config-property>
+            
+            <config-property>
+               <description>{$display:"Salesforce URL",$description:"URL for connecting to Salesforce",$advanced:"true"}</description>
+               <config-property-name>URL</config-property-name>
+               <config-property-type>java.lang.String</config-property-type>
+               <config-property-value>https://www.salesforce.com/services/Soap/u/17.0</config-property-value>
+            </config-property>     
+            
+            <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
+            <connectionfactory-impl-class>org.teiid.resource.spi.WrappedConnectionFactory</connectionfactory-impl-class>
+            <connection-interface>javax.resource.cci.Connection</connection-interface>
+            <connection-impl-class>org.teiid.resource.spi.WrappedConnection</connection-impl-class>
+
+         </connection-definition>
+         
+         <transaction-support>NoTransaction</transaction-support>
+        
+        <authentication-mechanism>
+            <authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
+            <credential-interface>javax.resource.spi.security.PasswordCredential</credential-interface>
+        </authentication-mechanism>
+        <reauthentication-support>false</reauthentication-support>
+      </outbound-resourceadapter>
+   </resourceadapter>
+</connector>

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml
===================================================================
--- trunk/connectors/connector-ws/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/connector-ws/pom.xml (from rev 2777, trunk/connectors/connector-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/connector-ws/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/pom.xml
===================================================================
--- trunk/connectors/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-SNAPSHOT</version>
-  </parent>
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>org.jboss.teiid</groupId>
-  <artifactId>connectors</artifactId>
-  <packaging>pom</packaging>
-  <name>Connectors</name>
-  <description>This project is aggregator for all the supported connectors.</description>
-  <dependencies>
-          
-    <!--  Internal Test Dependencies -->
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-api</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-common-core</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-client</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-engine</artifactId>
-      <scope>test</scope>
-    </dependency>    
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-metadata</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.jboss.teiid</groupId>
-      <artifactId>teiid-metadata</artifactId>
-      <type>test-jar</type>
-      <scope>test</scope>
-    </dependency>        
-
-    <!-- External dependencies -->
-    <dependency>
-        <groupId>org.jboss</groupId>
-        <artifactId>jboss-vfs</artifactId>
-        <scope>test</scope>
-    </dependency>    
-    <dependency>
-        <groupId>org.jboss.man</groupId>
-        <artifactId>jboss-managed</artifactId>
-        <scope>test</scope>
-    </dependency>     
-    
-  </dependencies>
-  
-  <modules>
-    <module>translator-jdbc</module>
-    <module>translator-ldap</module>
-    
-    <module>translator-loopback</module>
-    <module>translator-file</module>
-    <module>translator-salesforce</module>
-    
-    <module>connector-file</module>
-    <module>connector-salesforce</module>
-    <module>connector-ldap</module>
-    <module>salesforce-api</module>
-    <module>connector-ws</module>
-
-    <module>sandbox</module>
-    
-    <module>translator-ws</module>
-  </modules>
-</project>

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml (from rev 2777, trunk/connectors/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.jboss.teiid</groupId>
+  <artifactId>connectors</artifactId>
+  <packaging>pom</packaging>
+  <name>Connectors</name>
+  <description>This project is aggregator for all the supported connectors.</description>
+  <dependencies>
+          
+    <!--  Internal Test Dependencies -->
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-api</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-common-core</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-engine</artifactId>
+      <scope>test</scope>
+    </dependency>    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-metadata</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-metadata</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>        
+
+    <!-- External dependencies -->
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>test</scope>
+    </dependency>    
+    <dependency>
+        <groupId>org.jboss.man</groupId>
+        <artifactId>jboss-managed</artifactId>
+        <scope>test</scope>
+    </dependency>     
+    
+  </dependencies>
+  
+  <modules>
+    <module>translator-jdbc</module>
+    <module>translator-ldap</module>
+    
+    <module>translator-loopback</module>
+    <module>translator-file</module>
+    <module>translator-salesforce</module>
+    
+    <module>connector-file</module>
+    <module>connector-salesforce</module>
+    <module>connector-ldap</module>
+    <module>salesforce-api</module>
+    <module>connector-ws</module>
+
+    <module>sandbox</module>
+    
+    <module>translator-ws</module>
+  </modules>
+</project>

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml
===================================================================
--- trunk/connectors/salesforce-api/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/salesforce-api/pom.xml (from rev 2777, trunk/connectors/salesforce-api/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/salesforce-api/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/sandbox/pom.xml
===================================================================
--- trunk/connectors/sandbox/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/sandbox/pom.xml (from rev 2777, trunk/connectors/sandbox/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/sandbox/translator-yahoo/pom.xml (from rev 2777, trunk/connectors/sandbox/translator-yahoo/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/sandbox/translator-yahoo/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-file/pom.xml
===================================================================
--- trunk/connectors/translator-file/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-file/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-file/pom.xml (from rev 2777, trunk/connectors/translator-file/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-file/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-file/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-jdbc/pom.xml
===================================================================
--- trunk/connectors/translator-jdbc/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-jdbc/pom.xml (from rev 2777, trunk/connectors/translator-jdbc/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,198 +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.jdbc.h2;
-
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.translator.Translator;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.SourceSystemFunctions;
-import org.teiid.translator.jdbc.AliasModifier;
-import org.teiid.translator.jdbc.ConvertModifier;
-import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.ModFunctionModifier;
-import org.teiid.translator.jdbc.hsql.AddDiffModifier;
-import org.teiid.translator.jdbc.oracle.ConcatFunctionModifier;
-
- at Translator(name="h2", description="A translator for open source H2 Database")
-public class H2ExecutionFactory extends JDBCExecutionFactory {
-	
-	@Override
-	public void start() throws TranslatorException {
-		super.start();
-		registerFunctionModifier(SourceSystemFunctions.PARSETIMESTAMP, new AliasModifier("parsedatetime")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.FORMATTIMESTAMP, new AliasModifier("formatdatetime")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day_of_month")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new AliasModifier("day_of_week")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new AliasModifier("day_of_year")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier(SourceSystemFunctions.MOD, getLanguageFactory()));
-		//TODO: this behavior is configurable in h2 starting with 1.1.119
-		registerFunctionModifier(SourceSystemFunctions.CONCAT, new ConcatFunctionModifier(getLanguageFactory()));
-		
-		registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new AddDiffModifier(true, getLanguageFactory())); 
-		registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new AddDiffModifier(false, getLanguageFactory())); 
-	
-		ConvertModifier convert = new ConvertModifier();
-		convert.addTypeMapping("boolean", FunctionModifier.BOOLEAN); //$NON-NLS-1$
-		convert.addTypeMapping("tinyint", FunctionModifier.BYTE); //$NON-NLS-1$
-		convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
-		convert.addTypeMapping("int", FunctionModifier.INTEGER); //$NON-NLS-1$
-		convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
-		convert.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
-		convert.addTypeMapping("double", FunctionModifier.DOUBLE); //$NON-NLS-1$
-		convert.addTypeMapping("decimal", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
-		convert.addTypeMapping("decimal(38,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
-		convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
-		convert.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
-		convert.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
-		convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
-		convert.addTypeMapping("varchar", FunctionModifier.STRING); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);		
-	}
-	
-    @Override
-    public String translateLiteralDate(Date dateValue) {
-        return "DATE '" + formatDateValue(dateValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
-    }
-
-    @Override
-    public String translateLiteralTime(Time timeValue) {
-        return "TIME '" + formatDateValue(timeValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
-    }
-    
-    @Override
-    public String translateLiteralTimestamp(Timestamp timestampValue) {
-        return "TIMESTAMP '" + formatDateValue(timestampValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$ 
-    }
-	
-    @Override
-    public List<String> getSupportedFunctions() {
-        List<String> supportedFunctions = new ArrayList<String>();
-        supportedFunctions.addAll(super.getSupportedFunctions());
-
-        supportedFunctions.add(SourceSystemFunctions.ABS); 
-        supportedFunctions.add(SourceSystemFunctions.ACOS); 
-        supportedFunctions.add(SourceSystemFunctions.ASIN);
-        supportedFunctions.add(SourceSystemFunctions.ATAN);
-        supportedFunctions.add(SourceSystemFunctions.ATAN2);
-        supportedFunctions.add(SourceSystemFunctions.BITAND);
-        //supportedFunctions.add(SourceSystemFunctions.BITNOT);
-        supportedFunctions.add(SourceSystemFunctions.BITOR);
-        supportedFunctions.add(SourceSystemFunctions.BITXOR);
-        supportedFunctions.add(SourceSystemFunctions.CEILING);
-        supportedFunctions.add(SourceSystemFunctions.COS);
-        supportedFunctions.add(SourceSystemFunctions.COT);
-        supportedFunctions.add(SourceSystemFunctions.DEGREES);
-        supportedFunctions.add(SourceSystemFunctions.EXP);
-        supportedFunctions.add(SourceSystemFunctions.FLOOR);
-        supportedFunctions.add(SourceSystemFunctions.LOG);
-        supportedFunctions.add(SourceSystemFunctions.LOG10);
-        supportedFunctions.add(SourceSystemFunctions.MOD);
-        supportedFunctions.add(SourceSystemFunctions.PI);
-        supportedFunctions.add(SourceSystemFunctions.POWER);
-        supportedFunctions.add(SourceSystemFunctions.RADIANS);
-        supportedFunctions.add(SourceSystemFunctions.ROUND);
-        supportedFunctions.add(SourceSystemFunctions.SIGN);
-        supportedFunctions.add(SourceSystemFunctions.SIN);
-        supportedFunctions.add(SourceSystemFunctions.SQRT);
-        supportedFunctions.add(SourceSystemFunctions.TAN);
-
-        supportedFunctions.add(SourceSystemFunctions.ASCII);
-        supportedFunctions.add(SourceSystemFunctions.CHAR);
-        supportedFunctions.add(SourceSystemFunctions.CONCAT);
-        supportedFunctions.add(SourceSystemFunctions.INSERT);
-        supportedFunctions.add(SourceSystemFunctions.LCASE);
-        supportedFunctions.add(SourceSystemFunctions.LEFT);
-        supportedFunctions.add(SourceSystemFunctions.LENGTH);
-        supportedFunctions.add(SourceSystemFunctions.LOCATE);
-        supportedFunctions.add(SourceSystemFunctions.LPAD);
-        supportedFunctions.add(SourceSystemFunctions.LTRIM);
-        supportedFunctions.add(SourceSystemFunctions.REPEAT);
-        supportedFunctions.add(SourceSystemFunctions.REPLACE);
-        supportedFunctions.add(SourceSystemFunctions.RIGHT);
-        supportedFunctions.add(SourceSystemFunctions.RPAD);
-        supportedFunctions.add(SourceSystemFunctions.RTRIM);
-        supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
-        supportedFunctions.add(SourceSystemFunctions.UCASE);
-        
-        supportedFunctions.add(SourceSystemFunctions.DAYNAME);
-        supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
-        supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
-        supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
-        
-        supportedFunctions.add(SourceSystemFunctions.FORMATTIMESTAMP); 
-        supportedFunctions.add(SourceSystemFunctions.HOUR);
-        supportedFunctions.add(SourceSystemFunctions.MINUTE);
-        supportedFunctions.add(SourceSystemFunctions.MONTH);
-        supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
-        
-        supportedFunctions.add(SourceSystemFunctions.PARSETIMESTAMP);
-        supportedFunctions.add(SourceSystemFunctions.QUARTER);
-        supportedFunctions.add(SourceSystemFunctions.SECOND);
-        supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
-        supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
-        //supportedFunctions.add(SourceSystemFunctions.TIMESTAMPCREATE);
-        supportedFunctions.add(SourceSystemFunctions.WEEK);
-        supportedFunctions.add(SourceSystemFunctions.YEAR);
-
-        supportedFunctions.add(SourceSystemFunctions.CONVERT);
-        supportedFunctions.add(SourceSystemFunctions.IFNULL);
-        supportedFunctions.add(SourceSystemFunctions.COALESCE);
-        return supportedFunctions;
-    }
-	
-    @Override
-    public boolean supportsInlineViews() {
-        return true;
-    }
-    
-    @Override
-    public boolean supportsRowLimit() {
-        return true;
-    }
-
-    @Override
-    public boolean supportsRowOffset() {
-    	return true;
-    }
-    
-    @Override
-    public boolean supportsExcept() {
-        return true;
-    }
-    
-    @Override
-    public boolean supportsIntersect() {
-        return true;
-    }
-    
-    @Override
-    public boolean supportsAggregatesEnhancedNumeric() {
-    	return true;
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java (from rev 2765, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,200 @@
+/*
+ * 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.jdbc.h2;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.SourceSystemFunctions;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.hsql.AddDiffModifier;
+import org.teiid.translator.jdbc.oracle.ConcatFunctionModifier;
+
+ at Translator(name="h2", description="A translator for open source H2 Database")
+public class H2ExecutionFactory extends JDBCExecutionFactory {
+	
+	@Override
+	public void start() throws TranslatorException {
+		super.start();
+		registerFunctionModifier(SourceSystemFunctions.PARSETIMESTAMP, new AliasModifier("parsedatetime")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.FORMATTIMESTAMP, new AliasModifier("formatdatetime")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day_of_month")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new AliasModifier("day_of_week")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new AliasModifier("day_of_year")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.UNESCAPE, new AliasModifier("stringdecode")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier(SourceSystemFunctions.MOD, getLanguageFactory()));
+		//TODO: this behavior is configurable in h2 starting with 1.1.119
+		registerFunctionModifier(SourceSystemFunctions.CONCAT, new ConcatFunctionModifier(getLanguageFactory()));
+		
+		registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new AddDiffModifier(true, getLanguageFactory())); 
+		registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new AddDiffModifier(false, getLanguageFactory())); 
+	
+		ConvertModifier convert = new ConvertModifier();
+		convert.addTypeMapping("boolean", FunctionModifier.BOOLEAN); //$NON-NLS-1$
+		convert.addTypeMapping("tinyint", FunctionModifier.BYTE); //$NON-NLS-1$
+		convert.addTypeMapping("smallint", FunctionModifier.SHORT); //$NON-NLS-1$
+		convert.addTypeMapping("int", FunctionModifier.INTEGER); //$NON-NLS-1$
+		convert.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
+		convert.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+		convert.addTypeMapping("double", FunctionModifier.DOUBLE); //$NON-NLS-1$
+		convert.addTypeMapping("decimal", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+		convert.addTypeMapping("decimal(38,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+		convert.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
+		convert.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
+		convert.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+		convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+		convert.addTypeMapping("varchar", FunctionModifier.STRING); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);		
+	}
+	
+    @Override
+    public String translateLiteralDate(Date dateValue) {
+        return "DATE '" + formatDateValue(dateValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
+    }
+
+    @Override
+    public String translateLiteralTime(Time timeValue) {
+        return "TIME '" + formatDateValue(timeValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$
+    }
+    
+    @Override
+    public String translateLiteralTimestamp(Timestamp timestampValue) {
+        return "TIMESTAMP '" + formatDateValue(timestampValue) + "'"; //$NON-NLS-1$//$NON-NLS-2$ 
+    }
+	
+    @Override
+    public List<String> getSupportedFunctions() {
+        List<String> supportedFunctions = new ArrayList<String>();
+        supportedFunctions.addAll(super.getSupportedFunctions());
+
+        supportedFunctions.add(SourceSystemFunctions.ABS); 
+        supportedFunctions.add(SourceSystemFunctions.ACOS); 
+        supportedFunctions.add(SourceSystemFunctions.ASIN);
+        supportedFunctions.add(SourceSystemFunctions.ATAN);
+        supportedFunctions.add(SourceSystemFunctions.ATAN2);
+        supportedFunctions.add(SourceSystemFunctions.BITAND);
+        //supportedFunctions.add(SourceSystemFunctions.BITNOT);
+        supportedFunctions.add(SourceSystemFunctions.BITOR);
+        supportedFunctions.add(SourceSystemFunctions.BITXOR);
+        supportedFunctions.add(SourceSystemFunctions.CEILING);
+        supportedFunctions.add(SourceSystemFunctions.COS);
+        supportedFunctions.add(SourceSystemFunctions.COT);
+        supportedFunctions.add(SourceSystemFunctions.DEGREES);
+        supportedFunctions.add(SourceSystemFunctions.EXP);
+        supportedFunctions.add(SourceSystemFunctions.FLOOR);
+        supportedFunctions.add(SourceSystemFunctions.LOG);
+        supportedFunctions.add(SourceSystemFunctions.LOG10);
+        supportedFunctions.add(SourceSystemFunctions.MOD);
+        supportedFunctions.add(SourceSystemFunctions.PI);
+        supportedFunctions.add(SourceSystemFunctions.POWER);
+        supportedFunctions.add(SourceSystemFunctions.RADIANS);
+        supportedFunctions.add(SourceSystemFunctions.ROUND);
+        supportedFunctions.add(SourceSystemFunctions.SIGN);
+        supportedFunctions.add(SourceSystemFunctions.SIN);
+        supportedFunctions.add(SourceSystemFunctions.SQRT);
+        supportedFunctions.add(SourceSystemFunctions.TAN);
+
+        supportedFunctions.add(SourceSystemFunctions.ASCII);
+        supportedFunctions.add(SourceSystemFunctions.CHAR);
+        supportedFunctions.add(SourceSystemFunctions.CONCAT);
+        supportedFunctions.add(SourceSystemFunctions.INSERT);
+        supportedFunctions.add(SourceSystemFunctions.LCASE);
+        supportedFunctions.add(SourceSystemFunctions.LEFT);
+        supportedFunctions.add(SourceSystemFunctions.LENGTH);
+        supportedFunctions.add(SourceSystemFunctions.LOCATE);
+        supportedFunctions.add(SourceSystemFunctions.LPAD);
+        supportedFunctions.add(SourceSystemFunctions.LTRIM);
+        supportedFunctions.add(SourceSystemFunctions.REPEAT);
+        supportedFunctions.add(SourceSystemFunctions.REPLACE);
+        supportedFunctions.add(SourceSystemFunctions.RIGHT);
+        supportedFunctions.add(SourceSystemFunctions.RPAD);
+        supportedFunctions.add(SourceSystemFunctions.RTRIM);
+        supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+        supportedFunctions.add(SourceSystemFunctions.UCASE);
+        supportedFunctions.add(SourceSystemFunctions.UNESCAPE);
+        
+        supportedFunctions.add(SourceSystemFunctions.DAYNAME);
+        supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
+        supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
+        supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
+        
+        supportedFunctions.add(SourceSystemFunctions.FORMATTIMESTAMP); 
+        supportedFunctions.add(SourceSystemFunctions.HOUR);
+        supportedFunctions.add(SourceSystemFunctions.MINUTE);
+        supportedFunctions.add(SourceSystemFunctions.MONTH);
+        supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
+        
+        supportedFunctions.add(SourceSystemFunctions.PARSETIMESTAMP);
+        supportedFunctions.add(SourceSystemFunctions.QUARTER);
+        supportedFunctions.add(SourceSystemFunctions.SECOND);
+        supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
+        supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
+        //supportedFunctions.add(SourceSystemFunctions.TIMESTAMPCREATE);
+        supportedFunctions.add(SourceSystemFunctions.WEEK);
+        supportedFunctions.add(SourceSystemFunctions.YEAR);
+
+        supportedFunctions.add(SourceSystemFunctions.CONVERT);
+        supportedFunctions.add(SourceSystemFunctions.IFNULL);
+        supportedFunctions.add(SourceSystemFunctions.COALESCE);
+        return supportedFunctions;
+    }
+	
+    @Override
+    public boolean supportsInlineViews() {
+        return true;
+    }
+    
+    @Override
+    public boolean supportsRowLimit() {
+        return true;
+    }
+
+    @Override
+    public boolean supportsRowOffset() {
+    	return true;
+    }
+    
+    @Override
+    public boolean supportsExcept() {
+        return true;
+    }
+    
+    @Override
+    public boolean supportsIntersect() {
+        return true;
+    }
+    
+    @Override
+    public boolean supportsAggregatesEnhancedNumeric() {
+    	return true;
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,94 +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.jdbc.modeshape;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.NamedTable;
-import org.teiid.language.SQLConstants;
-import org.teiid.metadata.Column;
-import org.teiid.translator.jdbc.FunctionModifier;
-
-
-/**
- * Function to translate ColumnReferences to selector names
- * @since 7.1
- */
-public class IdentifierFunctionModifier extends FunctionModifier {
-
-    public List<?> translate(Function function) {
-    	
-    	List<Object> objs = new ArrayList<Object>();
-    	
-    	List<Expression> parms = function.getParameters();
-    	
-    	objs.add(function.getName().substring(function.getName().indexOf('_') + 1)); 
-    	objs.add(SQLConstants.Tokens.LPAREN);
-    	
-    	for (Iterator<Expression> iter = parms.iterator(); iter.hasNext();) 
-    	{
-    		Expression expr = iter.next();
-    		if (expr instanceof ColumnReference) {
-    			boolean dotAll = false;
-    			boolean useSelector = false;
-    			ColumnReference cr = (ColumnReference)expr;
-    			Column c = cr.getMetadataObject();
-    			if (c != null) {
-    				if ("\"mode:properties\"".equalsIgnoreCase(c.getNameInSource())) { //$NON-NLS-1$
-    					dotAll = true;
-    					useSelector = true;
-    				} else if ("\"mode:path\"".equalsIgnoreCase(c.getNameInSource())) { //$NON-NLS-1$
-    					useSelector = true;
-    				}
-    			}
-    			if (useSelector) {
-		    		NamedTable nt = ((ColumnReference)expr).getTable();
-		    		if (nt.getCorrelationName() != null) {
-		    			objs.add(nt.getCorrelationName());
-		    		} else {
-		    			objs.add(nt);
-		    		}
-    			} else {
-    				objs.add(expr);
-    			}
-	    		if (dotAll) {
-	    			objs.add(".*"); //$NON-NLS-1$
-	    		}
-    		} else {
-    			objs.add(expr);
-    		}
-    		if (iter.hasNext()) {
-    			objs.add(", "); //$NON-NLS-1$
-    		}
-     	}
-
-    	objs.add(SQLConstants.Tokens.RPAREN);
-        return objs; 
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java (from rev 2774, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/IdentifierFunctionModifier.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,94 @@
+/*
+ * 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.jdbc.modeshape;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.NamedTable;
+import org.teiid.language.SQLConstants;
+import org.teiid.metadata.Column;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+/**
+ * Function to translate ColumnReferences to selector names
+ * @since 7.1
+ */
+public class IdentifierFunctionModifier extends FunctionModifier {
+
+    public List<?> translate(Function function) {
+    	
+    	List<Object> objs = new ArrayList<Object>();
+    	
+    	List<Expression> parms = function.getParameters();
+    	
+    	objs.add(function.getName().substring(function.getName().indexOf('_') + 1)); 
+    	objs.add(SQLConstants.Tokens.LPAREN);
+    	
+    	for (Iterator<Expression> iter = parms.iterator(); iter.hasNext();) 
+    	{
+    		Expression expr = iter.next();
+    		if (expr instanceof ColumnReference) {
+    			boolean dotAll = false;
+    			boolean useSelector = false;
+    			ColumnReference cr = (ColumnReference)expr;
+    			Column c = cr.getMetadataObject();
+    			if (c != null) {
+    				if ("\"mode:properties\"".equalsIgnoreCase(c.getNameInSource())) { //$NON-NLS-1$
+    					dotAll = true;
+    					useSelector = true;
+    				} else if ("\"jcr:path\"".equalsIgnoreCase(c.getNameInSource())) { //$NON-NLS-1$
+    					useSelector = true;
+    				}
+    			}
+    			if (useSelector) {
+		    		NamedTable nt = ((ColumnReference)expr).getTable();
+		    		if (nt.getCorrelationName() != null) {
+		    			objs.add(nt.getCorrelationName());
+		    		} else {
+		    			objs.add(nt);
+		    		}
+    			} else {
+    				objs.add(expr);
+    			}
+	    		if (dotAll) {
+	    			objs.add(".*"); //$NON-NLS-1$
+	    		}
+    		} else {
+    			objs.add(expr);
+    		}
+    		if (iter.hasNext()) {
+    			objs.add(", "); //$NON-NLS-1$
+    		}
+     	}
+
+    	objs.add(SQLConstants.Tokens.RPAREN);
+        return objs; 
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,120 +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.jdbc.modeshape;
-
-import java.util.List;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.language.Command;
-import org.teiid.metadata.Column;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
-import org.teiid.metadata.Table;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.unittest.RealMetadataFactory;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-/**
- */
- at SuppressWarnings("nls")
-public class TestModeShapeSqlTranslator {
-
-	private static ModeShapeExecutionFactory TRANSLATOR;
-	private static TranslationUtility UTIL;
-    private static String UDF = "/JCRFunctions.xmi"; //$NON-NLS-1$;
-
-    @BeforeClass
-    public static void setUp() throws TranslatorException {
-        TRANSLATOR = new ModeShapeExecutionFactory();
-        TRANSLATOR.setUseBindVariables(false);
-        TRANSLATOR.start();
-        UTIL = new TranslationUtility(getMetadata());
-        TranslationHelper.loadUDFs(UDF, UTIL);
-    }
-    
-    public static TransformationMetadata getMetadata() {
-    	MetadataStore store = new MetadataStore();
-    	Schema modeshape = RealMetadataFactory.createPhysicalModel("modeshape", store);
-    	Table nt_base = RealMetadataFactory.createPhysicalGroup("nt_base", modeshape);
-    	nt_base.setNameInSource("\"nt:base\"");
-		List<Column> cols = RealMetadataFactory.createElements(nt_base, new String[] { "mode_path",
-				"mode_properties", "jcr_primaryType", "prop" }, new String[] {
-				TypeFacility.RUNTIME_NAMES.STRING,
-				TypeFacility.RUNTIME_NAMES.STRING,
-				TypeFacility.RUNTIME_NAMES.STRING,
-				TypeFacility.RUNTIME_NAMES.STRING });
-		cols.get(0).setNameInSource("\"mode:path\"");
-		cols.get(1).setNameInSource("\"mode:properties\"");
-		cols.get(2).setNameInSource("\"jcr:primaryType\"");
-    	return RealMetadataFactory.createTransformationMetadata(store, "modeshape");
-    }
-
-	public void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
-		Command obj = UTIL.parseCommand(input, true, true);
-		TranslationHelper.helpTestVisitor(expectedOutput, TRANSLATOR, obj);
-	}
-	
-	@Test
-	public void testSelectAllFromBase() throws Exception {
-		String input = "select * from nt_base"; //$NON-NLS-1$
-		String output = "SELECT g_0.\"mode:path\", g_0.\"mode:properties\", g_0.\"jcr:primaryType\", g_0.prop FROM \"nt:base\" AS g_0"; //$NON-NLS-1$
-
-		helpTestVisitor(input, output);
-
-	}
-	
-	@Test
-	public void testPredicate() throws Exception {
-
-		String input = "SELECT x.jcr_primaryType from nt_base inner join nt_base as x on jcr_issamenode(nt_base.mode_path, x.mode_path) = true where jcr_isdescendantnode(nt_base.mode_path, 'x/y/z') = true and jcr_reference(nt_base.mode_properties) = 'x'"; //$NON-NLS-1$
-		String output = "SELECT g_1.\"jcr:primaryType\" FROM \"nt:base\" AS g_0 INNER JOIN \"nt:base\" AS g_1 ON issamenode(g_0, g_1) WHERE isdescendantnode(g_0, 'x/y/z') AND reference(g_0.*) = 'x'"; //$NON-NLS-1$
-
-		helpTestVisitor(input, output);
-
-	}
-
-	@Test
-	public void testOrderBy() throws Exception {
-
-		String input = "SELECT jcr_primaryType from nt_base ORDER BY jcr_primaryType"; //$NON-NLS-1$
-		String output = "SELECT g_0.\"jcr:primaryType\" AS c_0 FROM \"nt:base\" AS g_0 ORDER BY c_0"; //$NON-NLS-1$
-
-		helpTestVisitor(input, output);
-
-	}
-
-	@Test
-	public void testUsingLike() throws Exception {
-
-		String input = "SELECT jcr_primaryType from nt_base WHERE jcr_primaryType LIKE '%relational%'"; //$NON-NLS-1$
-		String output = "SELECT g_0.\"jcr:primaryType\" FROM \"nt:base\" AS g_0 WHERE g_0.\"jcr:primaryType\" LIKE '%relational%'"; //$NON-NLS-1$
-
-		helpTestVisitor(input, output);
-
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java (from rev 2774, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/modeshape/TestModeShapeSqlTranslator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,120 @@
+/*
+ * 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.jdbc.modeshape;
+
+import java.util.List;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.language.Command;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+/**
+ */
+ at SuppressWarnings("nls")
+public class TestModeShapeSqlTranslator {
+
+	private static ModeShapeExecutionFactory TRANSLATOR;
+	private static TranslationUtility UTIL;
+    private static String UDF = "/JCRFunctions.xmi"; //$NON-NLS-1$;
+
+    @BeforeClass
+    public static void setUp() throws TranslatorException {
+        TRANSLATOR = new ModeShapeExecutionFactory();
+        TRANSLATOR.setUseBindVariables(false);
+        TRANSLATOR.start();
+        UTIL = new TranslationUtility(getMetadata());
+        TranslationHelper.loadUDFs(UDF, UTIL);
+    }
+    
+    public static TransformationMetadata getMetadata() {
+    	MetadataStore store = new MetadataStore();
+    	Schema modeshape = RealMetadataFactory.createPhysicalModel("modeshape", store);
+    	Table nt_base = RealMetadataFactory.createPhysicalGroup("nt_base", modeshape);
+    	nt_base.setNameInSource("\"nt:base\"");
+		List<Column> cols = RealMetadataFactory.createElements(nt_base, new String[] { "jcr_path",
+				"mode_properties", "jcr_primaryType", "prop" }, new String[] {
+				TypeFacility.RUNTIME_NAMES.STRING,
+				TypeFacility.RUNTIME_NAMES.STRING,
+				TypeFacility.RUNTIME_NAMES.STRING,
+				TypeFacility.RUNTIME_NAMES.STRING });
+		cols.get(0).setNameInSource("\"jcr:path\"");
+		cols.get(1).setNameInSource("\"mode:properties\"");
+		cols.get(2).setNameInSource("\"jcr:primaryType\"");
+    	return RealMetadataFactory.createTransformationMetadata(store, "modeshape");
+    }
+
+	public void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
+		Command obj = UTIL.parseCommand(input, true, true);
+		TranslationHelper.helpTestVisitor(expectedOutput, TRANSLATOR, obj);
+	}
+	
+	@Test
+	public void testSelectAllFromBase() throws Exception {
+		String input = "select * from nt_base"; //$NON-NLS-1$
+		String output = "SELECT g_0.\"jcr:path\", g_0.\"mode:properties\", g_0.\"jcr:primaryType\", g_0.prop FROM \"nt:base\" AS g_0"; //$NON-NLS-1$
+
+		helpTestVisitor(input, output);
+
+	}
+	
+	@Test
+	public void testPredicate() throws Exception {
+
+		String input = "SELECT x.jcr_primaryType from nt_base inner join nt_base as x on jcr_issamenode(nt_base.jcr_path, x.jcr_path) = true where jcr_isdescendantnode(nt_base.jcr_path, 'x/y/z') = true and jcr_reference(nt_base.mode_properties) = 'x'"; //$NON-NLS-1$
+		String output = "SELECT g_1.\"jcr:primaryType\" FROM \"nt:base\" AS g_0 INNER JOIN \"nt:base\" AS g_1 ON issamenode(g_0, g_1) WHERE isdescendantnode(g_0, 'x/y/z') AND reference(g_0.*) = 'x'"; //$NON-NLS-1$
+
+		helpTestVisitor(input, output);
+
+	}
+
+	@Test
+	public void testOrderBy() throws Exception {
+
+		String input = "SELECT jcr_primaryType from nt_base ORDER BY jcr_primaryType"; //$NON-NLS-1$
+		String output = "SELECT g_0.\"jcr:primaryType\" AS c_0 FROM \"nt:base\" AS g_0 ORDER BY c_0"; //$NON-NLS-1$
+
+		helpTestVisitor(input, output);
+
+	}
+
+	@Test
+	public void testUsingLike() throws Exception {
+
+		String input = "SELECT jcr_primaryType from nt_base WHERE jcr_primaryType LIKE '%relational%'"; //$NON-NLS-1$
+		String output = "SELECT g_0.\"jcr:primaryType\" FROM \"nt:base\" AS g_0 WHERE g_0.\"jcr:primaryType\" LIKE '%relational%'"; //$NON-NLS-1$
+
+		helpTestVisitor(input, output);
+
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml
===================================================================
--- trunk/connectors/translator-ldap/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-ldap/pom.xml (from rev 2777, trunk/connectors/translator-ldap/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ldap/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-loopback/pom.xml
===================================================================
--- trunk/connectors/translator-loopback/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-loopback/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-loopback/pom.xml (from rev 2777, trunk/connectors/translator-loopback/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-loopback/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-loopback/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-salesforce/pom.xml
===================================================================
--- trunk/connectors/translator-salesforce/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-salesforce/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-salesforce/pom.xml (from rev 2777, trunk/connectors/translator-salesforce/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-salesforce/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-salesforce/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/connectors/translator-ws/pom.xml
===================================================================
--- trunk/connectors/translator-ws/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ws/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/connectors/translator-ws/pom.xml (from rev 2777, trunk/connectors/translator-ws/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ws/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/connectors/translator-ws/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/console/pom.xml
===================================================================
--- trunk/console/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,181 +0,0 @@
-<?xml version="1.0"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-	<parent>
-		<artifactId>teiid-parent</artifactId>
-		<groupId>org.jboss.teiid</groupId>
-		<version>7.3.0.Alpha1-SNAPSHOT</version>
-	</parent>
-
-	<modelVersion>4.0.0</modelVersion>
-	<artifactId>teiid-console</artifactId>
-	<name>Console</name>
-	<description>This project is for the RHQ plugin that supports the TEIID Console </description>
-
-	<properties>
-		<!--
-			<org.jboss.jopr.as4.version>1.2.0.GA</org.jboss.jopr.as4.version>
-		-->
-		<org.jboss.jopr.as5.version>1.2.0.GA</org.jboss.jopr.as5.version>
-		<jopr.jboss.as5.plugin.version>1.4.0.B01</jopr.jboss.as5.plugin.version>
-		<org.rhq.version>1.3.0.GA</org.rhq.version>
-		<apache.ant.version>1.7.0</apache.ant.version>
-
-
-	</properties>
-
-	<dependencies>
-		<!--
-			Below are the core modules that are required dependencies of all
-			plugins
-		-->
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-domain</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope>
-			<!--
-				provided by the agent/plugin-container
-			-->
-		</dependency>
-
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-plugin-api</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-native-system</artifactId>
-			<version>${org.rhq.version}</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-jmx-plugin</artifactId>
-			<version>${org.rhq.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.rhq</groupId>
-			<artifactId>rhq-core-util</artifactId>
-			<version>${org.rhq.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>mc4j</groupId>
-			<artifactId>org-mc4j-ems</artifactId>
-			<version>1.2.6</version>
-		</dependency>
-
-		<!--
-			TODO: This is a fix for the Javac bug requiring annotations to be
-			available when compiling dependent classes. It is fixed in JDK 6.
-		-->
-		<dependency>
-			<groupId>javax.persistence</groupId>
-			<artifactId>persistence-api</artifactId>
-			<version>1.0</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-
-		<!--
-			TODO: This is a fix for the Javac bug requiring annotations to be
-			available when compiling dependent classes; it is fixed in JDK 6.
-		-->
-		<dependency>
-			<groupId>jboss.jboss-embeddable-ejb3</groupId>
-			<artifactId>hibernate-all</artifactId>
-			<version>1.0.0.Alpha9</version>
-			<scope>provided</scope> <!-- provided by the agent/plugin-container -->
-		</dependency>
-
-		<dependency>
-			<groupId>commons-logging</groupId>
-			<artifactId>commons-logging</artifactId>
-			<version>1.1</version>
-			<scope>provided</scope>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<scope>provided</scope>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-client</artifactId>
-			<type>test-jar</type>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.teiid</groupId>
-			<artifactId>teiid-common-core</artifactId>
-			<type>test-jar</type>
-		</dependency>
-		<dependency>
-			<groupId>org.jboss.jopr</groupId>
-			<artifactId>jopr-embedded-jbas5</artifactId>
-			<type>war</type>
-			<version>${org.jboss.jopr.as5.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.integration</groupId>
-			<artifactId>jboss-profileservice-spi</artifactId>
-			<version>5.1.0.CR2</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.jboss.on</groupId>
-			<artifactId>jopr-jboss-as-5-plugin</artifactId>
-			<version>${jopr.jboss.as5.plugin.version}</version>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.ant</groupId>
-			<artifactId>ant</artifactId>
-		</dependency>
-
-		<dependency>
-			<groupId>org.apache.commons</groupId>
-			<artifactId>commons-io</artifactId>
-			<version>1.3.2</version>
-		</dependency>
-
-
-
-	</dependencies>
-
-	<build>
-		<outputDirectory>target/classes</outputDirectory>
-		<resources>
-			<resource>
-				<directory>src/main/resources</directory>
-				<filtering>true</filtering>
-				<includes>
-					<include>**/*.xml</include>
-					<include>**/*.properties</include>
-				</includes>
-			</resource>
-			<resource>
-				<directory>src/main/resources</directory>
-				<filtering>false</filtering>
-				<excludes>
-					<exclude>**/*.xml</exclude>
-					<exclude>**/*.properties</exclude>
-				</excludes>
-			</resource>
-		</resources>
-	</build>
-
-
-</project>
\ No newline at end of file

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,287 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.plugins.ManagedObjectImpl;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.CompositeValueSupport;
-import org.jboss.metatype.api.values.EnumValueSupport;
-import org.jboss.metatype.api.values.GenericValue;
-import org.jboss.metatype.api.values.GenericValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.mc4j.ems.connection.EmsConnection;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
-import org.rhq.core.domain.configuration.Property;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementDataNumeric;
-import org.rhq.core.domain.measurement.MeasurementDataTrait;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
-import org.rhq.core.pluginapi.inventory.CreateResourceReport;
-import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceComponent;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.rhq.plugins.jbossas5.util.ConversionUtils;
-import org.teiid.adminapi.impl.PropertyMetadata;
-import org.teiid.rhq.admin.DQPManagementView;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-import org.teiid.rhq.plugin.util.PluginConstants.Operation;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
-
-/**
- * Component class for a Teiid VDB
- * 
- */
-public class DataRoleComponent extends Facet {
-	private final Log LOG = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @seeorg.teiid.rhq.plugin.Facet#start(org.rhq.core.pluginapi.inventory.
-	 * ResourceContext)
-	 */
-	@Override
-	public void start(ResourceContext context) {
-		this.resourceConfiguration = context.getPluginConfiguration();
-		this.componentType = PluginConstants.ComponentType.DATA_ROLE.NAME;
-		super.start(context);
-	}
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.teiid.rhq.plugin.Facet#getAvailability()
-	 */
-	@Override
-	public AvailabilityType getAvailability() {
-		return ((VDBComponent)this.resourceContext.getParentResourceComponent()).getAvailability();
-	}
-
-	@Override
-	String getComponentType() {
-		return PluginConstants.ComponentType.DATA_ROLE.NAME;
-	}
-
-	@Override
-	public void getValues(MeasurementReport arg0,
-			Set<MeasurementScheduleRequest> arg1) throws Exception {
-		// TODO Auto-generated method stub
-		
-	}
-	
-	/**
-	 * The plugin container will call this method when it has a new
-	 * configuration for your managed resource. Your plugin will re-configure
-	 * the managed resource in your own custom way, setting its configuration
-	 * based on the new values of the given configuration.
-	 * 
-	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
-	 */
-	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
-
-		Configuration resourceConfig = report.getConfiguration();
-		resourceConfiguration = resourceConfig.deepCopy();
-
-		// Get the vdb and update date role anyAuthenticated and MappedRoleNames
-		ManagementView managementView = null;
-		ComponentType componentType = new ComponentType(
-				PluginConstants.ComponentType.VDB.TYPE,
-				PluginConstants.ComponentType.VDB.SUBTYPE);
-
-		ManagedComponent managedComponent = null;
-		ManagedProperty anyAuthenticatedMp = null;
-		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
-		try {
-
-			managementView = getConnection().getManagementView();
-			managedComponent = managementView.getComponent(
-					((VDBComponent) this.resourceContext
-							.getParentResourceComponent()).name, componentType);
-			ManagedProperty mp = managedComponent.getProperty("dataPolicies");//$NON-NLS-1$
-			List<ManagedObject> dataRolesListMp = (List<ManagedObject>) MetaValueFactory
-					.getInstance().unwrap(mp.getValue());
-			String name = resourceConfiguration.getSimpleValue("name", null); //$NON-NLS-1$
-			String anyAuthenticated = resourceConfiguration.getSimpleValue(
-					"anyAuthenticated", null); //$NON-NLS-1$
-
-			for (ManagedObject mo : dataRolesListMp) {
-
-				String pname = ProfileServiceUtil.stringValue(mo.getProperty(
-						"name").getValue()); //$NON-NLS-1$
-				if (!pname.equals(name)) {
-					continue;
-				}
-				anyAuthenticatedMp = mo.getProperty("anyAuthenticated"); //$NON-NLS-1$
-				anyAuthenticatedMp.setValue(ProfileServiceUtil.wrap(
-						SimpleMetaType.BOOLEAN, anyAuthenticated));
-				List<Property> mappedRoleNamePropertyList = resourceConfiguration
-				.getList("mappedRoleNameList").getList(); //$NON-NLS-1$
-
-				List<String> mappedRoleNameList = new ArrayList<String>();
-				
-				for (Property mappedRoleNameProperty : mappedRoleNamePropertyList){
-					String mappedRoleNameString = ((PropertyMap)mappedRoleNameProperty).getSimpleValue("name", null); //$NON-NLS-1$
-					mappedRoleNameList.add(mappedRoleNameString);
-				}
-				ManagedProperty mappedRoleNameMp = mo.getProperty("mappedRoleNames"); //$NON-NLS-1$
-				mappedRoleNameMp.setValue(MetaValueFactory.getInstance().create(mappedRoleNameList));
-			}
-
-			try {
-				managementView.updateComponent(managedComponent);
-			} catch (Exception e) {
-				LOG.error("Unable to update component [" //$NON-NLS-1$
-						+ managedComponent.getName() + "] of type " //$NON-NLS-1$
-						+ componentType + ".", e); //$NON-NLS-1$
-				report.setStatus(ConfigurationUpdateStatus.FAILURE);
-				report.setErrorMessageFromThrowable(e);
-			}
-		} catch (Exception e) {
-			LOG.error("Unable to process update request", e); //$NON-NLS-1$
-			report.setStatus(ConfigurationUpdateStatus.FAILURE);
-			report.setErrorMessageFromThrowable(e);
-		}
-
-	}
-
-	@Override
-	public Configuration loadResourceConfiguration() {
-
-		VDBComponent parentComponent = (VDBComponent) this.resourceContext
-				.getParentResourceComponent();
-		ManagedComponent mcVdb = null;
-		Configuration configuration = resourceContext.getPluginConfiguration();
-		try {
-			mcVdb = ProfileServiceUtil.getManagedComponent(getConnection(),
-					new ComponentType(PluginConstants.ComponentType.VDB.TYPE,
-							PluginConstants.ComponentType.VDB.SUBTYPE),
-					parentComponent.name);
-		} catch (NamingException e) {
-			final String msg = "NamingException in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e) {
-			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		// Get data roles from VDB
-		ManagedProperty property = mcVdb.getProperty("dataPolicies"); //$NON-NLS-1$
-		if (property != null) {
-			CollectionValueSupport valueSupport = (CollectionValueSupport) property
-					.getValue();
-			MetaValue[] metaValues = valueSupport.getElements();
-
-			for (MetaValue value : metaValues) {
-				GenericValueSupport genValueSupport = (GenericValueSupport) value;
-				ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
-						.getValue();
-
-				String dataRoleName = ProfileServiceUtil.getSimpleValue(
-						managedObject, "name", String.class); //$NON-NLS-1$
-				Boolean anyAuthenticated = ProfileServiceUtil.getSimpleValue(
-						managedObject, "anyAuthenticated", Boolean.class); //$NON-NLS-1$
-				String description = ProfileServiceUtil.getSimpleValue(
-						managedObject, "description", String.class); //$NON-NLS-1$
-
-				configuration.put(new PropertySimple("name", dataRoleName)); //$NON-NLS-1$
-				configuration.put(new PropertySimple("anyAuthenticated", //$NON-NLS-1$ 
-						anyAuthenticated));
-				configuration
-						.put(new PropertySimple("description", description)); //$NON-NLS-1$
-
-				PropertyList mappedRoleNameList = new PropertyList(
-						"mappedRoleNameList"); //$NON-NLS-1$
-				configuration.put(mappedRoleNameList);
-				ManagedProperty mappedRoleNames = managedObject
-						.getProperty("mappedRoleNames"); //$NON-NLS-1$
-				if (mappedRoleNames != null) { 
-					List<String> props = (List<String>) MetaValueFactory
-							.getInstance().unwrap(mappedRoleNames.getValue());
-					for (String mappedRoleName : props) {
-						PropertyMap mappedRoleNameMap = null;
-
-						mappedRoleNameMap = new PropertyMap("map", //$NON-NLS-1$
-								new PropertySimple("name", mappedRoleName)); //$NON-NLS-1$
-						mappedRoleNameList.add(mappedRoleNameMap);
-					}
-				}
-			}
-		}
-
-		return configuration;
-
-	}
-
-	@Override
-	public CreateResourceReport createResource(
-			CreateResourceReport createResourceReport) {
-
-		createContentBasedResource(createResourceReport);
-		return createResourceReport;
-	}
-
-	@Override
-	public ProfileServiceConnection getConnection() {
-		return ((VDBComponent) this.resourceContext
-				.getParentResourceComponent()).getConnection();
-	}
-
-	@Override
-	public EmsConnection getEmsConnection() {
-		// TODO Auto-generated method stub
-		return null;
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,310 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.metatype.api.types.CollectionMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.MetaTypeFactory;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.mc4j.ems.connection.EmsConnection;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.rhq.core.domain.measurement.AvailabilityType;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
+import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * Component class for a Teiid VDB Data Role
+ * 
+ */
+public class DataRoleComponent extends Facet {
+	private final Log LOG = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @seeorg.teiid.rhq.plugin.Facet#start(org.rhq.core.pluginapi.inventory.
+	 * ResourceContext)
+	 */
+	@Override
+	public void start(ResourceContext context) {
+		this.resourceConfiguration = context.getPluginConfiguration();
+		this.componentType = PluginConstants.ComponentType.DATA_ROLE.NAME;
+		super.start(context);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.teiid.rhq.plugin.Facet#getAvailability()
+	 */
+	@Override
+	public AvailabilityType getAvailability() {
+		return ((VDBComponent) this.resourceContext
+				.getParentResourceComponent()).getAvailability();
+	}
+
+	@Override
+	String getComponentType() {
+		return PluginConstants.ComponentType.DATA_ROLE.NAME;
+	}
+
+	@Override
+	public void getValues(MeasurementReport arg0,
+			Set<MeasurementScheduleRequest> arg1) throws Exception {
+		// TODO Auto-generated method stub
+
+	}
+
+	/**
+	 * The plugin container will call this method when it has a new
+	 * configuration for your managed resource. Your plugin will re-configure
+	 * the managed resource in your own custom way, setting its configuration
+	 * based on the new values of the given configuration.
+	 * 
+	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
+	 */
+	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
+
+		Configuration resourceConfig = report.getConfiguration();
+		resourceConfiguration = resourceConfig.deepCopy();
+
+		// Get the vdb and update date role anyAuthenticated and MappedRoleNames
+		ManagementView managementView = null;
+		ComponentType componentType = new ComponentType(
+				PluginConstants.ComponentType.VDB.TYPE,
+				PluginConstants.ComponentType.VDB.SUBTYPE);
+
+		ManagedComponent managedComponent = null;
+		ManagedProperty anyAuthenticatedMp = null;
+		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
+		try {
+
+			managementView = getConnection().getManagementView();
+			managedComponent = managementView.getComponent(
+					((VDBComponent) this.resourceContext
+							.getParentResourceComponent()).name, componentType);
+			ManagedProperty mp = managedComponent.getProperty("dataPolicies");//$NON-NLS-1$
+			CollectionValueSupport dataRolesListMp = (CollectionValueSupport) mp
+					.getValue();
+			String name = resourceConfiguration.getSimpleValue("name", null); //$NON-NLS-1$
+			String anyAuthenticated = resourceConfiguration.getSimpleValue(
+					"anyAuthenticated", null); //$NON-NLS-1$
+
+			for (MetaValue val : dataRolesListMp.getElements()) {
+				GenericValueSupport genValueSupport = (GenericValueSupport) val;
+				ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+						.getValue();
+
+				for (String dataRolesProp : managedObject.getPropertyNames()) {
+					ManagedProperty property = managedObject
+							.getProperty(dataRolesProp);
+
+					String pname = ProfileServiceUtil.stringValue(managedObject
+							.getProperty("name").getValue()); //$NON-NLS-1$
+					if (!pname.equals(name)) {
+						continue;
+					}
+
+					anyAuthenticatedMp = managedObject
+							.getProperty("anyAuthenticated"); //$NON-NLS-1$
+					anyAuthenticatedMp.setValue(ProfileServiceUtil.wrap(
+							SimpleMetaType.BOOLEAN, anyAuthenticated));
+					List<Property> mappedRoleNamePropertyList = resourceConfiguration.getList("mappedRoleNameList").getList(); //$NON-NLS-1$
+					List<String> mappedRoleNameList = new ArrayList<String>();
+					
+					for (Property mappedRoleNameProperty : mappedRoleNamePropertyList){
+						String mappedRoleNameString = ((PropertyMap)mappedRoleNameProperty).getSimpleValue("name", null); //$NON-NLS-1$
+						mappedRoleNameList.add(mappedRoleNameString);
+					}
+					ManagedProperty mappedRoleNameMp = managedObject.getProperty("mappedRoleNames"); //$NON-NLS-1$
+					mappedRoleNameMp.setValue(convertListOfStringsToMetaValue(mappedRoleNameList));
+				}
+
+				try {
+					managementView.updateComponent(managedComponent);
+					managementView.load();
+				} catch (Exception e) {
+					LOG.error("Unable to update component [" //$NON-NLS-1$
+							+ managedComponent.getName() + "] of type " //$NON-NLS-1$
+							+ componentType + ".", e); //$NON-NLS-1$
+					report.setStatus(ConfigurationUpdateStatus.FAILURE);
+					report.setErrorMessageFromThrowable(e);
+				}
+			}
+		} catch (Exception e) {
+			LOG.error("Unable to process update request", e); //$NON-NLS-1$
+			report.setStatus(ConfigurationUpdateStatus.FAILURE);
+			report.setErrorMessageFromThrowable(e);
+		}
+
+	}
+
+	/**
+	 * @param mappedRoleNameList
+	 */
+	private MetaValue convertListOfStringsToMetaValue(List<String> mappedRoleNameList) {
+		 
+		 MetaValue[] listMemberValues = new MetaValue[mappedRoleNameList.size()];
+		 int memberIndex = 0;
+		 
+		 for (String mappedRoleName : mappedRoleNameList)
+	     {
+	      MetaValue mappedRoleNameValue = SimpleValueSupport.wrap(mappedRoleName);
+	      listMemberValues[memberIndex++] = mappedRoleNameValue;
+	     }
+	     return new CollectionValueSupport( new CollectionMetaType("java.util.List", SimpleMetaType.STRING), //$NON-NLS-1$
+	    		                            listMemberValues);
+	     
+	}
+
+	@Override
+	public Configuration loadResourceConfiguration() {
+
+		VDBComponent parentComponent = (VDBComponent) this.resourceContext
+				.getParentResourceComponent();
+		ManagedComponent mcVdb = null;
+		Configuration configuration = resourceContext.getPluginConfiguration();
+		try {
+			mcVdb = ProfileServiceUtil.getManagedComponent(getConnection(),
+					new ComponentType(PluginConstants.ComponentType.VDB.TYPE,
+							PluginConstants.ComponentType.VDB.SUBTYPE),
+					parentComponent.name);
+		} catch (NamingException e) {
+			final String msg = "NamingException in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e) {
+			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		// Get data roles from VDB
+		ManagedProperty property = mcVdb.getProperty("dataPolicies"); //$NON-NLS-1$
+		if (property != null) {
+			CollectionValueSupport valueSupport = (CollectionValueSupport) property
+					.getValue();
+			MetaValue[] metaValues = valueSupport.getElements();
+
+			for (MetaValue value : metaValues) {
+				GenericValueSupport genValueSupport = (GenericValueSupport) value;
+				ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+						.getValue();
+
+				String dataRoleName = ProfileServiceUtil.getSimpleValue(
+						managedObject, "name", String.class); //$NON-NLS-1$
+				Boolean anyAuthenticated = ProfileServiceUtil.getSimpleValue(
+						managedObject, "anyAuthenticated", Boolean.class); //$NON-NLS-1$
+				String description = ProfileServiceUtil.getSimpleValue(
+						managedObject, "description", String.class); //$NON-NLS-1$
+
+				configuration.put(new PropertySimple("name", dataRoleName)); //$NON-NLS-1$
+				configuration.put(new PropertySimple("anyAuthenticated", //$NON-NLS-1$ 
+						anyAuthenticated));
+				configuration
+						.put(new PropertySimple("description", description)); //$NON-NLS-1$
+
+				PropertyList mappedRoleNameList = new PropertyList(
+						"mappedRoleNameList"); //$NON-NLS-1$
+				configuration.put(mappedRoleNameList);
+				ManagedProperty mappedRoleNames = managedObject
+						.getProperty("mappedRoleNames"); //$NON-NLS-1$
+				if (mappedRoleNames != null) {
+					CollectionValueSupport props = (CollectionValueSupport) mappedRoleNames
+							.getValue();
+					for (MetaValue mappedRoleName : props.getElements()) {
+						PropertyMap mappedRoleNameMap = null;
+
+						try {
+							mappedRoleNameMap = new PropertyMap(
+									"map", //$NON-NLS-1$
+									new PropertySimple(
+											"name", (ProfileServiceUtil.stringValue(mappedRoleName)))); //$NON-NLS-1$
+						} catch (Exception e) {
+							final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+							LOG.error(msg, e);
+						}
+						mappedRoleNameList.add(mappedRoleNameMap);
+					}
+				}
+			}
+		}
+
+		return configuration;
+
+	}
+
+	@Override
+	public CreateResourceReport createResource(
+			CreateResourceReport createResourceReport) {
+
+		createContentBasedResource(createResourceReport);
+		return createResourceReport;
+	}
+
+	@Override
+	public ProfileServiceConnection getConnection() {
+		return ((VDBComponent) this.resourceContext
+				.getParentResourceComponent()).getConnection();
+	}
+
+	@Override
+	public EmsConnection getEmsConnection() {
+		// TODO Auto-generated method stub
+		return null;
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,139 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.plugins.ManagedObjectImpl;
-import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.GenericValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * Discovery component for Data Roles of a VDB
- * 
- */
-public class DataRoleDiscoveryComponent implements ResourceDiscoveryComponent {
-
-	private final Log log = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	public Set<DiscoveredResourceDetails> discoverResources(
-			ResourceDiscoveryContext discoveryContext)
-			throws InvalidPluginConfigurationException, Exception {
-		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
-		VDBComponent parenComponent = (VDBComponent) discoveryContext
-				.getParentResourceComponent();
-		ProfileServiceConnection connection = parenComponent.getConnection();
-
-		ManagedComponent mcVdb = ProfileServiceUtil.getManagedComponent(
-				connection, new ComponentType(
-						PluginConstants.ComponentType.VDB.TYPE,
-						PluginConstants.ComponentType.VDB.SUBTYPE),
-				parenComponent.name);
-
-		// Get data roles from VDB
-		ManagedProperty property = mcVdb.getProperty("dataPolicies");
-		if (property != null) {
-			CollectionValueSupport valueSupport = (CollectionValueSupport) property
-					.getValue();
-			MetaValue[] metaValues = valueSupport.getElements();
-
-			for (MetaValue value : metaValues) {
-				GenericValueSupport genValueSupport = (GenericValueSupport) value;
-				ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
-						.getValue();
-
-				String dataRoleName = ProfileServiceUtil.getSimpleValue(
-						managedObject, "name", String.class);
-				Boolean anyAuthenticated = ProfileServiceUtil.getSimpleValue(
-						managedObject, "anyAuthenticated", Boolean.class);
-				String description = ProfileServiceUtil.getSimpleValue(
-						managedObject, "description", String.class);
-
-				/**
-				 * 
-				 * A discovered resource must have a unique key, that must stay
-				 * the same when the resource is discovered the next time
-				 */
-				DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
-						discoveryContext.getResourceType(), // ResourceType
-						dataRoleName, // Resource Key
-						dataRoleName, // Resource Name
-						null, // Version
-						PluginConstants.ComponentType.DATA_ROLE.DESCRIPTION, // Description
-						discoveryContext.getDefaultPluginConfiguration(), // Plugin
-						// Config
-						null // Process info from a process scan
-				);
-
-				Configuration configuration = detail.getPluginConfiguration();
-
-				configuration.put(new PropertySimple("name", dataRoleName));
-				configuration.put(new PropertySimple("anyAuthenticated",
-						anyAuthenticated));
-				configuration
-						.put(new PropertySimple("description", description));
-
-				PropertyList mappedRoleNameList = new PropertyList(
-						"mappedRoleNameList");
-				configuration.put(mappedRoleNameList);
-				ManagedProperty mappedRoleNames = managedObject
-						.getProperty("mappedRoleNames");
-				if (mappedRoleNames != null) {
-					List<String> props = (List<String>) MetaValueFactory
-							.getInstance().unwrap(mappedRoleNames.getValue());
-					for (String mappedRoleName : props) {
-						mappedRoleNameList.add(new PropertySimple("name", mappedRoleName));
-					}
-
-				}
-				// Add to return values
-				discoveredResources.add(detail);
-				log.debug("Discovered Teiid VDB Data Role: " + dataRoleName);
-			}
-		}
-		
-		return discoveredResources;
-
-	}
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/DataRoleDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,134 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * Discovery component for Data Roles of a VDB
+ * 
+ */
+public class DataRoleDiscoveryComponent implements ResourceDiscoveryComponent {
+
+	private final Log log = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	public Set<DiscoveredResourceDetails> discoverResources(
+			ResourceDiscoveryContext discoveryContext)
+			throws InvalidPluginConfigurationException, Exception {
+		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
+		VDBComponent parenComponent = (VDBComponent) discoveryContext
+				.getParentResourceComponent();
+		ProfileServiceConnection connection = parenComponent.getConnection();
+
+		ManagedComponent mcVdb = ProfileServiceUtil.getManagedComponent(
+				connection, new ComponentType(
+						PluginConstants.ComponentType.VDB.TYPE,
+						PluginConstants.ComponentType.VDB.SUBTYPE),
+				parenComponent.name);
+
+		// Get data roles from VDB
+		ManagedProperty property = mcVdb.getProperty("dataPolicies");
+		if (property != null) {
+			CollectionValueSupport valueSupport = (CollectionValueSupport) property
+					.getValue();
+			MetaValue[] metaValues = valueSupport.getElements();
+
+			for (MetaValue value : metaValues) {
+				GenericValueSupport genValueSupport = (GenericValueSupport) value;
+				ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+						.getValue();
+
+				String dataRoleName = ProfileServiceUtil.getSimpleValue(
+						managedObject, "name", String.class);
+				Boolean anyAuthenticated = ProfileServiceUtil.getSimpleValue(
+						managedObject, "anyAuthenticated", Boolean.class);
+				String description = ProfileServiceUtil.getSimpleValue(
+						managedObject, "description", String.class);
+
+				/**
+				 * 
+				 * A discovered resource must have a unique key, that must stay
+				 * the same when the resource is discovered the next time
+				 */
+				DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
+						discoveryContext.getResourceType(), // ResourceType
+						dataRoleName, // Resource Key
+						dataRoleName, // Resource Name
+						null, // Version
+						PluginConstants.ComponentType.DATA_ROLE.DESCRIPTION, // Description
+						discoveryContext.getDefaultPluginConfiguration(), // Plugin
+						// Config
+						null // Process info from a process scan
+				);
+
+				Configuration configuration = detail.getPluginConfiguration();
+
+				configuration.put(new PropertySimple("name", dataRoleName));
+				configuration.put(new PropertySimple("anyAuthenticated",
+						anyAuthenticated));
+				configuration
+						.put(new PropertySimple("description", description));
+
+				PropertyList mappedRoleNameList = new PropertyList(
+						"mappedRoleNameList");
+				configuration.put(mappedRoleNameList);
+				ManagedProperty mappedRoleNames = managedObject
+						.getProperty("mappedRoleNames");
+				if (mappedRoleNames != null) {
+					CollectionValueSupport props = (CollectionValueSupport)mappedRoleNames.getValue();
+					for (MetaValue mappedRoleName : props.getElements()) {
+						mappedRoleNameList.add(new PropertySimple("name", ProfileServiceUtil.stringValue(mappedRoleName)));
+					}
+
+				}
+				// Add to return values
+				discoveredResources.add(detail);
+				log.debug("Discovered Teiid VDB Data Role: " + dataRoleName);
+			}
+		}
+		
+		return discoveredResources;
+
+	}
+}
\ No newline at end of file

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

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

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,104 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
-import org.rhq.plugins.jbossas5.ApplicationServerComponent;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * This is the parent node for a Teiid system
- */
-public class PlatformDiscoveryComponent implements ResourceDiscoveryComponent {
-
-	private final Log log = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	/**
-	 * Review the javadoc for both {@link ResourceDiscoveryComponent} and
-	 * {@link ResourceDiscoveryContext} to learn what you need to do in this
-	 * method.
-	 * 
-	 * @see ResourceDiscoveryComponent#discoverResources(ResourceDiscoveryContext)
-	 */
-	public Set<DiscoveredResourceDetails> discoverResources(
-			ResourceDiscoveryContext discoveryContext)
-			throws InvalidPluginConfigurationException, Exception {
-
-		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
-		ProfileServiceConnection connection = ((ApplicationServerComponent) discoveryContext.getParentResourceComponent()).getConnection();
-		
-		ManagedComponent mc = ProfileServiceUtil.getManagedComponent(connection,
-				new ComponentType(
-						PluginConstants.ComponentType.Platform.TEIID_TYPE,
-						PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE),
-						PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE);
-		
-		if (mc==null){
-			//No Teiid instance found
-			return discoveredResources;
-		}
-		
-		String version = ProfileServiceUtil.getSimpleValue(mc, "runtimeVersion", String.class); //$NON-NLS-1$
-			
-		/**
-		 * 
-		 * A discovered resource must have a unique key, that must stay the same
-		 * when the resource is discovered the next time
-		 */
-		DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
-				discoveryContext.getResourceType(), // ResourceType
-				mc.getName(), // Resource Key
-				PluginConstants.ComponentType.Platform.TEIID_ENGINE_RESOURCE_NAME, // Resource name
-				version,
-				PluginConstants.ComponentType.Platform.TEIID_ENGINE_RESOURCE_DESCRIPTION, // Description
-				discoveryContext.getDefaultPluginConfiguration(), // Plugin
-				// Config
-				null // Process info from a process scan
-		);
-
-		Configuration configuration = detail.getPluginConfiguration();
-		configuration.put(new PropertySimple(
-				PluginConstants.Operation.Value.LONG_RUNNING_QUERY_LIMIT, 600));
-		detail.setPluginConfiguration(configuration);
-
-		// Add to return values
-		discoveredResources.add(detail);
-		log.debug("Discovered Teiid instance: " + mc.getName()); //$NON-NLS-1$
-		return discoveredResources;
-
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/PlatformDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,103 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.plugins.jbossas5.ApplicationServerComponent;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * This is the parent node for a Teiid system
+ */
+public class PlatformDiscoveryComponent implements ResourceDiscoveryComponent {
+
+	private final Log log = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	/**
+	 * Review the javadoc for both {@link ResourceDiscoveryComponent} and
+	 * {@link ResourceDiscoveryContext} to learn what you need to do in this
+	 * method.
+	 * 
+	 * @see ResourceDiscoveryComponent#discoverResources(ResourceDiscoveryContext)
+	 */
+	public Set<DiscoveredResourceDetails> discoverResources(
+			ResourceDiscoveryContext discoveryContext)
+			throws InvalidPluginConfigurationException, Exception {
+
+		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
+		ProfileServiceConnection connection = ((ApplicationServerComponent) discoveryContext.getParentResourceComponent()).getConnection();
+		
+		ManagedComponent mc = ProfileServiceUtil.getManagedComponent(connection,
+				new ComponentType(
+						PluginConstants.ComponentType.Platform.TEIID_TYPE,
+						PluginConstants.ComponentType.Platform.TEIID_SUB_TYPE),
+						PluginConstants.ComponentType.Platform.TEIID_RUNTIME_ENGINE);
+		
+		if (mc==null){
+			//No Teiid instance found
+			return discoveredResources;
+		}
+		
+		String version = ProfileServiceUtil.getSimpleValue(mc, "runtimeVersion", String.class); //$NON-NLS-1$
+			
+		/**
+		 * 
+		 * A discovered resource must have a unique key, that must stay the same
+		 * when the resource is discovered the next time
+		 */
+		DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
+				discoveryContext.getResourceType(), // ResourceType
+				mc.getName(), // Resource Key
+				PluginConstants.ComponentType.Platform.TEIID_ENGINE_RESOURCE_NAME, // Resource name
+				version,
+				PluginConstants.ComponentType.Platform.TEIID_ENGINE_RESOURCE_DESCRIPTION, // Description
+				discoveryContext.getDefaultPluginConfiguration(), // Plugin
+				// Config
+				null // Process info from a process scan
+		);
+
+		Configuration configuration = detail.getPluginConfiguration();
+		configuration.put(new PropertySimple("displayPreviewVDBS", Boolean.FALSE));
+		detail.setPluginConfiguration(configuration);
+
+		// Add to return values
+		discoveredResources.add(detail);
+		log.debug("Discovered Teiid instance: " + mc.getName()); //$NON-NLS-1$
+		return discoveredResources;
+
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,185 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.Map;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.mc4j.ems.connection.EmsConnection;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.measurement.MeasurementDataNumeric;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.rhq.core.pluginapi.measurement.MeasurementFacet;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * Component class for the Teiid Translator.
- * 
- */
-public class TranslatorComponent extends Facet {
-	private final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	public static interface Config {
-		String COMPONENT_TYPE = "componentType";
-		String COMPONENT_SUBTYPE = "componentSubtype";
-		String COMPONENT_NAME = "componentName";
-		String TEMPLATE_NAME = "template-name";
-		String RESOURCE_NAME = "resourceName";
-	}
-
-	@Override
-	public void start(ResourceContext context) {
-		this.setComponentName(context.getPluginConfiguration().getSimpleValue(	"name", null));
-		this.resourceConfiguration=context.getPluginConfiguration();
-		super.start(context);
-	}
-	
-	/**
-	 * @see org.teiid.rhq.plugin.Facet#getComponentType()
-	 * @since 1.0
-	 */
-	@Override
-	String getComponentType() {
-		return PluginConstants.ComponentType.Translator.NAME;
-	}
-
-	/**
-	 * The plugin container will call this method when your resource component
-	 * has been scheduled to collect some measurements now. It is within this
-	 * method that you actually talk to the managed resource and collect the
-	 * measurement data that is has emitted.
-	 * 
-	 * @see MeasurementFacet#getValues(MeasurementReport, Set)
-	 */
-	public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) {
-		for (MeasurementScheduleRequest request : requests) {
-			String name = request.getName();
-
-			// TODO: based on the request information, you must collect the
-			// requested measurement(s)
-			// you can use the name of the measurement to determine what you
-			// actually need to collect
-			try {
-				Number value = new Integer(1); // dummy measurement value -
-				// this should come from the
-				// managed resource
-				report.addData(new MeasurementDataNumeric(request, value.doubleValue()));
-			} catch (Exception e) {
-				LOG.error("Failed to obtain measurement [" + name 	+ "]. Cause: " + e); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		}
-
-		return;
-	}
-	
-	protected void setOperationArguments(String name,
-			Configuration configuration, Map argumentMap) {
-		//No operations for translators
-	}
-	
-	@Override
-	public Configuration loadResourceConfiguration() {
-
-		ManagedComponent translator = null;
-		try {
-			translator = ProfileServiceUtil
-			.getManagedComponent(getConnection(), new ComponentType(
-					PluginConstants.ComponentType.Translator.TYPE,
-					PluginConstants.ComponentType.Translator.SUBTYPE), this.name);
-		} catch (NamingException e) {
-			final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e) {
-			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-		
-		String translatorName = ProfileServiceUtil.getSimpleValue(	translator, "name", String.class);
-		String description = ProfileServiceUtil.getSimpleValue(	translator, "description", String.class);
-
-		Configuration c = resourceConfiguration;
-		PropertyList list = new PropertyList("translatorList");
-		PropertyMap propMap = null;
-		c.put(list);
-
-		// First get translator specific properties
-		ManagedProperty translatorProps = translator.getProperty("property");
-		getTranslatorValues(translatorProps.getValue(), propMap, list);
-
-		// Now get common properties
-		c.put(new PropertySimple("name", translatorName));
-		c.put(new PropertySimple("description", description));
-		
-		return c;
-
-	}
-	
-	public static <T> void getTranslatorValues(MetaValue pValue,
-			PropertyMap map, PropertyList list) {
-		MetaType metaType = pValue.getMetaType();
-		Map<String, T> unwrappedvalue = null;
-		if (metaType.isComposite()) {
-			unwrappedvalue = (Map<String, T>) MetaValueFactory	.getInstance().unwrap(pValue);
-
-			for (String key : unwrappedvalue.keySet()) {
-				map = new PropertyMap("property");
-				map.put(new PropertySimple("name", key));
-				map.put(new PropertySimple("value", unwrappedvalue.get(key)));
-				map.put(new PropertySimple("description", "Custom property"));
-				list.add(map);
-			}
-		} else {
-			throw new IllegalStateException(pValue + " is not a Composite type");
-		}
-
-	}
-
-	@Override
-	public ProfileServiceConnection getConnection() {
-		return ((PlatformComponent)this.resourceContext.getParentResourceComponent()).getConnection();
-	}
-
-
-	@Override
-	public EmsConnection getEmsConnection() {
-		// TODO Auto-generated method stub
-		return null;
-	}
-	
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,189 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.Map;
+import java.util.Set;
+
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.mc4j.ems.connection.EmsConnection;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.measurement.MeasurementDataNumeric;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.core.pluginapi.measurement.MeasurementFacet;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * Component class for the Teiid Translator.
+ * 
+ */
+public class TranslatorComponent extends Facet {
+	private final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	public static interface Config {
+		String COMPONENT_TYPE = "componentType";
+		String COMPONENT_SUBTYPE = "componentSubtype";
+		String COMPONENT_NAME = "componentName";
+		String TEMPLATE_NAME = "template-name";
+		String RESOURCE_NAME = "resourceName";
+	}
+
+	@Override
+	public void start(ResourceContext context) {
+		this.setComponentName(context.getPluginConfiguration().getSimpleValue(	"name", null));
+		this.resourceConfiguration=context.getPluginConfiguration();
+		super.start(context);
+	}
+	
+	/**
+	 * @see org.teiid.rhq.plugin.Facet#getComponentType()
+	 * @since 1.0
+	 */
+	@Override
+	String getComponentType() {
+		return PluginConstants.ComponentType.Translator.NAME;
+	}
+
+	/**
+	 * The plugin container will call this method when your resource component
+	 * has been scheduled to collect some measurements now. It is within this
+	 * method that you actually talk to the managed resource and collect the
+	 * measurement data that is has emitted.
+	 * 
+	 * @see MeasurementFacet#getValues(MeasurementReport, Set)
+	 */
+	public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) {
+		for (MeasurementScheduleRequest request : requests) {
+			String name = request.getName();
+
+			// TODO: based on the request information, you must collect the
+			// requested measurement(s)
+			// you can use the name of the measurement to determine what you
+			// actually need to collect
+			try {
+				Number value = new Integer(1); // dummy measurement value -
+				// this should come from the
+				// managed resource
+				report.addData(new MeasurementDataNumeric(request, value.doubleValue()));
+			} catch (Exception e) {
+				LOG.error("Failed to obtain measurement [" + name 	+ "]. Cause: " + e); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}
+
+		return;
+	}
+	
+	protected void setOperationArguments(String name,
+			Configuration configuration, Map argumentMap) {
+		//No operations for translators
+	}
+	
+	@Override
+	public Configuration loadResourceConfiguration() {
+
+		ManagedComponent translator = null;
+		try {
+			translator = ProfileServiceUtil
+			.getManagedComponent(getConnection(), new ComponentType(
+					PluginConstants.ComponentType.Translator.TYPE,
+					PluginConstants.ComponentType.Translator.SUBTYPE), this.name);
+		} catch (NamingException e) {
+			final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e) {
+			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+		
+		String translatorName = ProfileServiceUtil.getSimpleValue(	translator, "name", String.class);
+		String description = ProfileServiceUtil.getSimpleValue(	translator, "description", String.class);
+
+		Configuration c = resourceConfiguration;
+		PropertyList list = new PropertyList("translatorList");
+		PropertyMap propMap = null;
+		c.put(list);
+
+		// First get translator specific properties
+		ManagedProperty translatorProps = translator.getProperty("property");
+		try {
+			getTranslatorValues(translatorProps.getValue(), propMap, list);
+		} catch (Exception e) {
+			throw new RuntimeException(e.getMessage());
+		}
+
+		// Now get common properties
+		c.put(new PropertySimple("name", translatorName));
+		c.put(new PropertySimple("description", description));
+		
+		return c;
+
+	}
+	
+	public static <T> void getTranslatorValues(MetaValue pValue,
+			PropertyMap map, PropertyList list) throws Exception {
+		MetaType metaType = pValue.getMetaType();
+		MapCompositeValueSupport unwrappedvalueMap = null;
+		if (metaType.isComposite()) {
+			unwrappedvalueMap = (MapCompositeValueSupport) pValue;
+
+			for (String key : unwrappedvalueMap.getMetaType().keySet()) {
+				map = new PropertyMap("property");
+				map.put(new PropertySimple("name", key));
+				map.put(new PropertySimple("value", ProfileServiceUtil.stringValue((MetaValue)unwrappedvalueMap.get(key))));
+				map.put(new PropertySimple("description", "Custom property"));
+				list.add(map);
+			}
+		} else {
+			throw new IllegalStateException(pValue + " is not a Composite type");
+		}
+
+	}
+
+	@Override
+	public ProfileServiceConnection getConnection() {
+		return ((PlatformComponent)this.resourceContext.getParentResourceComponent()).getConnection();
+	}
+
+
+	@Override
+	public EmsConnection getEmsConnection() {
+		// TODO Auto-generated method stub
+		return null;
+	}
+	
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,137 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.core.util.ApplicationInfo;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * Discovery component for Teiid Translator instances
- * 
- */
-public class TranslatorDiscoveryComponent implements ResourceDiscoveryComponent {
-
-	private final Log log = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	public Set<DiscoveredResourceDetails> discoverResources(
-			ResourceDiscoveryContext discoveryContext)
-			throws InvalidPluginConfigurationException, Exception {
-		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
-		ProfileServiceConnection connection = ((PlatformComponent) discoveryContext
-				.getParentResourceComponent()).getConnection();
-	
-		Set<ManagedComponent> translators = ProfileServiceUtil
-				.getManagedComponents(connection, new ComponentType(
-						PluginConstants.ComponentType.Translator.TYPE,
-						PluginConstants.ComponentType.Translator.SUBTYPE));
-
-		for (ManagedComponent translator : translators) {
-
-			String translatorKey = translator.getName();
-			String translatorName = ProfileServiceUtil.getSimpleValue(translator, "name", String.class); //$NON-NLS-1$
-			String description = ProfileServiceUtil.getSimpleValue(translator, "description", String.class); //$NON-NLS-1$
-			
-			/**
-			 * 
-			 * A discovered resource must have a unique key, that must stay the
-			 * same when the resource is discovered the next time
-			 */
-			DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
-					discoveryContext.getResourceType(), // ResourceType
-					translatorKey, // Resource Key
-					translatorName, // Resource Name
-					ApplicationInfo.getInstance().getReleaseNumber(), // Version
-					description, // Description
-					discoveryContext.getDefaultPluginConfiguration(), // Plugin config
-					null // Process info from a process scan
-			);
-
-			// Get plugin config map for models
-			Configuration configuration = detail.getPluginConfiguration();
-
-			configuration.put(new PropertySimple("name", translatorName));//$NON-NLS-1$
-			detail.setPluginConfiguration(configuration);
-			
-			 // Add to return values
-			// First get translator specific properties
-			ManagedProperty translatorProps = translator.getProperty("property");//$NON-NLS-1$
-			PropertyList list = new PropertyList("translatorList");//$NON-NLS-1$
-			PropertyMap propMap = null;
-			getTranslatorValues(translatorProps.getValue(), propMap, list);
-
-			// Now get common properties
-			configuration.put(new PropertySimple("name", translatorName));//$NON-NLS-1$
-			configuration.put(new PropertySimple("type",ProfileServiceUtil.getSimpleValue(translator,"type", String.class)));//$NON-NLS-1$ //$NON-NLS-2$
-
-			detail.setPluginConfiguration(configuration);
-			// Add to return values
-			discoveredResources.add(detail);
-			log.debug("Discovered Teiid Translator: " + translatorName);
-		}
-
-		return discoveredResources;
-	}
-
-
-	public static <T> void getTranslatorValues(MetaValue pValue,
-			PropertyMap map, PropertyList list) {
-		MetaType metaType = pValue.getMetaType();
-		Map<String, T> unwrappedvalue = null;
-		if (metaType.isComposite()) {
-			unwrappedvalue = (Map<String, T>) MetaValueFactory.getInstance().unwrap(pValue);
-
-			for (String key : unwrappedvalue.keySet()) {
-				map = new PropertyMap("properties");//$NON-NLS-1$
-				map.put(new PropertySimple("name", key));//$NON-NLS-1$
-				map.put(new PropertySimple("value", unwrappedvalue.get(key)));//$NON-NLS-1$
-				//map.put(new PropertySimple("description", "Custom property"));
-				list.add(map);
-			}
-		} else {
-			throw new IllegalStateException(pValue + " is not a Composite type");
-		}
-
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,135 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.core.util.ApplicationInfo;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * Discovery component for Teiid Translator instances
+ * 
+ */
+public class TranslatorDiscoveryComponent implements ResourceDiscoveryComponent {
+
+	private final Log log = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	public Set<DiscoveredResourceDetails> discoverResources(
+			ResourceDiscoveryContext discoveryContext)
+			throws InvalidPluginConfigurationException, Exception {
+		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
+		ProfileServiceConnection connection = ((PlatformComponent) discoveryContext
+				.getParentResourceComponent()).getConnection();
+	
+		Set<ManagedComponent> translators = ProfileServiceUtil
+				.getManagedComponents(connection, new ComponentType(
+						PluginConstants.ComponentType.Translator.TYPE,
+						PluginConstants.ComponentType.Translator.SUBTYPE));
+
+		for (ManagedComponent translator : translators) {
+
+			String translatorKey = translator.getName();
+			String translatorName = ProfileServiceUtil.getSimpleValue(translator, "name", String.class); //$NON-NLS-1$
+			String description = ProfileServiceUtil.getSimpleValue(translator, "description", String.class); //$NON-NLS-1$
+			
+			/**
+			 * 
+			 * A discovered resource must have a unique key, that must stay the
+			 * same when the resource is discovered the next time
+			 */
+			DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
+					discoveryContext.getResourceType(), // ResourceType
+					translatorKey, // Resource Key
+					translatorName, // Resource Name
+					ApplicationInfo.getInstance().getReleaseNumber(), // Version
+					description, // Description
+					discoveryContext.getDefaultPluginConfiguration(), // Plugin config
+					null // Process info from a process scan
+			);
+
+			// Get plugin config map for models
+			Configuration configuration = detail.getPluginConfiguration();
+
+			configuration.put(new PropertySimple("name", translatorName));//$NON-NLS-1$
+			detail.setPluginConfiguration(configuration);
+			
+			 // Add to return values
+			// First get translator specific properties
+			ManagedProperty translatorProps = translator.getProperty("property");//$NON-NLS-1$
+			PropertyList list = new PropertyList("translatorList");//$NON-NLS-1$
+			PropertyMap propMap = null;
+			getTranslatorValues(translatorProps.getValue(), propMap, list);
+
+			// Now get common properties
+			configuration.put(new PropertySimple("name", translatorName));//$NON-NLS-1$
+			configuration.put(new PropertySimple("type",ProfileServiceUtil.getSimpleValue(translator,"type", String.class)));//$NON-NLS-1$ //$NON-NLS-2$
+
+			detail.setPluginConfiguration(configuration);
+			// Add to return values
+			discoveredResources.add(detail);
+			log.debug("Discovered Teiid Translator: " + translatorName);
+		}
+
+		return discoveredResources;
+	}
+
+
+	public static <T> void getTranslatorValues(MetaValue pValue,
+			PropertyMap map, PropertyList list) throws Exception {
+		MetaType metaType = pValue.getMetaType();
+		MapCompositeValueSupport unwrappedvalue = null;
+		if (metaType.isComposite()) {
+			unwrappedvalue = (MapCompositeValueSupport)pValue;
+
+			for (String key : unwrappedvalue.getMetaType().keySet()) {
+				map = new PropertyMap("properties");//$NON-NLS-1$
+				map.put(new PropertySimple("name", key));//$NON-NLS-1$
+				map.put(new PropertySimple("value", ProfileServiceUtil.stringValue((MetaValue)unwrappedvalue.get(key))));//$NON-NLS-1$
+				list.add(map);
+			}
+		} else {
+			throw new IllegalStateException(pValue + " is not a Composite type");
+		}
+
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,679 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.naming.NamingException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.plugins.ManagedObjectImpl;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.CompositeValueSupport;
-import org.jboss.metatype.api.values.EnumValueSupport;
-import org.jboss.metatype.api.values.GenericValue;
-import org.jboss.metatype.api.values.GenericValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.mc4j.ems.connection.EmsConnection;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
-import org.rhq.core.domain.configuration.Property;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.PropertyMap;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementDataNumeric;
-import org.rhq.core.domain.measurement.MeasurementDataTrait;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
-import org.rhq.core.pluginapi.inventory.CreateResourceReport;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceComponent;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.adminapi.impl.PropertyMetadata;
-import org.teiid.rhq.admin.DQPManagementView;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-import org.teiid.rhq.plugin.util.PluginConstants.Operation;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
-import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
-
-/**
- * Component class for a Teiid VDB
- * 
- */
-public class VDBComponent extends Facet {
-	private final Log LOG = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @seeorg.teiid.rhq.plugin.Facet#start(org.rhq.core.pluginapi.inventory.
-	 * ResourceContext)
-	 */
-	@Override
-	public void start(ResourceContext context) {
-		this.setComponentName(context.getPluginConfiguration().getSimpleValue(
-				"fullName", null));
-		this.resourceConfiguration = context.getPluginConfiguration();
-		this.componentType = PluginConstants.ComponentType.VDB.NAME;
-		super.start(context);
-	}
-
-	@Override
-	protected void setOperationArguments(String name,
-			Configuration configuration, Map<String, Object> valueMap) {
-		// Parameter logic for VDB Metrics
-		String key = VDB.NAME;
-		valueMap.put(key, this.resourceConfiguration.getSimpleValue("name",
-				null));
-		String version = VDB.VERSION;
-		valueMap.put(version, this.resourceConfiguration.getSimpleValue(
-				"version", null));
-
-		// Parameter logic for VDB Operations
-		if (name.equals(VDB.Operations.KILL_REQUEST)) {
-			valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(
-					Operation.Value.REQUEST_ID).getLongValue());
-			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
-					Operation.Value.SESSION_ID).getLongValue());
-		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
-			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
-					Operation.Value.SESSION_ID).getLongValue());
-		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
-			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
-					Operation.Value.SESSION_ID).getLongValue());
-		} else if (name.equals(VDB.Operations.RELOAD_MATVIEW)) {
-			valueMap.put(Operation.Value.MATVIEW_SCHEMA, configuration.getSimple(
-					Operation.Value.MATVIEW_SCHEMA).getStringValue());
-			valueMap.put(Operation.Value.MATVIEW_TABLE, configuration.getSimple(
-					Operation.Value.MATVIEW_TABLE).getStringValue());
-			valueMap.put(Operation.Value.INVALIDATE_MATVIEW, configuration.getSimple(
-					Operation.Value.INVALIDATE_MATVIEW).getBooleanValue());
-		}
-	}
-
-	/*
-	 * (non-Javadoc)
-	 * 
-	 * @see org.teiid.rhq.plugin.Facet#getAvailability()
-	 */
-	@Override
-	public AvailabilityType getAvailability() {
-		// TODO Remove vdb version after no longer viable in Teiid
-		String version = this.resourceConfiguration.getSimpleValue("version",
-				null);
-		String status = DQPManagementView.getVDBStatus(getConnection(),
-				this.name);
-		if (status.equals("ACTIVE")) {
-			return AvailabilityType.UP;
-		}
-
-		return AvailabilityType.DOWN;
-	}
-
-	@Override
-	protected void setMetricArguments(String name, Configuration configuration,
-			Map<String, Object> valueMap) {
-		// Parameter logic for VDB Metrics
-		String key = VDB.NAME;
-		valueMap.put(key, this.name);
-	}
-
-	@Override
-	public void getValues(MeasurementReport report,
-			Set<MeasurementScheduleRequest> requests) throws Exception {
-
-		DQPManagementView view = new DQPManagementView();
-
-		Map<String, Object> valueMap = new HashMap<String, Object>();
-		setMetricArguments(VDB.NAME, null, valueMap);
-
-		for (MeasurementScheduleRequest request : requests) {
-			String name = request.getName();
-			LOG.debug("Measurement name = " + name); //$NON-NLS-1$
-
-			Object metricReturnObject = view.getMetric(getConnection(),
-					getComponentType(), this.getComponentIdentifier(), name,
-					valueMap);
-
-			try {
-				if (request.getName().equals(
-						PluginConstants.ComponentType.VDB.Metrics.ERROR_COUNT)) {
-					String message = "";
-					if (((Integer) metricReturnObject) > 0) {
-						message = "** There are "
-								+ ((Integer) metricReturnObject)
-								+ " errors reported for this VDB. See the Configuration tab for details. **";
-					} else {
-						message = "** There are no errors reported for this VDB. **";
-					}
-
-					report.addData(new MeasurementDataTrait(request, message));
-				} else {
-					if (request
-							.getName()
-							.equals(
-									PluginConstants.ComponentType.VDB.Metrics.QUERY_COUNT)) {
-						report.addData(new MeasurementDataTrait(request,
-								(String) metricReturnObject));
-					} else {
-						if (request
-								.getName()
-								.equals(
-										PluginConstants.ComponentType.VDB.Metrics.SESSION_COUNT)) {
-							report.addData(new MeasurementDataNumeric(request,
-									(Double) metricReturnObject));
-						} else {
-							if (request
-									.getName()
-									.equals(
-											PluginConstants.ComponentType.VDB.Metrics.STATUS)) {
-								if (((String) metricReturnObject)
-										.equals("ACTIVE")) {
-									report.addData(new MeasurementDataTrait(
-											request, "UP"));
-								} else {
-									report.addData(new MeasurementDataTrait(
-											request, "DOWN"));
-								}
-							} else {
-								if (request
-										.getName()
-										.equals(
-												PluginConstants.ComponentType.VDB.Metrics.LONG_RUNNING_QUERIES)) {
-									report.addData(new MeasurementDataNumeric(
-											request,
-											(Double) metricReturnObject));
-								}
-							}
-
-						}
-					}
-				}
-
-			} catch (Exception e) {
-				LOG.error("Failed to obtain measurement [" + name //$NON-NLS-1$
-						+ "]. Cause: " + e); //$NON-NLS-1$
-				// throw(e);
-			}
-		}
-
-	}
-
-	@Override
-	String getComponentType() {
-		return PluginConstants.ComponentType.VDB.NAME;
-	}
-
-	/**
-	 * The plugin container will call this method when it has a new
-	 * configuration for your managed resource. Your plugin will re-configure
-	 * the managed resource in your own custom way, setting its configuration
-	 * based on the new values of the given configuration.
-	 * 
-	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
-	 */
-	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
-
-		Configuration resourceConfig = report.getConfiguration();
-		resourceConfiguration = resourceConfig.deepCopy();
-
-		// First update simple properties
-		super.updateResourceConfiguration(report);
-
-		// Then update models
-		ManagementView managementView = null;
-		ComponentType componentType = new ComponentType(
-				PluginConstants.ComponentType.VDB.TYPE,
-				PluginConstants.ComponentType.VDB.SUBTYPE);
-
-		ManagedComponent managedComponent = null;
-		CollectionValueSupport modelsMetaValue = null;
-		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
-		try {
-
-			managementView = getConnection().getManagementView();
-			managedComponent = managementView.getComponent(this.name,
-					componentType);
-			ManagedProperty mp = managedComponent.getProperty("models");//$NON-NLS-1$
-			List<ManagedObject> modelsMp = (List<ManagedObject>) MetaValueFactory
-					.getInstance().unwrap(mp.getValue());
-			modelsMetaValue = (CollectionValueSupport) managedComponent
-					.getProperty("models").getValue();
-			GenericValue[] models = (GenericValue[]) modelsMetaValue
-					.getElements();
-			List<Property> multiSourceModelsPropertyList = resourceConfiguration
-					.getList("multiSourceModels").getList();
-			List<Property> singleSourceModelsPropertyList = resourceConfiguration
-					.getList("singleSourceModels").getList();
-			ArrayList<List<Property>> sourceMappingList = new ArrayList<List<Property>>();
-			sourceMappingList.add(singleSourceModelsPropertyList);
-			sourceMappingList.add(multiSourceModelsPropertyList);
-			PropertyMap model = null;
-			Iterator<List<Property>> sourceMappingListIterator = sourceMappingList
-					.iterator();
-			while (sourceMappingListIterator.hasNext()) {
-				List<Property> sourceList = sourceMappingListIterator.next();
-				for (int i = 0; i < sourceList.size(); i++) {
-					model = (PropertyMap) sourceList.get(i);
-					String sourceName = ((PropertySimple) model
-							.get("sourceName")).getStringValue(); //$NON-NLS-1$
-					if (sourceName.equals("See below"))
-						continue; // This is a multisource model which we will
-					// handle separately
-					String modelName = ((PropertySimple) model.get("name")) //$NON-NLS-1$
-							.getStringValue();
-					String dsName = ((PropertySimple) model.get("jndiName")) //$NON-NLS-1$
-							.getStringValue();
-
-					ManagedObject managedModel = null;
-					if (models != null && !modelsMp.isEmpty()) {
-						for (ManagedObject mo : modelsMp) {
-							String name = ProfileServiceUtil.getSimpleValue(mo,
-									"name", String.class); //$NON-NLS-1$
-							if (modelName.equals(name)) {
-								managedModel = mo;
-							}
-						}
-					}
-					ManagedProperty sourceMappings = managedModel
-							.getProperty("sourceMappings");//$NON-NLS-1$
-					if (sourceMappings != null) {
-						List<ManagedObject> mappings = (List<ManagedObject>) MetaValueFactory
-								.getInstance()
-								.unwrap(sourceMappings.getValue());
-						for (ManagedObject mo : mappings) {
-							String sName = ProfileServiceUtil.getSimpleValue(
-									mo, "name", String.class);//$NON-NLS-1$
-							if (sName.equals(sourceName)) {
-								// set the jndi name for the ds.
-								ManagedProperty jndiProperty = mo
-										.getProperty("connectionJndiName"); //$NON-NLS-1$
-								jndiProperty.setValue(ProfileServiceUtil.wrap(
-										SimpleMetaType.STRING, dsName));
-							}
-						}
-					}
-				}
-			}
-
-			try {
-				managementView.updateComponent(managedComponent);
-			} catch (Exception e) {
-				LOG.error("Unable to update component ["
-						+ managedComponent.getName() + "] of type "
-						+ componentType + ".", e);
-				report.setStatus(ConfigurationUpdateStatus.FAILURE);
-				report.setErrorMessageFromThrowable(e);
-			}
-		} catch (Exception e) {
-			LOG.error("Unable to process update request", e);
-			report.setStatus(ConfigurationUpdateStatus.FAILURE);
-			report.setErrorMessageFromThrowable(e);
-		}
-
-	}
-
-	@Override
-	public Configuration loadResourceConfiguration() {
-
-		ManagedComponent mcVdb = null;
-		try {
-			mcVdb = ProfileServiceUtil.getManagedComponent(getConnection(),
-					new org.jboss.managed.api.ComponentType(
-							PluginConstants.ComponentType.VDB.TYPE,
-							PluginConstants.ComponentType.VDB.SUBTYPE),
-					this.name);
-		} catch (NamingException e) {
-			final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		} catch (Exception e) {
-			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
-			LOG.error(msg, e);
-		}
-
-		String vdbName = ProfileServiceUtil.getSimpleValue(mcVdb, "name",
-				String.class);
-		Integer vdbVersion = ProfileServiceUtil.getSimpleValue(mcVdb,
-				"version", Integer.class);
-		String vdbDescription = ProfileServiceUtil.getSimpleValue(mcVdb,
-				"description", String.class);
-		String vdbStatus = ProfileServiceUtil.getSimpleValue(mcVdb, "status",
-				String.class);
-		String connectionType = ProfileServiceUtil.getSimpleValue(mcVdb,
-				"connectionType", String.class);
-		String vdbURL = ProfileServiceUtil.getSimpleValue(mcVdb, "url",
-				String.class);
-
-		// Get plugin config map for models
-		Configuration configuration = resourceContext.getPluginConfiguration();
-
-		configuration.put(new PropertySimple("name", vdbName));
-		configuration.put(new PropertySimple("version", vdbVersion));
-		configuration.put(new PropertySimple("description", vdbDescription));
-		configuration.put(new PropertySimple("status", vdbStatus));
-		configuration.put(new PropertySimple("url", vdbURL));
-		configuration.put(new PropertySimple("connectionType", connectionType));
-
-		getTranslators(mcVdb, configuration);
-
-		getModels(mcVdb, configuration);
-
-		return configuration;
-
-	}
-
-	@Override
-	public CreateResourceReport createResource(
-			CreateResourceReport createResourceReport) {
-
-		createContentBasedResource(createResourceReport);
-		return createResourceReport;
-	}
-
-	/**
-	 * @param mcVdb
-	 * @param configuration
-	 * @throws Exception
-	 */
-	private void getModels(ManagedComponent mcVdb, Configuration configuration) {
-		// Get models from VDB
-		ManagedProperty property = mcVdb.getProperty("models");
-		List<ManagedObject> models = (List<ManagedObject>) MetaValueFactory
-				.getInstance().unwrap(property.getValue());
-		CollectionValueSupport valueSupport = (CollectionValueSupport) property
-				.getValue();
-		MetaValue[] metaValues = valueSupport.getElements();
-
-		PropertyList sourceModelsList = new PropertyList("singleSourceModels");
-		configuration.put(sourceModelsList);
-
-		PropertyList multiSourceModelsList = new PropertyList(
-				"multiSourceModels");
-		configuration.put(multiSourceModelsList);
-
-		PropertyList logicalModelsList = new PropertyList("logicalModels");
-		configuration.put(logicalModelsList);
-
-		PropertyList errorList = new PropertyList("errorList");
-		configuration.put(errorList);
-
-		for (MetaValue value : metaValues) {
-			GenericValueSupport genValueSupport = (GenericValueSupport) value;
-			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
-					.getValue();
-
-			Boolean isSource = Boolean.TRUE;
-			try {
-				isSource = ProfileServiceUtil.booleanValue(managedObject
-						.getProperty("source").getValue());
-			} catch (Exception e) {
-				LOG.error(e.getMessage());
-			}
-
-			Boolean supportMultiSource = Boolean.TRUE;
-			try {
-				supportMultiSource = ProfileServiceUtil
-						.booleanValue(managedObject.getProperty(
-								"supportsMultiSourceBindings").getValue());
-			} catch (Exception e) {
-				LOG.error(e.getMessage());
-			}
-
-			String modelName = managedObject.getName();
-			ManagedProperty connectorBinding = managedObject
-					.getProperty("sourceMappings");
-			Collection<Map<String, String>> sourceList = new ArrayList<Map<String, String>>();
-
-			getSourceMappingValue(connectorBinding.getValue(), sourceList);
-
-			String visibility = ((SimpleValueSupport) managedObject
-					.getProperty("visible").getValue()).getValue().toString();
-			String type = ((EnumValueSupport) managedObject.getProperty(
-					"modelType").getValue()).getValue().toString();
-
-			// Get any model errors/warnings
-			MetaValue errors = managedObject.getProperty("errors").getValue();
-			if (errors != null) {
-				CollectionValueSupport errorValueSupport = (CollectionValueSupport) errors;
-				MetaValue[] errorArray = errorValueSupport.getElements();
-
-				for (MetaValue error : errorArray) {
-					GenericValueSupport errorGenValueSupport = (GenericValueSupport) error;
-
-					ManagedObject errorMo = (ManagedObject) errorGenValueSupport
-							.getValue();
-					String severity = ((SimpleValue) errorMo.getProperty(
-							"severity").getValue()).getValue().toString();
-					String message = ((SimpleValue) errorMo
-							.getProperty("value").getValue()).getValue()
-							.toString();
-
-					PropertyMap errorMap = new PropertyMap("errorMap",
-							new PropertySimple("severity", severity),
-							new PropertySimple("message", message));
-					errorList.add(errorMap);
-				}
-			}
-
-			for (Map<String, String> sourceMap : sourceList) {
-
-				if (isSource) {
-					String sourceName = (String) sourceMap.get("name");
-					String jndiName = (String) sourceMap.get("jndiName");
-					String translatorName = (String) sourceMap
-							.get("translatorName");
-					PropertyMap multiSourceModel = null;
-
-					PropertyMap model = null;
-					if (supportMultiSource) {
-						// TODO need to loop through multisource models
-						multiSourceModel = new PropertyMap("map",
-								new PropertySimple("name", modelName),
-								new PropertySimple("sourceName", sourceName),
-								new PropertySimple("jndiName", jndiName),
-								new PropertySimple("translatorName",
-										translatorName));
-
-						multiSourceModelsList.add(multiSourceModel);
-
-						model = new PropertyMap("map", new PropertySimple(
-								"name", modelName), new PropertySimple(
-								"sourceName", "See below"), new PropertySimple(
-								"jndiName", "See below"), new PropertySimple(
-								"translatorName", "See below"),
-								new PropertySimple("visibility", visibility),
-								new PropertySimple("supportsMultiSource", true));
-						sourceModelsList.add(model);
-					} else {
-						model = new PropertyMap("map", new PropertySimple(
-								"name", modelName), new PropertySimple(
-								"sourceName", sourceName), new PropertySimple(
-								"jndiName", jndiName), new PropertySimple(
-								"translatorName", translatorName),
-								new PropertySimple("visibility", visibility),
-								new PropertySimple("supportsMultiSource",
-										supportMultiSource));
-						sourceModelsList.add(model);
-					}
-				} else {
-					PropertyMap model = new PropertyMap("map",
-							new PropertySimple("name", modelName),
-							new PropertySimple("type", type),
-							new PropertySimple("visibility", visibility));
-
-					logicalModelsList.add(model);
-				}
-			}
-		}
-	}
-
-	/**
-	 * @param <T>
-	 * @param pValue
-	 * @param list
-	 */
-	public static <T> void getSourceMappingValue(MetaValue pValue,
-			Collection<Map<String, String>> list) {
-		Map<String, String> map = new HashMap<String, String>();
-		list.add(map);
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				GenericValueSupport genValue = ((GenericValueSupport) value);
-				ManagedObject mo = (ManagedObject) genValue.getValue();
-				String sourceName = mo.getName();
-				String jndi = ((SimpleValue) mo.getProperty(
-						"connectionJndiName").getValue()).getValue().toString();
-				String translatorName = ((SimpleValue) mo.getProperty(
-						"translatorName").getValue()).getValue().toString();
-				map.put("name", sourceName);
-				map.put("jndiName", jndi);
-				map.put("translatorName", translatorName);
-			}
-		} else {
-			throw new IllegalStateException(pValue
-					+ " is not a Collection type");
-		}
-	}
-
-	/**
-	 * @param mcVdb
-	 * @param configuration
-	 * @throws Exception
-	 */
-	private void getTranslators(ManagedComponent mcVdb,
-			Configuration configuration) {
-		// Get models from VDB
-		ManagedProperty property = mcVdb.getProperty("overrideTranslators");
-		if (property == null) {
-			return;
-		}
-		List<ManagedObject> translators = (List<ManagedObject>) MetaValueFactory
-				.getInstance().unwrap(property.getValue());
-		CollectionValueSupport valueSupport = (CollectionValueSupport) property
-				.getValue();
-		MetaValue[] metaValues = valueSupport.getElements();
-
-		PropertyList translatorsList = new PropertyList("translators");
-		configuration.put(translatorsList);
-
-		for (MetaValue value : metaValues) {
-			GenericValueSupport genValueSupport = (GenericValueSupport) value;
-			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
-					.getValue();
-
-			String translatorName = ProfileServiceUtil.getSimpleValue(
-					managedObject, "name", String.class);
-			String translatorType = ProfileServiceUtil.getSimpleValue(
-					managedObject, "type", String.class);
-			ManagedProperty properties = managedObject.getProperty("property");
-
-			if (properties != null) {
-				List<PropertyMetadata> props = (List<PropertyMetadata>) MetaValueFactory
-						.getInstance().unwrap(properties.getValue());
-				for (PropertyMetadata propertyMetaData : props) {
-					String propertyName = propertyMetaData.getName();
-					String propertyValue = propertyMetaData.getValue();
-					PropertyMap translatorMap = null;
-
-					translatorMap = new PropertyMap("translatorMap",
-							new PropertySimple("name", translatorName),
-							new PropertySimple("type", translatorType),
-							new PropertySimple("propertyName", propertyName),
-							new PropertySimple("propertyValue", propertyValue));
-					// Only want translator name and value to show up for the
-					// first row,
-					// so we will blank them out here.
-					translatorName = "";
-					translatorType = "";
-					translatorsList.add(translatorMap);
-				}
-			}
-		}
-	}
-
-	/**
-	 * @param <T>
-	 * @param pValue
-	 * @param list
-	 */
-	public static <T> void getPropertyValues(MetaValue pValue,
-			Collection<Map<String, String>> list) {
-		Map<String, String> map = new HashMap<String, String>();
-		list.add(map);
-		MetaType metaType = pValue.getMetaType();
-		if (metaType.isCollection()) {
-			for (MetaValue value : ((CollectionValueSupport) pValue)
-					.getElements()) {
-				CompositeValueSupport compValue = ((CompositeValueSupport) value);
-				for (MetaValue propValue : compValue.values()) {
-					String propertyName = ((CompositeValueSupport) propValue)
-							.get("name").toString();
-					String propertyValue = ((CompositeValueSupport) propValue)
-							.get("value").toString();
-					map.put("name", propertyName);
-					map.put("value", propertyValue);
-				}
-			}
-		} else {
-			throw new IllegalStateException(pValue
-					+ " is not a Collection type");
-		}
-	}
-
-	@Override
-	public ProfileServiceConnection getConnection() {
-		return ((PlatformComponent) this.resourceContext
-				.getParentResourceComponent()).getConnection();
-	}
-
-	@Override
-	public EmsConnection getEmsConnection() {
-		// TODO Auto-generated method stub
-		return null;
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,700 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.naming.NamingException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedObject;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.EnumValueSupport;
+import org.jboss.metatype.api.values.GenericValue;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.mc4j.ems.connection.EmsConnection;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.measurement.AvailabilityType;
+import org.rhq.core.domain.measurement.MeasurementDataNumeric;
+import org.rhq.core.domain.measurement.MeasurementDataTrait;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
+import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
+import org.rhq.core.pluginapi.inventory.ResourceContext;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.admin.DQPManagementView;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+import org.teiid.rhq.plugin.util.PluginConstants.Operation;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.Platform;
+import org.teiid.rhq.plugin.util.PluginConstants.ComponentType.VDB;
+
+/**
+ * Component class for a Teiid VDB
+ * 
+ */
+public class VDBComponent extends Facet {
+	private final Log LOG = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @seeorg.teiid.rhq.plugin.Facet#start(org.rhq.core.pluginapi.inventory.
+	 * ResourceContext)
+	 */
+	@Override
+	public void start(ResourceContext context) {
+		this.setComponentName(context.getPluginConfiguration().getSimpleValue(
+				"fullName", null));
+		this.resourceConfiguration = context.getPluginConfiguration();
+		this.componentType = PluginConstants.ComponentType.VDB.NAME;
+		super.start(context);
+	}
+
+	@Override
+	protected void setOperationArguments(String name,
+			Configuration configuration, Map<String, Object> valueMap) {
+		// Parameter logic for VDB Metrics
+		String key = VDB.NAME;
+		valueMap.put(key, this.resourceConfiguration.getSimpleValue("name",
+				null));
+		String version = VDB.VERSION;
+		valueMap.put(version, this.resourceConfiguration.getSimpleValue(
+				VDB.VERSION, null));
+
+		// Parameter logic for VDB Operations
+		if (name.equals(VDB.Operations.KILL_REQUEST)) {
+			valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(
+					Operation.Value.REQUEST_ID).getLongValue());
+			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+					Operation.Value.SESSION_ID).getLongValue());
+		} else if (name.equals(VDB.Operations.CLEAR_CACHE)) {
+				valueMap.put(Operation.Value.CACHE_TYPE, configuration.getSimple(
+					Operation.Value.CACHE_TYPE).getStringValue());
+		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
+			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+					Operation.Value.SESSION_ID).getLongValue());
+		} else if (name.equals(Platform.Operations.KILL_SESSION)) {
+			valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(
+					Operation.Value.SESSION_ID).getLongValue());
+		} else if (name.equals(VDB.Operations.RELOAD_MATVIEW)) {
+			valueMap
+					.put(Operation.Value.MATVIEW_SCHEMA, configuration
+							.getSimple(Operation.Value.MATVIEW_SCHEMA)
+							.getStringValue());
+			valueMap.put(Operation.Value.MATVIEW_TABLE, configuration
+					.getSimple(Operation.Value.MATVIEW_TABLE).getStringValue());
+			valueMap.put(Operation.Value.INVALIDATE_MATVIEW, configuration
+					.getSimple(Operation.Value.INVALIDATE_MATVIEW)
+					.getBooleanValue());
+		}
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see org.teiid.rhq.plugin.Facet#getAvailability()
+	 */
+	@Override
+	public AvailabilityType getAvailability() {
+		// TODO Remove vdb version after no longer viable in Teiid
+		String version = this.resourceConfiguration.getSimpleValue("version",
+				null);
+		String status = DQPManagementView.getVDBStatus(getConnection(),
+				this.name);
+		if (status.equals("ACTIVE")) {
+			return AvailabilityType.UP;
+		}
+
+		return AvailabilityType.DOWN;
+	}
+
+	@Override
+	protected void setMetricArguments(String name, Configuration configuration,
+			Map<String, Object> valueMap) {
+		// Parameter logic for VDB Metrics
+		String key = VDB.NAME;
+		valueMap.put(key, this.name);
+	}
+
+	@Override
+	public void getValues(MeasurementReport report,
+			Set<MeasurementScheduleRequest> requests) throws Exception {
+
+		DQPManagementView view = new DQPManagementView();
+
+		Map<String, Object> valueMap = new HashMap<String, Object>();
+		setMetricArguments(VDB.NAME, null, valueMap);
+
+		for (MeasurementScheduleRequest request : requests) {
+			String name = request.getName();
+			LOG.debug("Measurement name = " + name); //$NON-NLS-1$
+
+			Object metricReturnObject = view.getMetric(getConnection(),
+					getComponentType(), this.getComponentIdentifier(), name,
+					valueMap);
+
+			try {
+				if (request.getName().equals(
+						PluginConstants.ComponentType.VDB.Metrics.ERROR_COUNT)) {
+					String message = "";
+					if (((Integer) metricReturnObject) > 0) {
+						message = "** There are "
+								+ ((Integer) metricReturnObject)
+								+ " errors reported for this VDB. See the Configuration tab for details. **";
+					} else {
+						message = "** There are no errors reported for this VDB. **";
+					}
+
+					report.addData(new MeasurementDataTrait(request, message));
+				} else {
+					if (request
+							.getName()
+							.equals(
+									PluginConstants.ComponentType.VDB.Metrics.QUERY_COUNT)) {
+						report.addData(new MeasurementDataTrait(request,
+								(String) metricReturnObject));
+					} else {
+						if (request
+								.getName()
+								.equals(
+										PluginConstants.ComponentType.VDB.Metrics.SESSION_COUNT)) {
+							report.addData(new MeasurementDataNumeric(request,
+									(Double) metricReturnObject));
+						} else {
+							if (request
+									.getName()
+									.equals(
+											PluginConstants.ComponentType.VDB.Metrics.STATUS)) {
+								if (((String) metricReturnObject)
+										.equals("ACTIVE")) {
+									report.addData(new MeasurementDataTrait(
+											request, "UP"));
+								} else {
+									report.addData(new MeasurementDataTrait(
+											request, "DOWN"));
+								}
+							} else {
+								if (request
+										.getName()
+										.equals(
+												PluginConstants.ComponentType.VDB.Metrics.LONG_RUNNING_QUERIES)) {
+									report.addData(new MeasurementDataNumeric(
+											request,
+											(Double) metricReturnObject));
+								}
+							}
+
+						}
+					}
+				}
+
+			} catch (Exception e) {
+				LOG.error("Failed to obtain measurement [" + name //$NON-NLS-1$
+						+ "]. Cause: " + e); //$NON-NLS-1$
+				// throw(e);
+			}
+		}
+
+	}
+
+	@Override
+	String getComponentType() {
+		return PluginConstants.ComponentType.VDB.NAME;
+	}
+
+	/**
+	 * The plugin container will call this method when it has a new
+	 * configuration for your managed resource. Your plugin will re-configure
+	 * the managed resource in your own custom way, setting its configuration
+	 * based on the new values of the given configuration.
+	 * 
+	 * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
+	 */
+	public void updateResourceConfiguration(ConfigurationUpdateReport report) {
+
+		Configuration resourceConfig = report.getConfiguration();
+		resourceConfiguration = resourceConfig.deepCopy();
+
+		// First update simple properties
+		super.updateResourceConfiguration(report);
+
+		// Then update models
+		ManagementView managementView = null;
+		ComponentType componentType = new ComponentType(
+				PluginConstants.ComponentType.VDB.TYPE,
+				PluginConstants.ComponentType.VDB.SUBTYPE);
+
+		ManagedComponent managedComponent = null;
+		CollectionValueSupport modelsMetaValue = null;
+		report.setStatus(ConfigurationUpdateStatus.SUCCESS);
+		try {
+
+			managementView = getConnection().getManagementView();
+			managedComponent = managementView.getComponent(this.name,
+					componentType);
+			modelsMetaValue = (CollectionValueSupport) managedComponent
+					.getProperty("models").getValue();
+			GenericValue[] models = (GenericValue[]) modelsMetaValue
+					.getElements();
+			List<Property> multiSourceModelsPropertyList = resourceConfiguration
+					.getList("multiSourceModels").getList();
+			List<Property> singleSourceModelsPropertyList = resourceConfiguration
+					.getList("singleSourceModels").getList();
+			ArrayList<List<Property>> sourceMappingList = new ArrayList<List<Property>>();
+			sourceMappingList.add(singleSourceModelsPropertyList);
+			sourceMappingList.add(multiSourceModelsPropertyList);
+			PropertyMap model = null;
+			Iterator<List<Property>> sourceMappingListIterator = sourceMappingList
+					.iterator();
+			while (sourceMappingListIterator.hasNext()) {
+				List<Property> sourceList = sourceMappingListIterator.next();
+				for (int i = 0; i < sourceList.size(); i++) {
+					model = (PropertyMap) sourceList.get(i);
+					String sourceName = ((PropertySimple) model
+							.get("sourceName")).getStringValue(); //$NON-NLS-1$
+					if (sourceName.equals("See below"))
+						continue; // This is a multisource model which we will
+									// handle separately
+					String modelName = ((PropertySimple) model.get("name")) //$NON-NLS-1$
+							.getStringValue();
+					String dsName = ((PropertySimple) model.get("jndiName")) //$NON-NLS-1$
+							.getStringValue();
+
+					ManagedObject managedModel = null;
+					if (models != null && models.length != 0) {
+						for (GenericValue genValue : models) {
+							ManagedObject mo = (ManagedObject) ((GenericValueSupport) genValue)
+									.getValue();
+							String name = ProfileServiceUtil.getSimpleValue(mo,
+									"name", String.class); //$NON-NLS-1$
+							if (modelName.equals(name)) {
+								managedModel = mo;
+								break;
+							}
+						}
+					}
+
+					ManagedProperty sourceMappings = null;
+					if (managedModel != null) {
+
+						sourceMappings = managedModel
+								.getProperty("sourceMappings");//$NON-NLS-1$
+
+						if (sourceMappings != null) {
+							CollectionValueSupport mappings = (CollectionValueSupport) sourceMappings
+									.getValue();
+							GenericValue[] mappingsArray = (GenericValue[]) mappings
+									.getElements();
+							for (GenericValue sourceGenValue : mappingsArray) {
+								ManagedObject sourceMo = (ManagedObject) ((GenericValueSupport) sourceGenValue)
+										.getValue();
+								String sName = ProfileServiceUtil
+										.getSimpleValue(sourceMo,
+												"name", String.class);//$NON-NLS-1$
+								if (sName.equals(sourceName)) {
+									// set the jndi name for the ds.
+									ManagedProperty jndiProperty = sourceMo
+											.getProperty("connectionJndiName"); //$NON-NLS-1$
+									jndiProperty
+											.setValue(ProfileServiceUtil.wrap(
+													SimpleMetaType.STRING,
+													dsName));
+									break;
+								}
+							}
+						}
+					}
+				}
+			}
+
+			try {
+				managementView.updateComponent(managedComponent);
+				managementView.load();
+			} catch (Exception e) {
+				LOG.error("Unable to update component ["
+						+ managedComponent.getName() + "] of type "
+						+ componentType + ".", e);
+				report.setStatus(ConfigurationUpdateStatus.FAILURE);
+				report.setErrorMessageFromThrowable(e);
+			}
+		} catch (Exception e) {
+			LOG.error("Unable to process update request", e);
+			report.setStatus(ConfigurationUpdateStatus.FAILURE);
+			report.setErrorMessageFromThrowable(e);
+		}
+
+	}
+
+	@Override
+	public Configuration loadResourceConfiguration() {
+
+		ManagedComponent mcVdb = null;
+		try {
+			mcVdb = ProfileServiceUtil.getManagedComponent(getConnection(),
+					new org.jboss.managed.api.ComponentType(
+							PluginConstants.ComponentType.VDB.TYPE,
+							PluginConstants.ComponentType.VDB.SUBTYPE),
+					this.name);
+		} catch (NamingException e) {
+			final String msg = "NamingException in loadResourceConfiguration(): " + e.getExplanation(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		} catch (Exception e) {
+			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		String vdbName = ProfileServiceUtil.getSimpleValue(mcVdb, "name",
+				String.class);
+		Integer vdbVersion = ProfileServiceUtil.getSimpleValue(mcVdb,
+				"version", Integer.class);
+		String vdbDescription = ProfileServiceUtil.getSimpleValue(mcVdb,
+				"description", String.class);
+		String vdbStatus = ProfileServiceUtil.getSimpleValue(mcVdb, "status",
+				String.class);
+		String connectionType = ProfileServiceUtil.getSimpleValue(mcVdb,
+				"connectionType", String.class);
+		String vdbURL = ProfileServiceUtil.getSimpleValue(mcVdb, "url",
+				String.class);
+
+		// Get plugin config map for models
+		Configuration configuration = resourceContext.getPluginConfiguration();
+
+		configuration.put(new PropertySimple("name", vdbName));
+		configuration.put(new PropertySimple("version", vdbVersion));
+		configuration.put(new PropertySimple("description", vdbDescription));
+		configuration.put(new PropertySimple("status", vdbStatus));
+		configuration.put(new PropertySimple("url", vdbURL));
+		configuration.put(new PropertySimple("connectionType", connectionType));
+
+		try {
+			getTranslators(mcVdb, configuration);
+		} catch (Exception e) {
+			final String msg = "Exception in loadResourceConfiguration(): " + e.getMessage(); //$NON-NLS-1$
+			LOG.error(msg, e);
+		}
+
+		getModels(mcVdb, configuration);
+
+		return configuration;
+
+	}
+
+	@Override
+	public CreateResourceReport createResource(
+			CreateResourceReport createResourceReport) {
+
+		createContentBasedResource(createResourceReport);
+		return createResourceReport;
+	}
+
+	/**
+	 * @param mcVdb
+	 * @param configuration
+	 * @throws Exception
+	 */
+	private void getModels(ManagedComponent mcVdb, Configuration configuration) {
+		// Get models from VDB
+		ManagedProperty property = mcVdb.getProperty("models");
+		CollectionValueSupport valueSupport = (CollectionValueSupport) property
+				.getValue();
+		MetaValue[] metaValues = valueSupport.getElements();
+
+		PropertyList sourceModelsList = new PropertyList("singleSourceModels");
+		configuration.put(sourceModelsList);
+
+		PropertyList multiSourceModelsList = new PropertyList(
+				"multiSourceModels");
+		configuration.put(multiSourceModelsList);
+
+		PropertyList logicalModelsList = new PropertyList("logicalModels");
+		configuration.put(logicalModelsList);
+
+		PropertyList errorList = new PropertyList("errorList");
+		configuration.put(errorList);
+
+		for (MetaValue value : metaValues) {
+			GenericValueSupport genValueSupport = (GenericValueSupport) value;
+			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+					.getValue();
+
+			Boolean isSource = Boolean.TRUE;
+			try {
+				isSource = ProfileServiceUtil.booleanValue(managedObject
+						.getProperty("source").getValue());
+			} catch (Exception e) {
+				LOG.error(e.getMessage());
+			}
+
+			Boolean supportMultiSource = Boolean.TRUE;
+			try {
+				supportMultiSource = ProfileServiceUtil
+						.booleanValue(managedObject.getProperty(
+								"supportsMultiSourceBindings").getValue());
+			} catch (Exception e) {
+				LOG.error(e.getMessage());
+			}
+
+			String modelName = managedObject.getName();
+			ManagedProperty connectorBinding = managedObject
+					.getProperty("sourceMappings");
+			Collection<Map<String, String>> sourceList = new ArrayList<Map<String, String>>();
+
+			getSourceMappingValue(connectorBinding.getValue(), sourceList);
+
+			String visibility = ((SimpleValueSupport) managedObject
+					.getProperty("visible").getValue()).getValue().toString();
+			String type = ((EnumValueSupport) managedObject.getProperty(
+					"modelType").getValue()).getValue().toString();
+
+			// Get any model errors/warnings
+			MetaValue errors = managedObject.getProperty("errors").getValue();
+			if (errors != null) {
+				CollectionValueSupport errorValueSupport = (CollectionValueSupport) errors;
+				MetaValue[] errorArray = errorValueSupport.getElements();
+
+				for (MetaValue error : errorArray) {
+					GenericValueSupport errorGenValueSupport = (GenericValueSupport) error;
+
+					ManagedObject errorMo = (ManagedObject) errorGenValueSupport
+							.getValue();
+					String severity = ((SimpleValue) errorMo.getProperty(
+							"severity").getValue()).getValue().toString();
+					String message = ((SimpleValue) errorMo
+							.getProperty("value").getValue()).getValue()
+							.toString();
+
+					PropertyMap errorMap = new PropertyMap("errorMap",
+							new PropertySimple("severity", severity),
+							new PropertySimple("message", message));
+					errorList.add(errorMap);
+				}
+			}
+
+			for (Map<String, String> sourceMap : sourceList) {
+
+				if (isSource) {
+					String sourceName = (String) sourceMap.get("name");
+					String jndiName = (String) sourceMap.get("jndiName");
+					String translatorName = (String) sourceMap
+							.get("translatorName");
+					PropertyMap multiSourceModel = null;
+
+					PropertyMap model = null;
+					if (supportMultiSource) {
+						// TODO need to loop through multisource models
+						multiSourceModel = new PropertyMap("map",
+								new PropertySimple("name", modelName),
+								new PropertySimple("sourceName", sourceName),
+								new PropertySimple("jndiName", jndiName),
+								new PropertySimple("translatorName",
+										translatorName));
+
+						multiSourceModelsList.add(multiSourceModel);
+
+						model = new PropertyMap("map", new PropertySimple(
+								"name", modelName), new PropertySimple(
+								"sourceName", "See below"), new PropertySimple(
+								"jndiName", "See below"), new PropertySimple(
+								"translatorName", "See below"),
+								new PropertySimple("visibility", visibility),
+								new PropertySimple("supportsMultiSource", true));
+						sourceModelsList.add(model);
+					} else {
+						model = new PropertyMap("map", new PropertySimple(
+								"name", modelName), new PropertySimple(
+								"sourceName", sourceName), new PropertySimple(
+								"jndiName", jndiName), new PropertySimple(
+								"translatorName", translatorName),
+								new PropertySimple("visibility", visibility),
+								new PropertySimple("supportsMultiSource",
+										supportMultiSource));
+						sourceModelsList.add(model);
+					}
+				} else {
+					PropertyMap model = new PropertyMap("map",
+							new PropertySimple("name", modelName),
+							new PropertySimple("type", type),
+							new PropertySimple("visibility", visibility));
+
+					logicalModelsList.add(model);
+				}
+			}
+		}
+	}
+
+	/**
+	 * @param <T>
+	 * @param pValue
+	 * @param list
+	 */
+	public static <T> void getSourceMappingValue(MetaValue pValue,
+			Collection<Map<String, String>> list) {
+		Map<String, String> map = new HashMap<String, String>();
+		list.add(map);
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue)
+					.getElements()) {
+				GenericValueSupport genValue = ((GenericValueSupport) value);
+				ManagedObject mo = (ManagedObject) genValue.getValue();
+				String sourceName = mo.getName();
+				String jndi = ((SimpleValue) mo.getProperty(
+						"connectionJndiName").getValue()).getValue().toString();
+				String translatorName = ((SimpleValue) mo.getProperty(
+						"translatorName").getValue()).getValue().toString();
+				map.put("name", sourceName);
+				map.put("jndiName", jndi);
+				map.put("translatorName", translatorName);
+			}
+		} else {
+			throw new IllegalStateException(pValue
+					+ " is not a Collection type");
+		}
+	}
+
+	/**
+	 * @param mcVdb
+	 * @param configuration
+	 * @throws Exception 
+	 */
+	private void getTranslators(ManagedComponent mcVdb,
+			Configuration configuration) throws Exception {
+		// Get models from VDB
+		ManagedProperty property = mcVdb.getProperty("overrideTranslators");
+		if (property == null) {
+			return;
+		}
+		CollectionValueSupport valueSupport = (CollectionValueSupport) property
+				.getValue();
+		MetaValue[] metaValues = valueSupport.getElements();
+
+		PropertyList translatorsList = new PropertyList("translators");
+		configuration.put(translatorsList);
+
+		for (MetaValue value : metaValues) {
+			GenericValueSupport genValueSupport = (GenericValueSupport) value;
+			ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+					.getValue();
+
+			String translatorName = ProfileServiceUtil.getSimpleValue(
+					managedObject, "name", String.class);
+			String translatorType = ProfileServiceUtil.getSimpleValue(
+					managedObject, "type", String.class);
+			ManagedProperty properties = managedObject.getProperty("property");
+
+			if (properties != null) {
+				CollectionValueSupport props = (CollectionValueSupport) properties
+						.getValue();
+				for (MetaValue propertyMetaData : props) {
+					String propertyName = ProfileServiceUtil
+							.stringValue(((CompositeValueSupport) propertyMetaData)
+									.get("name"));
+					String propertyValue = ProfileServiceUtil
+							.stringValue(((CompositeValueSupport) propertyMetaData)
+									.get("value"));
+					PropertyMap translatorMap = null;
+
+					translatorMap = new PropertyMap("translatorMap",
+							new PropertySimple("name", translatorName),
+							new PropertySimple("type", translatorType),
+							new PropertySimple("propertyName", propertyName),
+							new PropertySimple("propertyValue", propertyValue));
+					// Only want translator name and value to show up for the
+					// first row,
+					// so we will blank them out here.
+					translatorName = "";
+					translatorType = "";
+					translatorsList.add(translatorMap);
+				}
+			}
+		}
+	}
+
+	/**
+	 * @param <T>
+	 * @param pValue
+	 * @param list
+	 */
+	public static <T> void getPropertyValues(MetaValue pValue,
+			Collection<Map<String, String>> list) {
+		Map<String, String> map = new HashMap<String, String>();
+		list.add(map);
+		MetaType metaType = pValue.getMetaType();
+		if (metaType.isCollection()) {
+			for (MetaValue value : ((CollectionValueSupport) pValue)
+					.getElements()) {
+				CompositeValueSupport compValue = ((CompositeValueSupport) value);
+				for (MetaValue propValue : compValue.values()) {
+					String propertyName = ((CompositeValueSupport) propValue)
+							.get("name").toString();
+					String propertyValue = ((CompositeValueSupport) propValue)
+							.get("value").toString();
+					map.put("name", propertyName);
+					map.put("value", propertyValue);
+				}
+			}
+		} else {
+			throw new IllegalStateException(pValue
+					+ " is not a Collection type");
+		}
+	}
+
+	@Override
+	public ProfileServiceConnection getConnection() {
+		return ((PlatformComponent) this.resourceContext
+				.getParentResourceComponent()).getConnection();
+	}
+
+	@Override
+	public EmsConnection getEmsConnection() {
+		// TODO Auto-generated method stub
+		return null;
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,114 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.ManagedComponent;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
-import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
-import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
-import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
-import org.teiid.rhq.plugin.util.PluginConstants;
-import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
-/**
- * Discovery component for VDBs
- * 
- */
-public class VDBDiscoveryComponent implements ResourceDiscoveryComponent {
-
-	private final Log log = LogFactory
-			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-	public Set<DiscoveredResourceDetails> discoverResources(
-			ResourceDiscoveryContext discoveryContext)
-			throws InvalidPluginConfigurationException, Exception {
-		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
-		ProfileServiceConnection connection = ((PlatformComponent) discoveryContext
-				.getParentResourceComponent()).getConnection();
-
-		Set<ManagedComponent> vdbs = ProfileServiceUtil
-				.getManagedComponents(connection, new ComponentType(
-						PluginConstants.ComponentType.VDB.TYPE,
-						PluginConstants.ComponentType.VDB.SUBTYPE));
-
-		for (ManagedComponent mcVdb : vdbs) {
-
-			String vdbKey = (String)mcVdb.getName();
-			String vdbName = vdbKey;
-			String fullName = ProfileServiceUtil.getSimpleValue(mcVdb, "fullName",
-					String.class);
-			Integer vdbVersion = ProfileServiceUtil.getSimpleValue(mcVdb,
-					"version", Integer.class);
-			String vdbDescription = ProfileServiceUtil.getSimpleValue(mcVdb,
-					"description", String.class);
-			String vdbStatus = ProfileServiceUtil.getSimpleValue(mcVdb,
-					"status", String.class);
-			String vdbURL = ProfileServiceUtil.getSimpleValue(mcVdb, "url",
-					String.class);
-
-			/**
-			 * 
-			 * A discovered resource must have a unique key, that must stay the
-			 * same when the resource is discovered the next time
-			 */
-			DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
-					discoveryContext.getResourceType(), // ResourceType
-					vdbKey, // Resource Key
-					vdbName, // Resource Name
-					vdbVersion.toString(), // Version
-					PluginConstants.ComponentType.VDB.DESCRIPTION, // Description
-					discoveryContext.getDefaultPluginConfiguration(), // Plugin
-					// Config
-					null // Process info from a process scan
-			);
-
-			// Get plugin config map for properties
-			Configuration configuration = detail.getPluginConfiguration();
-
-			configuration.put(new PropertySimple("name", vdbName));
-			configuration.put(new PropertySimple("fullName", fullName));
-			configuration.put(new PropertySimple("version", vdbVersion));
-			configuration
-					.put(new PropertySimple("description", vdbDescription));
-			configuration.put(new PropertySimple("status", vdbStatus));
-			configuration.put(new PropertySimple("url", vdbURL));
-
-			detail.setPluginConfiguration(configuration);
-
-			// Add to return values
-			discoveredResources.add(detail);
-			log.debug("Discovered Teiid VDB: " + vdbName);
-		}
-
-		return discoveredResources;
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,144 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.plugins.jbossas5.connection.ProfileServiceConnection;
+import org.teiid.rhq.plugin.util.PluginConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * Discovery component for VDBs
+ * 
+ */
+public class VDBDiscoveryComponent implements ResourceDiscoveryComponent {
+
+	private final Log log = LogFactory
+			.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+	public Set<DiscoveredResourceDetails> discoverResources(
+			ResourceDiscoveryContext discoveryContext)
+			throws InvalidPluginConfigurationException, Exception {
+		Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
+		ProfileServiceConnection connection = ((PlatformComponent) discoveryContext
+				.getParentResourceComponent()).getConnection();
+
+		Set<ManagedComponent> vdbs = ProfileServiceUtil
+				.getManagedComponents(connection, new ComponentType(
+						PluginConstants.ComponentType.VDB.TYPE,
+						PluginConstants.ComponentType.VDB.SUBTYPE));
+		
+		PropertySimple displayPreviewVdbs = ((PlatformComponent)discoveryContext.getParentResourceComponent()).getResourceConfiguration().getSimple("displayPreviewVDBS");
+		
+		for (ManagedComponent mcVdb : vdbs) {
+
+			boolean skipVdb = false;
+			if (!displayPreviewVdbs.getBooleanValue()){
+				MetaValue[] propsArray = ((CollectionValueSupport)mcVdb.getProperty("JAXBProperties").getValue()).getElements();
+				String isPreview = "false";
+				
+				for (MetaValue propertyMetaData : propsArray) {
+					GenericValueSupport genValueSupport = (GenericValueSupport) propertyMetaData;
+					ManagedObjectImpl managedObject = (ManagedObjectImpl) genValueSupport
+							.getValue();
+	
+					String propertyName = ProfileServiceUtil.getSimpleValue(
+							managedObject, "name", String.class);
+					if (propertyName.equals("preview")){
+						isPreview =ProfileServiceUtil.getSimpleValue(
+								managedObject, "value", String.class);
+						if (Boolean.valueOf(isPreview)) skipVdb=true;
+						break;
+					}
+				}	
+			}
+				
+			//If this is a Preview VDB and displayPreviewVdbs is false, skip this VDB
+			if (skipVdb) continue;
+				
+			String vdbKey = (String)mcVdb.getName();
+			String vdbName = vdbKey;
+			String fullName = ProfileServiceUtil.getSimpleValue(mcVdb, "fullName",
+					String.class);
+			Integer vdbVersion = ProfileServiceUtil.getSimpleValue(mcVdb,
+					"version", Integer.class);
+			String vdbDescription = ProfileServiceUtil.getSimpleValue(mcVdb,
+					"description", String.class);
+			String vdbStatus = ProfileServiceUtil.getSimpleValue(mcVdb,
+					"status", String.class);
+			String vdbURL = ProfileServiceUtil.getSimpleValue(mcVdb, "url",
+					String.class);
+
+			/**
+			 * 
+			 * A discovered resource must have a unique key, that must stay the
+			 * same when the resource is discovered the next time
+			 */
+			DiscoveredResourceDetails detail = new DiscoveredResourceDetails(
+					discoveryContext.getResourceType(), // ResourceType
+					vdbKey, // Resource Key
+					vdbName, // Resource Name
+					vdbVersion.toString(), // Version
+					PluginConstants.ComponentType.VDB.DESCRIPTION, // Description
+					discoveryContext.getDefaultPluginConfiguration(), // Plugin
+					// Config
+					null // Process info from a process scan
+			);
+
+			// Get plugin config map for properties
+			Configuration configuration = detail.getPluginConfiguration();
+
+			configuration.put(new PropertySimple("name", vdbName));
+			configuration.put(new PropertySimple("fullName", fullName));
+			configuration.put(new PropertySimple("version", vdbVersion));
+			configuration
+					.put(new PropertySimple("description", vdbDescription));
+			configuration.put(new PropertySimple("status", vdbStatus));
+			configuration.put(new PropertySimple("url", vdbURL));
+
+			detail.setPluginConfiguration(configuration);
+
+			// Add to return values
+			discoveredResources.add(detail);
+			log.debug("Discovered Teiid VDB: " + vdbName);
+		}
+
+		return discoveredResources;
+	}
+
+}
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,125 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin.adapter.api;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.metatype.api.types.MapCompositeMetaType;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.PropertiesMetaType;
-import org.jboss.metatype.api.values.MetaValue;
-import org.rhq.core.domain.configuration.PropertySimple;
-import org.teiid.rhq.plugin.adapter.impl.PropertyListToArrayValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyListToCollectionValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyMapToCompositeValueSupportAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyMapToGenericValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyMapToMapCompositeValueSupportAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyMapToPropertiesValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertyMapToTableValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToEnumValueAdapter;
-import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToSimpleValueAdapter;
-import org.teiid.rhq.plugin.util.PluginConstants;
-
-import com.sun.istack.Nullable;
-
-/**
- * 
- */
-public class PropertyAdapterFactory
-{
-    private static final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
-
-    public static PropertyAdapter getPropertyAdapter(MetaValue metaValue)
-    {
-        if (metaValue == null)
-        {
-            LOG.debug("The MetaValue passed in is null.");
-            return null;
-        }
-        MetaType metaType = metaValue.getMetaType();
-        return getPropertyAdapter(metaType);
-    }
-
-    public static PropertyAdapter getPropertyAdapter(MetaType metaType)
-    {
-        PropertyAdapter propertyAdapter = null;
-        if (metaType.isSimple())
-        {
-            propertyAdapter = new PropertySimpleToSimpleValueAdapter();
-        }
-        else if (metaType.isGeneric())
-        {
-            propertyAdapter = new PropertyMapToGenericValueAdapter();
-        }
-        else if (metaType.isComposite())
-        {
-            if (metaType instanceof MapCompositeMetaType)
-                propertyAdapter = new PropertyMapToMapCompositeValueSupportAdapter();
-            else
-                propertyAdapter = new PropertyMapToCompositeValueSupportAdapter();
-        }
-        else if (metaType.isTable())
-        {
-            propertyAdapter = new PropertyMapToTableValueAdapter();
-        }
-        else if (metaType.isCollection())
-        {
-            propertyAdapter = new PropertyListToCollectionValueAdapter();
-        }
-        else if (metaType.isArray())
-        {
-            propertyAdapter = new PropertyListToArrayValueAdapter();
-        }
-        else if (metaType.isEnum())
-        {
-            propertyAdapter = new PropertySimpleToEnumValueAdapter();
-        }
-        else if (metaType instanceof PropertiesMetaType)
-        {
-            propertyAdapter = new PropertyMapToPropertiesValueAdapter();
-        }
-        else
-        {
-            LOG.warn("Unsupported MetaType: " + metaType);
-        }
-        return propertyAdapter;
-    }
-
-    @Nullable
-    public static PropertyAdapter getCustomPropertyAdapter(PropertySimple customProp)
-    {
-        if (customProp == null)
-            return null;
-        String adapterClassName = customProp.getStringValue();
-        PropertyAdapter propertyAdapter = null;
-        try
-        {
-            Class adapterClass = Class.forName(adapterClassName);
-            propertyAdapter = (PropertyAdapter)adapterClass.newInstance();
-        }
-        catch (Exception e)
-        {
-            LOG.error("Unable to create custom adapter class for " + customProp + ".", e);
-        }
-        return propertyAdapter;
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,120 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.PropertiesMetaType;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.teiid.rhq.plugin.adapter.impl.PropertyListToCollectionValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToCompositeValueSupportAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToGenericValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToMapCompositeValueSupportAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToPropertiesValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToTableValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToEnumValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToSimpleValueAdapter;
+import org.teiid.rhq.plugin.util.PluginConstants;
+
+import com.sun.istack.Nullable;
+
+/**
+ * 
+ */
+public class PropertyAdapterFactory
+{
+    private static final Log LOG = LogFactory.getLog(PluginConstants.DEFAULT_LOGGER_CATEGORY);
+
+    public static PropertyAdapter getPropertyAdapter(MetaValue metaValue)
+    {
+        if (metaValue == null)
+        {
+            LOG.debug("The MetaValue passed in is null.");
+            return null;
+        }
+        MetaType metaType = metaValue.getMetaType();
+        return getPropertyAdapter(metaType);
+    }
+
+    public static PropertyAdapter getPropertyAdapter(MetaType metaType)
+    {
+        PropertyAdapter propertyAdapter = null;
+        if (metaType.isSimple())
+        {
+            propertyAdapter = new PropertySimpleToSimpleValueAdapter();
+        }
+        else if (metaType.isGeneric())
+        {
+            propertyAdapter = new PropertyMapToGenericValueAdapter();
+        }
+        else if (metaType.isComposite())
+        {
+            if (metaType instanceof MapCompositeMetaType)
+                propertyAdapter = new PropertyMapToMapCompositeValueSupportAdapter();
+            else
+                propertyAdapter = new PropertyMapToCompositeValueSupportAdapter();
+        }
+        else if (metaType.isTable())
+        {
+            propertyAdapter = new PropertyMapToTableValueAdapter();
+        }
+        else if (metaType.isCollection())
+        {
+            propertyAdapter = new PropertyListToCollectionValueAdapter();
+        }
+        else if (metaType.isEnum())
+        {
+            propertyAdapter = new PropertySimpleToEnumValueAdapter();
+        }
+        else if (metaType instanceof PropertiesMetaType)
+        {
+            propertyAdapter = new PropertyMapToPropertiesValueAdapter();
+        }
+        else
+        {
+            LOG.warn("Unsupported MetaType: " + metaType);
+        }
+        return propertyAdapter;
+    }
+
+    @Nullable
+    public static PropertyAdapter getCustomPropertyAdapter(PropertySimple customProp)
+    {
+        if (customProp == null)
+            return null;
+        String adapterClassName = customProp.getStringValue();
+        PropertyAdapter propertyAdapter = null;
+        try
+        {
+            Class adapterClass = Class.forName(adapterClassName);
+            propertyAdapter = (PropertyAdapter)adapterClass.newInstance();
+        }
+        catch (Exception e)
+        {
+            LOG.error("Unable to create custom adapter class for " + customProp + ".", e);
+        }
+        return propertyAdapter;
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,93 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin.adapter.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.rhq.core.domain.configuration.Property;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.configuration.definition.PropertyDefinition;
-import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
-import org.teiid.rhq.plugin.adapter.api.AbstractPropertyListAdapter;
-import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
-import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
-
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.ArrayValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-
-/**
- * 
- */
-public class PropertyListToArrayValueAdapter extends AbstractPropertyListAdapter implements PropertyAdapter<PropertyList, PropertyDefinitionList>
-{
-    //@todo need to implement this like the other List to Collection, but not until there is an actual property that needs this
-    public void populateMetaValueFromProperty(PropertyList property, MetaValue metaValue, PropertyDefinitionList propertyDefinition)
-    {
-        PropertyDefinition memberDefinition = propertyDefinition.getMemberDefinition();
-        List<Property> properties = property.getList();
-        if (metaValue != null)
-        {
-            ArrayValueSupport valueSupport = (ArrayValueSupport)metaValue;
-            MetaType listMetaType = valueSupport.getMetaType().getElementType();
-            List<MetaValue> values = new ArrayList<MetaValue>(properties.size());
-            for (Property propertyWithinList : properties)
-            {
-                MetaValue value = MetaValueFactory.getInstance().create(null);
-                PropertyAdapter<Property, PropertyDefinition> propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMetaType);
-                propertyAdapter.populateMetaValueFromProperty(propertyWithinList, value, memberDefinition);
-                values.add(value);
-            }
-            valueSupport.setValue(values.toArray());
-        }
-    }
-
-    //@todo need to implement this like the other List to Collection, but not until there is an actual property that needs this
-    public MetaValue convertToMetaValue(PropertyList property, PropertyDefinitionList propertyDefinition, MetaType type)
-    {
-        return null;
-    }
-
-    public void populatePropertyFromMetaValue(PropertyList property, MetaValue metaValue, PropertyDefinitionList propertyDefinition)
-    {
-        PropertyDefinition memberDefinition = propertyDefinition.getMemberDefinition();
-        List<Property> properties = property.getList();
-
-        // Since we want to load the PropertyList with fresh values, we want it cleared out
-        properties.clear();
-
-        if (metaValue != null)
-        {
-            ArrayValueSupport valueSupport = (ArrayValueSupport)metaValue;
-            MetaType listMetaType = valueSupport.getMetaType().getElementType();
-            MetaValue[] metaValues = (MetaValue[])valueSupport.getValue();
-            PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMetaType);
-            for (MetaValue value : metaValues)
-            {
-                Property propertyToAddToList = propertyAdapter.convertToProperty(value, memberDefinition);
-                properties.add(propertyToAddToList);
-            }
-        }
-    }
-}

Deleted: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,260 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin.util;
-
-/**
- * These are the Constants that used in conjunction with using the
- * 
- * @since 5.5.3
- */
-public interface PluginConstants {
-
-	/**
-	 * These are properties required for connecting to the profile service and
-	 * getting a handle to a specific component related to Teiid.
-	 */
-
-	/**
-	 * These are global properties used by all components
-	 */
-	public final static String PROFILE_SERVICE = "ProfileService"; //$NON-NLS-1$
-	
-	/**
-	 * Log4j log category to use
-	 */
-	public final static String DEFAULT_LOGGER_CATEGORY = "org.rhq"; //$NON-NLS-1$
-	
-	
-	/**
-	 * Use these component type names when calling Connection related methods
-	 * that require the type.
-	 * 
-	 * @since 1.0
-	 */
-	public interface ComponentType {
-
-		public interface Platform {
-
-			public final static String NAME = "Platform"; //$NON-NLS-1$
-			public final static String TEIID_TYPE = "teiid"; //$NON-NLS-1$
-			public final static String TEIID_SUB_TYPE = "dqp"; //$NON-NLS-1$
-			public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
-			public final static String SUBTYPE = "NoTx"; //$NON-NLS-1$
-			public final static String TEIID_RUNTIME_ENGINE = "RuntimeEngineDeployer"; //$NON-NLS-1$
-			public final static String TEIID_ENGINE_RESOURCE_NAME = "Data Services"; //$NON-NLS-1$
-			public final static String TEIID_ENGINE_RESOURCE_DESCRIPTION = "Teiid Data Service Runtime Engine"; //$NON-NLS-1$
-
-			public static interface Operations {
-
-				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$					
-				public final static String GET_LONGRUNNINGQUERIES = "getLongRunningRequests"; //$NON-NLS-1$
-				public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
-				public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
-				public final static String KILL_TRANSACTION = "terminateTransaction"; //$NON-NLS-1$
-				public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
-				public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
-				public final static String GET_TRANSACTIONS = "getTransactions"; //$NON-NLS-1$
-				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
-				public final static String GET_BUFFER_USAGE = "userBufferSpace"; //$NON-NLS-1$
-				public final static String GET_CACHE_STATS = "getCacheStatistics"; //$NON-NLS-1$
-				public final static String DEPLOY_VDB_BY_URL = "deployVdbByUrl"; //$NON-NLS-1$
-			}
-
-			public static interface Metrics {
-				public final static String QUERY_COUNT = "queryCount"; //$NON-NLS-1$            
-				public final static String SESSION_COUNT = "sessionCount"; //$NON-NLS-1$
-				public final static String LONG_RUNNING_QUERIES = "longRunningQueries"; //$NON-NLS-1$     
-				public final static String BUFFER_USAGE = "userBufferSpace"; //$NON-NLS-1$
-			}
-		}
-
-		public interface VDB {
-
-			public final static String TYPE = "teiid"; //$NON-NLS-1$
-			public final static String SUBTYPE = "vdb"; //$NON-NLS-1$
-			public final static String NAME = "Teiid Virtual Database"; //$NON-NLS-1$
-			public final static String VERSION = "version"; //$NON-NLS-1$
-			public final static String DESCRIPTION = "Teiid Virtual Database (VDB)"; //$NON-NLS-1$
-
-			public static interface Operations {
-
-				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$	
-				public final static String EXECUTE_QUERIES = "executeQuery"; //$NON-NLS-1$
-				public final static String GET_LONGRUNNINGQUERIES = "getLongRunningRequests"; //$NON-NLS-1$
-				public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
-				public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
-				public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
-				public final static String GET_REQUESTS = "getRequestsUsingVDB"; //$NON-NLS-1$
-				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
-				public final static String GET_MATVIEWS = "getMaterializedViews"; //$NON-NLS-1$
-				public final static String RELOAD_MATVIEW = "reloadMaterializedView"; //$NON-NLS-1$
-
-			}
-			
-			public static interface Metrics {
-
-				public final static String STATUS = "status"; //$NON-NLS-1$ 
-				public final static String QUERY_COUNT = "queryCount"; //$NON-NLS-1$            
-				public final static String ERROR_COUNT = "errorCount"; //$NON-NLS-1$
-				public final static String SESSION_COUNT = "sessionCount"; //$NON-NLS-1$
-				public final static String LONG_RUNNING_QUERIES = "longRunningQueries"; //$NON-NLS-1$     
-
-			}
-
-		}
-		
-		public interface DATA_ROLE {
-
-			public final static String NAME = "VDB Data Role"; //$NON-NLS-1$
-			public final static String DESCRIPTION = "Data/Security Role for a Teiid Virtual Database (VDB)"; //$NON-NLS-1$
-
-			public static interface Operations {
-			}
-			
-			public static interface Metrics {
-			}
-
-		}
-
-		public interface Translator {
-
-			public final static String TYPE = "teiid"; //$NON-NLS-1$
-			public final static String SUBTYPE = "translator"; //$NON-NLS-1$
-			public final static String NAME = "Translator"; //$NON-NLS-1$
-
-			public static interface Operations {
-
-			}
-			
-			public static interface Metrics {
-
-			}
-
-		}
-		public interface Model {
-
-			public final static String TYPE = "teiid"; //$NON-NLS-1$
-			public final static String SUBTYPE = "model"; //$NON-NLS-1$
-			public final static String NAME = "Model"; //$NON-NLS-1$
-			public final static String DESCRIPTION = "Model used to map to a source"; //$NON-NLS-1$
-
-		}
-
-		public interface Connector {
-
-			public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
-			public final static String SUBTYPE_NOTX = "NoTx"; //$NON-NLS-1$
-			public final static String SUBTYPE_TX = "Tx"; //$NON-NLS-1$
-			public final static String NAME = "Enterprise Connector"; //$NON-NLS-1$
-			public final static String DESCRIPTION = "JBoss Enterprise Connector Binding"; //$NON-NLS-1$
-
-			public static interface Operations {
-
-				public final static String RESTART_CONNECTOR = "restart"; //$NON-NLS-1$            
-				public final static String STOP_CONNECTOR = "stop"; //$NON-NLS-1$ 
-
-			}
-
-		}
-
-		public interface Session {
-
-			public final static String TYPE = "Runtime.Sesssion"; //$NON-NLS-1$
-
-			public static interface Query {
-
-				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
-			}
-		}
-
-		public interface Queries {
-
-			public final static String TYPE = "Runtime.Queries"; //$NON-NLS-1$
-
-			public static interface Query {
-
-				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$
-			}
-		}
-
-	}
-
-	/**
-	 * Use these metric names when calling getValues() on the connection
-	 * interface.
-	 * 
-	 * @since 1.0
-	 */
-	public interface Metric {
-		public final static String HIGH_WATER_MARK = "highWatermark"; //$NON-NLS-1$
-
-	}
-
-	/**
-	 * Use these operation names when calling executeOperation() on the
-	 * connection interface.
-	 * 
-	 * @since 1.0
-	 */
-	public static interface Operation {
-		public final static String KILL_REQUEST = "killRequest"; //$NON-NLS-1$
-		public final static String GET_VDBS = "listVDBs"; //$NON-NLS-1$
-		public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
-		public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
-		public final static String GET_SESSIONS = "getActiveSessions"; //$NON-NLS-1$
-
-		/**
-		 * Use these value names when calling executeOperation() on the
-		 * connection interface. These will correlate with parameters used in
-		 * operations.
-		 * 
-		 * @since 1.0
-		 */
-		public static interface Value {
-			public final static String STOP_NOW = "stopNow"; //$NON-NLS-1$  
-			public final static String MAT_VIEW_QUERY = "select SchemaName, Name, TargetSchemaName, TargetName, " + //$NON-NLS-1$ 
-														"Valid, LoadState, Updated, Cardinality from SYSADMIN.MATVIEWS " +  //$NON-NLS-1$  
-														"where SchemaName != 'pg_catalog'"; //$NON-NLS-1$  
-			public final static String MAT_VIEW_REFRESH = "exec SYSADMIN.refreshMatView('param1','param2');";  //$NON-NLS-1$
-			public final static String WAIT_UNTIL_FINISHED = "waitUntilFinished"; //$NON-NLS-1$
-
-			public final static String INCLUDE_SOURCE_QUERIES = "includeSourceQueries"; //$NON-NLS-1$
-
-			public final static String LONG_RUNNING_QUERY_LIMIT = "longRunningQueryLimit"; //$NON-NLS-1$
-
-			public final static String FIELD_LIST = "fieldList"; //$NON-NLS-1$
-			public final static String TRANSACTION_ID = "transactionID"; //$NON-NLS-1$
-			public final static String REQUEST_ID = "requestID"; //$NON-NLS-1$
-			public final static String SESSION_ID = "sessionID"; //$NON-NLS-1$
-			public final static String VDB_URL = "vdbUrl"; //$NON-NLS-1$
-			public final static String VDB_DEPLOY_NAME = "vdbDeployName"; //$NON-NLS-1$
-			public final static String VDB_VERSION = "vdbVersion"; //$NON-NLS-1$
-			public final static String NAME = "Name"; //$NON-NLS-1$
-			public final static String VALUE = "Value"; //$NON-NLS-1$
-			public final static String MATVIEW_SCHEMA = "schema"; //$NON-NLS-1$
-			public final static String MATVIEW_TABLE = "table"; //$NON-NLS-1$
-			public final static String INVALIDATE_MATVIEW = "invalidate"; //$NON-NLS-1$
-
-		}
-
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java (from rev 2774, trunk/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,262 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.util;
+
+/**
+ * These are the Constants that used in conjunction with using the
+ * 
+ * @since 5.5.3
+ */
+public interface PluginConstants {
+
+	/**
+	 * These are properties required for connecting to the profile service and
+	 * getting a handle to a specific component related to Teiid.
+	 */
+
+	/**
+	 * These are global properties used by all components
+	 */
+	public final static String PROFILE_SERVICE = "ProfileService"; //$NON-NLS-1$
+	
+	/**
+	 * Log4j log category to use
+	 */
+	public final static String DEFAULT_LOGGER_CATEGORY = "org.rhq"; //$NON-NLS-1$
+	
+	
+	/**
+	 * Use these component type names when calling Connection related methods
+	 * that require the type.
+	 * 
+	 * @since 1.0
+	 */
+	public interface ComponentType {
+
+		public interface Platform {
+
+			public final static String NAME = "Platform"; //$NON-NLS-1$
+			public final static String TEIID_TYPE = "teiid"; //$NON-NLS-1$
+			public final static String TEIID_SUB_TYPE = "dqp"; //$NON-NLS-1$
+			public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
+			public final static String SUBTYPE = "NoTx"; //$NON-NLS-1$
+			public final static String TEIID_RUNTIME_ENGINE = "RuntimeEngineDeployer"; //$NON-NLS-1$
+			public final static String TEIID_ENGINE_RESOURCE_NAME = "Data Services"; //$NON-NLS-1$
+			public final static String TEIID_ENGINE_RESOURCE_DESCRIPTION = "Teiid Data Service Runtime Engine"; //$NON-NLS-1$
+
+			public static interface Operations {
+
+				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$					
+				public final static String GET_LONGRUNNINGQUERIES = "getLongRunningRequests"; //$NON-NLS-1$
+				public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
+				public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
+				public final static String KILL_TRANSACTION = "terminateTransaction"; //$NON-NLS-1$
+				public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
+				public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
+				public final static String GET_TRANSACTIONS = "getTransactions"; //$NON-NLS-1$
+				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
+				public final static String GET_BUFFER_USAGE = "userBufferSpace"; //$NON-NLS-1$
+				public final static String GET_CACHE_STATS = "getCacheStatistics"; //$NON-NLS-1$
+				public final static String DEPLOY_VDB_BY_URL = "deployVdbByUrl"; //$NON-NLS-1$
+			}
+
+			public static interface Metrics {
+				public final static String QUERY_COUNT = "queryCount"; //$NON-NLS-1$            
+				public final static String SESSION_COUNT = "sessionCount"; //$NON-NLS-1$
+				public final static String LONG_RUNNING_QUERIES = "longRunningQueries"; //$NON-NLS-1$     
+				public final static String BUFFER_USAGE = "userBufferSpace"; //$NON-NLS-1$
+			}
+		}
+
+		public interface VDB {
+
+			public final static String TYPE = "teiid"; //$NON-NLS-1$
+			public final static String SUBTYPE = "vdb"; //$NON-NLS-1$
+			public final static String NAME = "Teiid Virtual Database"; //$NON-NLS-1$
+			public final static String VERSION = "version"; //$NON-NLS-1$
+			public final static String DESCRIPTION = "Teiid Virtual Database (VDB)"; //$NON-NLS-1$
+
+			public static interface Operations {
+
+				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$	
+				public final static String CLEAR_CACHE = "clearCache"; //$NON-NLS-1$	
+				public final static String EXECUTE_QUERIES = "executeQuery"; //$NON-NLS-1$
+				public final static String GET_LONGRUNNINGQUERIES = "getLongRunningRequests"; //$NON-NLS-1$
+				public final static String KILL_REQUEST = "cancelRequest"; //$NON-NLS-1$
+				public final static String KILL_SESSION = "terminateSession"; //$NON-NLS-1$
+				public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
+				public final static String GET_REQUESTS = "getRequestsUsingVDB"; //$NON-NLS-1$
+				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
+				public final static String GET_MATVIEWS = "getMaterializedViews"; //$NON-NLS-1$
+				public final static String RELOAD_MATVIEW = "reloadMaterializedView"; //$NON-NLS-1$
+
+			}
+			
+			public static interface Metrics {
+
+				public final static String STATUS = "status"; //$NON-NLS-1$ 
+				public final static String QUERY_COUNT = "queryCount"; //$NON-NLS-1$            
+				public final static String ERROR_COUNT = "errorCount"; //$NON-NLS-1$
+				public final static String SESSION_COUNT = "sessionCount"; //$NON-NLS-1$
+				public final static String LONG_RUNNING_QUERIES = "longRunningQueries"; //$NON-NLS-1$     
+
+			}
+
+		}
+		
+		public interface DATA_ROLE {
+
+			public final static String NAME = "VDB Data Role"; //$NON-NLS-1$
+			public final static String DESCRIPTION = "Data/Security Role for a Teiid Virtual Database (VDB)"; //$NON-NLS-1$
+
+			public static interface Operations {
+			}
+			
+			public static interface Metrics {
+			}
+
+		}
+
+		public interface Translator {
+
+			public final static String TYPE = "teiid"; //$NON-NLS-1$
+			public final static String SUBTYPE = "translator"; //$NON-NLS-1$
+			public final static String NAME = "Translator"; //$NON-NLS-1$
+
+			public static interface Operations {
+
+			}
+			
+			public static interface Metrics {
+
+			}
+
+		}
+		public interface Model {
+
+			public final static String TYPE = "teiid"; //$NON-NLS-1$
+			public final static String SUBTYPE = "model"; //$NON-NLS-1$
+			public final static String NAME = "Model"; //$NON-NLS-1$
+			public final static String DESCRIPTION = "Model used to map to a source"; //$NON-NLS-1$
+
+		}
+
+		public interface Connector {
+
+			public final static String TYPE = "ConnectionFactory"; //$NON-NLS-1$
+			public final static String SUBTYPE_NOTX = "NoTx"; //$NON-NLS-1$
+			public final static String SUBTYPE_TX = "Tx"; //$NON-NLS-1$
+			public final static String NAME = "Enterprise Connector"; //$NON-NLS-1$
+			public final static String DESCRIPTION = "JBoss Enterprise Connector Binding"; //$NON-NLS-1$
+
+			public static interface Operations {
+
+				public final static String RESTART_CONNECTOR = "restart"; //$NON-NLS-1$            
+				public final static String STOP_CONNECTOR = "stop"; //$NON-NLS-1$ 
+
+			}
+
+		}
+
+		public interface Session {
+
+			public final static String TYPE = "Runtime.Sesssion"; //$NON-NLS-1$
+
+			public static interface Query {
+
+				public final static String GET_SESSIONS = "getSessions"; //$NON-NLS-1$
+			}
+		}
+
+		public interface Queries {
+
+			public final static String TYPE = "Runtime.Queries"; //$NON-NLS-1$
+
+			public static interface Query {
+
+				public final static String GET_QUERIES = "listQueries"; //$NON-NLS-1$
+			}
+		}
+
+	}
+
+	/**
+	 * Use these metric names when calling getValues() on the connection
+	 * interface.
+	 * 
+	 * @since 1.0
+	 */
+	public interface Metric {
+		public final static String HIGH_WATER_MARK = "highWatermark"; //$NON-NLS-1$
+
+	}
+
+	/**
+	 * Use these operation names when calling executeOperation() on the
+	 * connection interface.
+	 * 
+	 * @since 1.0
+	 */
+	public static interface Operation {
+		public final static String KILL_REQUEST = "killRequest"; //$NON-NLS-1$
+		public final static String GET_VDBS = "listVDBs"; //$NON-NLS-1$
+		public final static String GET_PROPERTIES = "getProperties"; //$NON-NLS-1$
+		public final static String GET_REQUESTS = "getRequests"; //$NON-NLS-1$
+		public final static String GET_SESSIONS = "getActiveSessions"; //$NON-NLS-1$
+
+		/**
+		 * Use these value names when calling executeOperation() on the
+		 * connection interface. These will correlate with parameters used in
+		 * operations.
+		 * 
+		 * @since 1.0
+		 */
+		public static interface Value {
+			public final static String STOP_NOW = "stopNow"; //$NON-NLS-1$  
+			public final static String MAT_VIEW_QUERY = "select SchemaName, Name, TargetSchemaName, TargetName, " + //$NON-NLS-1$ 
+														"Valid, LoadState, Updated, Cardinality from SYSADMIN.MATVIEWS " +  //$NON-NLS-1$  
+														"where SchemaName != 'pg_catalog'"; //$NON-NLS-1$  
+			public final static String MAT_VIEW_REFRESH = "exec SYSADMIN.refreshMatView('param1','param2');";  //$NON-NLS-1$
+			public final static String WAIT_UNTIL_FINISHED = "waitUntilFinished"; //$NON-NLS-1$
+
+			public final static String INCLUDE_SOURCE_QUERIES = "includeSourceQueries"; //$NON-NLS-1$
+
+			public final static String LONG_RUNNING_QUERY_LIMIT = "longRunningQueryLimit"; //$NON-NLS-1$
+
+			public final static String FIELD_LIST = "fieldList"; //$NON-NLS-1$
+			public final static String TRANSACTION_ID = "transactionID"; //$NON-NLS-1$
+			public final static String REQUEST_ID = "requestID"; //$NON-NLS-1$
+			public final static String SESSION_ID = "sessionID"; //$NON-NLS-1$
+			public final static String VDB_URL = "vdbUrl"; //$NON-NLS-1$
+			public final static String VDB_DEPLOY_NAME = "vdbDeployName"; //$NON-NLS-1$
+			public final static String VDB_VERSION = "vdbVersion"; //$NON-NLS-1$
+			public final static String NAME = "Name"; //$NON-NLS-1$
+			public final static String VALUE = "Value"; //$NON-NLS-1$
+			public final static String MATVIEW_SCHEMA = "schema"; //$NON-NLS-1$
+			public final static String MATVIEW_TABLE = "table"; //$NON-NLS-1$
+			public final static String INVALIDATE_MATVIEW = "invalidate"; //$NON-NLS-1$
+			public final static String CACHE_TYPE = "cacheType"; //$NON-NLS-1$
+
+		}
+
+	}
+}

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml
===================================================================
--- trunk/documentation/admin-guide/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/admin-guide/pom.xml (from rev 2777, trunk/documentation/admin-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/admin-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/caching-guide/pom.xml
===================================================================
--- trunk/documentation/caching-guide/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/caching-guide/pom.xml (from rev 2777, trunk/documentation/caching-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml
===================================================================
--- trunk/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,64 +0,0 @@
-<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="cache-hint-options">
-    <title>Hints and Options</title>
-	<section id="cache-hint">
-		<title>Cache Hint</title>
-	   	<para>A query cache hint can be used to:</para>
-	   	<itemizedlist>
-	   		<listitem><para>Indicate that a user query is eligible for result set caching and set the cache entry memory preference or time to live.
-	   		</para></listitem>
-	   		<listitem><para>Set the materialized view memory preference, time to live, or updatablity.
-	   		</para></listitem>
-	   		<listitem><para>Indicate that a virtual procedure should be cachable and set the cache entry memory preference or time to live.
-	   		</para></listitem>
-	   	</itemizedlist>
-	   	<para><synopsis>/*+ cache[([pref_mem] [ttl:n] [updatable])] [scope:(session|user|vdb)] */ sql ...</synopsis>
-	   	<itemizedlist>
-	   		<listitem><para>The cache hint should appear at the beginning of the SQL.  It will not have any affect on INSERT/UPDATE/DELETE statements or virtual update procedure definitions.</para></listitem>
-	   		<listitem><para><emphasis>pref_mem</emphasis> - if present indicates that the cached results should prefer to remain in memory.  They are not however required to be memory only.
-	   		</para></listitem>
-	   		<listitem><para><emphasis>ttl:n</emphasis> - if present n indicates the time to live value in milliseconds.
-	   		</para></listitem>
-	   		<listitem><para><emphasis>updatable</emphasis> - if present indicates that the cached results can be updated.  This is currently only applicable to materialized views.
-	   		</para></listitem>
-            <listitem><para><emphasis>scope</emphasis> - if present indicates the override scope of query results. Using this flag, user can override the computed scope, to improve or force the results to cache.
-            There are three different cache scopes, session - cached only for current session, user - cached for any session by the current user, vdb - cached for any user connected to the same vdb. 
-            </para></listitem>
-            
-	 	</itemizedlist>
-	   	</para>
-	   	   	<section>
-   		<title>Limitations</title>
-	   	<itemizedlist>
-	   		<listitem><para>The form of the query hint must be matched exactly for the hint to have affect.  
-	   		For a user query if the hint is not specified correctly, e.g. <code>/*+ cach(pref_mem) */</code>, it will not be used by the engine nor will 
-	   		there be an informational log.  As a workaround, the query plan may be checked though (see the Client Developers Guide) to see if the user command
-	   		in the plan has retained the proper hint.
-	   		</para></listitem>
-	  	</itemizedlist>
-	   	</section>
-   	</section>
-   	<section id="nocache">
-   		<title>OPTION NOCACHE</title>
-   		<para>Individual queries may override the use of cached results by
-			specifying <code>OPTION NOCACHE</code> on the query.  0 or more fully qualified view or procedure names may be specified to exclude using their cached results.  
-			If no names are specified, cached results will not be used transitively.
-		</para>
-		<example>
-			<title>Full NOCACHE</title>
-			<programlisting>SELECT * from vg1, vg2, vg3 WHERE … OPTION NOCACHE</programlisting>
-			<para>No cached results will be used at all.</para>
-		</example>
-		<example>
-			<title>Specific NOCACHE</title>
-			<programlisting>SELECT * from vg1, vg2, vg3 WHERE … OPTION NOCACHE vg1, vg3</programlisting>
-			<para>Only the vg1 and vg3 caches will be skipped, vg2 or any cached results nested under vg1 and vg3 will be used.</para>
-		</example>
-		<para><code>OPTION NOCACHE</code> may be specified in procedure or view definitions.  In that way, transformations can
-			specify to always use real-time data obtained directly from sources.
-			</para>
-   	</section>
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml (from rev 2762, trunk/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/caching-guide/src/main/docbook/en-US/content/hint-option.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,64 @@
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="cache-hint-options">
+    <title>Hints and Options</title>
+	<section id="cache-hint">
+		<title>Cache Hint</title>
+	   	<para>A query cache hint can be used to:</para>
+	   	<itemizedlist>
+	   		<listitem><para>Indicate that a user query is eligible for result set caching and set the cache entry memory preference or time to live.
+	   		</para></listitem>
+	   		<listitem><para>Set the materialized view memory preference, time to live, or updatablity.
+	   		</para></listitem>
+	   		<listitem><para>Indicate that a virtual procedure should be cachable and set the cache entry memory preference or time to live.
+	   		</para></listitem>
+	   	</itemizedlist>
+	   	<para><synopsis>/*+ cache[([pref_mem] [ttl:n] [updatable])] [scope:(session|user|vdb)] */ sql ...</synopsis>
+	   	<itemizedlist>
+	   		<listitem><para>The cache hint should appear at the beginning of the SQL.  It will not have any affect on INSERT/UPDATE/DELETE statements or virtual update procedure definitions.</para></listitem>
+	   		<listitem><para><emphasis>pref_mem</emphasis> - if present indicates that the cached results should prefer to remain in memory.  They are not however required to be memory only.
+	   		</para></listitem>
+	   		<listitem><para><emphasis>ttl:n</emphasis> - if present n indicates the time to live value in milliseconds.
+	   		</para></listitem>
+	   		<listitem><para><emphasis>updatable</emphasis> - if present indicates that the cached results can be updated.  This is currently only applicable to materialized views.
+	   		</para></listitem>
+            <listitem><para><emphasis>scope</emphasis> - if present indicates the override scope of query results. Using this flag, the user can override the computed scope.
+            There are three different cache scopes: session - cached only for current session, user - cached for any session by the current user, vdb - cached for any user connected to the same vdb. 
+            </para></listitem>
+            
+	 	</itemizedlist>
+	   	</para>
+	   	   	<section>
+   		<title>Limitations</title>
+	   	<itemizedlist>
+	   		<listitem><para>The form of the query hint must be matched exactly for the hint to have affect.  
+	   		For a user query if the hint is not specified correctly, e.g. <code>/*+ cach(pref_mem) */</code>, it will not be used by the engine nor will 
+	   		there be an informational log.  As a workaround, the query plan may be checked though (see the Client Developers Guide) to see if the user command
+	   		in the plan has retained the proper hint.
+	   		</para></listitem>
+	  	</itemizedlist>
+	   	</section>
+   	</section>
+   	<section id="nocache">
+   		<title>OPTION NOCACHE</title>
+   		<para>Individual queries may override the use of cached results by
+			specifying <code>OPTION NOCACHE</code> on the query.  0 or more fully qualified view or procedure names may be specified to exclude using their cached results.  
+			If no names are specified, cached results will not be used transitively.
+		</para>
+		<example>
+			<title>Full NOCACHE</title>
+			<programlisting>SELECT * from vg1, vg2, vg3 WHERE … OPTION NOCACHE</programlisting>
+			<para>No cached results will be used at all.</para>
+		</example>
+		<example>
+			<title>Specific NOCACHE</title>
+			<programlisting>SELECT * from vg1, vg2, vg3 WHERE … OPTION NOCACHE vg1, vg3</programlisting>
+			<para>Only the vg1 and vg3 caches will be skipped, vg2 or any cached results nested under vg1 and vg3 will be used.</para>
+		</example>
+		<para><code>OPTION NOCACHE</code> may be specified in procedure or view definitions.  In that way, transformations can
+			specify to always use real-time data obtained directly from sources.
+			</para>
+   	</section>
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml
===================================================================
--- trunk/documentation/client-developers-guide/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/client-developers-guide/pom.xml (from rev 2777, trunk/documentation/client-developers-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/client-developers-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/developer-guide/pom.xml
===================================================================
--- trunk/documentation/developer-guide/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/developer-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/developer-guide/pom.xml (from rev 2777, trunk/documentation/developer-guide/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/developer-guide/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/developer-guide/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/pom.xml
===================================================================
--- trunk/documentation/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/pom.xml (from rev 2777, trunk/documentation/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/quick-start-example/pom.xml
===================================================================
--- trunk/documentation/quick-start-example/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/quick-start-example/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/quick-start-example/pom.xml (from rev 2777, trunk/documentation/quick-start-example/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/quick-start-example/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/quick-start-example/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/reference/pom.xml
===================================================================
--- trunk/documentation/reference/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/documentation/reference/pom.xml (from rev 2777, trunk/documentation/reference/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,158 +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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="dataroles">
-    <title>Data Roles</title>
-    <para>Data roles, also called entitlements, are sets of permissions defined 
-    per VDB that dictate data access (create, read,  update, delete). Data roles use a fine-grained permission system that Teiid will enforce
-     at runtime and provide audit log entries for access violations (see that Admin and Developers Guide for more on Audit Logging).</para>
-    
-    <para>Prior to applying data roles, you should consider restricting source system access through the fundamental design of your VDB.  
-    Foremost, Teiid can only access source entries that are represented in imported metadata.  You should narrow imported metadata to only what
-     is necessary for use by your VDB.  When using Teiid Designer, you may then go further and modify the imported metadata at a granular
-      level to remove specific columns, mark tables as non-updatable, etc.</para>
-    
-    <para>If data roles is enabled and data roles are defined in a VDB, then access permissions will be enforced by the Teiid Server.  
-    The use of data roles may be disabled system wide via the
-    &jboss-beans; file, by setting the property <code>useDataRoles</code> to false in the configuration section of the <code>RuntimeEngineDeployer</code>.</para>
-    
-    <warning><para>Unlike previous versions of Teiid data roles will only be checked if present in a VDB.  
-    A VDB deployed without data roles is open for use by any authenticated user.</para></warning>
-
-    <section>
-    	<title>Permissions</title>
-
-		<para>CREATE, READ, UPDATE, DELETE (CRUD) permissions can be set for any resource path in a VDB.  
-		A resource path can be as specific as the fully qualified name of a column or as general a top level model (schema) name.
-		Permissions granted to a particular path apply to it and any resource paths that share the same partial name.  
-		For example, granting read to "model" will also grant read to "model.table", "model.table.column", etc.
-		Allowing or denying a particular action is determined by searching for permissions from the most to least specific resource paths.
-		The first permission found with a specific allow or deny will be used.  
-		Thus it is possible to set very general permissions at high-level resource path names and to override only as necessary at more specific resource paths. 
-		</para>
-
-		<para>Permission grants are only needed for resources that a role needs access to.
-			Permissions are also only applied to the columns/tables/procedures in the user query - not to every resource
-			accessed transitively through view and procedure definitions.
-			It is important therefore to ensure that permission grants are applied
-			consistently across models that access the same resources.
-		</para>
-		
-		<warning><para>Unlike previous versions of Teiid, non-visible models are accessible by user queries.  
-		To restrict user access at a model level, at least one data role should be created to enable data role checking.  
-		In turn that role can be mapped to any authenticated user and should not grant permissions to models that should be inaccessable.</para></warning>
-		
-		<para>Permissions are not applicable to the SYS and pg_catalog schemas.  These metadata reporting schemas are always accessible regardless of the user.
-		The SYSADMIN schema however may need permissions as applicable.</para>
-		    	
-   	    <orderedlist>
-	        <para>To process a <emphasis>SELECT</emphasis> statement or a stored procedure execution, the user account requires the following access rights:</para>
-	        <listitem> <para><emphasis>READ</emphasis> - on the Table(s) being accessed or the procedure being called.</para></listitem>
-	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced.</para></listitem>
-	    </orderedlist>   
-	    
-	    <orderedlist>
-	        <para>To process an <emphasis>INSERT</emphasis> statement, the user account requires the following access rights:</para>
-	        <listitem> <para><emphasis>CREATE</emphasis> - on the Table being inserted into.</para></listitem>
-	        <listitem> <para><emphasis>CREATE</emphasis> - on every column being inserted on that Table.</para></listitem>
-	    </orderedlist>   
-	    
-	    <orderedlist>
-	        <para>To process an <emphasis>UPDATE</emphasis> statement, the user account requires the following access rights:</para>
-	        <listitem> <para><emphasis>UPDATE</emphasis> - on the Table being updated.</para></listitem>
-	        <listitem> <para><emphasis>UPDATE</emphasis> - on every column being updated on that Table.</para></listitem>
-	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced in the criteria.</para></listitem>
-	    </orderedlist>    
-	    
-	    <orderedlist>
-	    	<para>To process a <emphasis>DELETE</emphasis> statement, the user account requires the following access rights:</para>
-	        <listitem> <para><emphasis>DELETE</emphasis> - on the Table being deleted.</para></listitem>
-	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced in the criteria.</para></listitem>
-	    </orderedlist> 
-	    
-	    <orderedlist>
-	    	<para>To process a <emphasis>EXEC</emphasis> statement, the user account requires the following access rights:</para>
-	        <listitem> <para><emphasis>READ</emphasis> - on the Procedure being executed.</para></listitem>
-	    </orderedlist>
-	       
-    </section>
-    
-    <section>
-    	<title>Role Mapping</title>
-    	<para>Each Teiid data role can be mapped to any number of container roles or any authenticated user.  
-    	You may control role membership through whatever system the Teiid security domain login modules are associated with. 
-    	The kit includes example files for use with the UsersRolesLoginModule - see teiid-security-roles.properties.</para>
-    	<para>It is possible for a user to have any number of container roles, which in turn imply a subset of Teiid data roles.  
-    	Each applicable Teiid data role contributes cumulatively to the permissions of the user. 
-    	No one role supercedes or negates the permissions of the other data roles.</para>
-    </section>
-
-	<section>
-		<title>XML Definition</title>
-	    <para>Data roles are defined inside the <code>vdb.xml</code> file (inside the .vdb Zip archive under META-INF/vdb.xml) if you used Designer.  
-	    The "vdb.xml" file is checked against the schema file <code>vdb-deployer.xsd</code>, which can be found in the kit under teiid-docs/schema.
-	    This example will show a sample "vdb.xml" file with few simple data roles.</para>
-    
-    <para>For example, if a VDB defines a table "TableA" in schema "modelName" with columns (column1, column2) - note that the column types do not matter.  And we wish to define three roles "RoleA", "RoleB", "RoleC" with following permissions:
-   <orderedlist>
-    <listitem><para>RoleA has permissions to read, write access to TableA, but can not delete.</para></listitem>
-    <listitem><para>RoleB has no permissions that allow access to TableA</para></listitem>
-    <listitem><para>RoleC has permissions that only allow read access to TableA.column1</para></listitem>
-   </orderedlist>
-	</para>
-    <example><title>vdb.xml defining RoleA, RoleB, and RoleC</title>
-   <programlisting><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
-<vdb name="sample" version="1">
-
-    <model name="modelName">
-        <source name="source-name" translator-name="oracle" connection-jndi-name="java:myDS" />
-    </model>
-
-    <data-role name="RoleA">
-        <description>Allow all, except Delete</description>
-
-        <permission>
-            <resource-name>modelName.TableA</resource-name>
-            <allow-create>true</allow-create>
-            <allow-read>true</allow-read>
-            <allow-update>true</allow-update>
-        </permission>
-
-        <mapped-role-name>role1</mapped-role-name>
-
-    </data-role>
-
-    <data-role name="RoleC">
-        <description>Allow read only</description>
-
-        <permission>
-            <resource-name>modelName.TableA</resource-name>
-            <allow-read>true</allow-read>
-        </permission>
-
-        <permission>
-            <resource-name>modelName.TableA.colum2</resource-name>
-            <allow-read>false</allow-read>
-        </permission>
-
-        <mapped-role-name>role2</mapped-role-name>
-    </data-role>
-</vdb>]]></programlisting>    
-</example>   
-   <para>The above XML defined two data roles, "RoleA" which allows everything except delete on the table, "RoleC" that 
-   allows only read operation on the table. Since Teiid uses deny by default, there is no explicit data-role entry needed for "RoleB".  Note that explicit column permissions are 
-   not needed for RoleA, since the parent resource path, modelName.TableA, permissions still apply.  RoleC however must explicitly disallow read to column2.</para>  
-   
-   <para>The "mapped-role-name" defines the container JAAS roles that are assigned the data role.  For assigning roles to your users in the JBoss AS, 
-   check out the instructions for the selected Login Module. Check the "Admin Guide" for configuring Login Modules.  You may also choose to allow any
-   authenticated user to have a data role by setting the any-authenticated attribute value to true on data-role element.</para> 
-   
-	</section>
-	<section>
-		<title>System Functions</title>
-		<para>The <code>hasRole</code> system function will return true if the current user has the given data role.  
-		The <code>hasRole</code> function can be used in procedure or view definitions to allow for a more dynamic application of security - which allows for things such as value masking or row level security.</para>
-	</section>
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml (from rev 2765, trunk/documentation/reference/src/main/docbook/en-US/content/dataroles.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,160 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="dataroles">
+    <title>Data Roles</title>
+    <para>Data roles, also called entitlements, are sets of permissions defined 
+    per VDB that dictate data access (create, read,  update, delete). Data roles use a fine-grained permission system that Teiid will enforce
+     at runtime and provide audit log entries for access violations (see that Admin and Developers Guide for more on Audit Logging).</para>
+    
+    <para>Prior to applying data roles, you should consider restricting source system access through the fundamental design of your VDB.  
+    Foremost, Teiid can only access source entries that are represented in imported metadata.  You should narrow imported metadata to only what
+     is necessary for use by your VDB.  When using Teiid Designer, you may then go further and modify the imported metadata at a granular
+      level to remove specific columns, mark tables as non-updatable, etc.</para>
+    
+    <para>If data roles is enabled and data roles are defined in a VDB, then access permissions will be enforced by the Teiid Server.  
+    The use of data roles may be disabled system wide via the
+    &jboss-beans; file, by setting the property <code>useDataRoles</code> to false in the configuration section of the <code>RuntimeEngineDeployer</code>.</para>
+    
+    <warning><para>Unlike previous versions of Teiid data roles will only be checked if present in a VDB.  
+    A VDB deployed without data roles is open for use by any authenticated user.</para></warning>
+
+    <section>
+    	<title>Permissions</title>
+
+		<para>CREATE, READ, UPDATE, DELETE (CRUD) permissions can be set for any resource path in a VDB.  
+		A resource path can be as specific as the fully qualified name of a column or as general a top level model (schema) name.
+		Permissions granted to a particular path apply to it and any resource paths that share the same partial name.  
+		For example, granting read to "model" will also grant read to "model.table", "model.table.column", etc.
+		Allowing or denying a particular action is determined by searching for permissions from the most to least specific resource paths.
+		The first permission found with a specific allow or deny will be used.  
+		Thus it is possible to set very general permissions at high-level resource path names and to override only as necessary at more specific resource paths. 
+		</para>
+
+		<para>Permission grants are only needed for resources that a role needs access to.
+			Permissions are also only applied to the columns/tables/procedures in the user query - not to every resource
+			accessed transitively through view and procedure definitions.
+			It is important therefore to ensure that permission grants are applied
+			consistently across models that access the same resources.
+		</para>
+		
+		<warning><para>Unlike previous versions of Teiid, non-visible models are accessible by user queries.  
+		To restrict user access at a model level, at least one data role should be created to enable data role checking.  
+		In turn that role can be mapped to any authenticated user and should not grant permissions to models that should be inaccessable.</para></warning>
+		
+		<para>Permissions are not applicable to the SYS and pg_catalog schemas.  These metadata reporting schemas are always accessible regardless of the user.
+		The SYSADMIN schema however may need permissions as applicable.</para>
+		    	
+   	    <orderedlist>
+	        <para>To process a <emphasis>SELECT</emphasis> statement or a stored procedure execution, the user account requires the following access rights:</para>
+	        <listitem> <para><emphasis>READ</emphasis> - on the Table(s) being accessed or the procedure being called.</para></listitem>
+	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced.</para></listitem>
+	    </orderedlist>   
+	    
+	    <orderedlist>
+	        <para>To process an <emphasis>INSERT</emphasis> statement, the user account requires the following access rights:</para>
+	        <listitem> <para><emphasis>CREATE</emphasis> - on the Table being inserted into.</para></listitem>
+	        <listitem> <para><emphasis>CREATE</emphasis> - on every column being inserted on that Table.</para></listitem>
+	    </orderedlist>   
+	    
+	    <orderedlist>
+	        <para>To process an <emphasis>UPDATE</emphasis> statement, the user account requires the following access rights:</para>
+	        <listitem> <para><emphasis>UPDATE</emphasis> - on the Table being updated.</para></listitem>
+	        <listitem> <para><emphasis>UPDATE</emphasis> - on every column being updated on that Table.</para></listitem>
+	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced in the criteria.</para></listitem>
+	    </orderedlist>    
+	    
+	    <orderedlist>
+	    	<para>To process a <emphasis>DELETE</emphasis> statement, the user account requires the following access rights:</para>
+	        <listitem> <para><emphasis>DELETE</emphasis> - on the Table being deleted.</para></listitem>
+	        <listitem> <para><emphasis>READ</emphasis> - on every column referenced in the criteria.</para></listitem>
+	    </orderedlist> 
+	    
+	    <orderedlist>
+	    	<para>To process a <emphasis>EXEC</emphasis> statement, the user account requires the following access rights:</para>
+	        <listitem> <para><emphasis>READ</emphasis> - on the Procedure being executed.</para></listitem>
+	    </orderedlist>
+	       
+    </section>
+    
+    <section>
+    	<title>Role Mapping</title>
+    	<para>Each Teiid data role can be mapped to any number of container roles or any authenticated user.  
+    	You may control role membership through whatever system the Teiid security domain login modules are associated with. 
+    	The kit includes example files for use with the UsersRolesLoginModule - see teiid-security-roles.properties.</para>
+    	<para>It is possible for a user to have any number of container roles, which in turn imply a subset of Teiid data roles.  
+    	Each applicable Teiid data role contributes cumulatively to the permissions of the user. 
+    	No one role supercedes or negates the permissions of the other data roles.</para>
+    </section>
+
+	<section>
+		<title>XML Definition</title>
+	    <para>Data roles are defined inside the <code>vdb.xml</code> file (inside the .vdb Zip archive under META-INF/vdb.xml) if you used Designer.  
+	    The "vdb.xml" file is checked against the schema file <code>vdb-deployer.xsd</code>, which can be found in the kit under teiid-docs/schema.
+	    This example will show a sample "vdb.xml" file with few simple data roles.</para>
+    
+    <para>For example, if a VDB defines a table "TableA" in schema "modelName" with columns (column1, column2) - note that the column types do not matter.  And we wish to define three roles "RoleA", "RoleB", "RoleC" with following permissions:
+   <orderedlist>
+    <listitem><para>RoleA has permissions to read, write access to TableA, but can not delete.</para></listitem>
+    <listitem><para>RoleB has no permissions that allow access to TableA</para></listitem>
+    <listitem><para>RoleC has permissions that only allow read access to TableA.column1</para></listitem>
+   </orderedlist>
+	</para>
+    <example><title>vdb.xml defining RoleA, RoleB, and RoleC</title>
+   <programlisting><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
+<vdb name="sample" version="1">
+
+    <model name="modelName">
+        <source name="source-name" translator-name="oracle" connection-jndi-name="java:myDS" />
+    </model>
+
+    <data-role name="RoleA">
+        <description>Allow all, except Delete</description>
+
+        <permission>
+            <resource-name>modelName.TableA</resource-name>
+            <allow-create>true</allow-create>
+            <allow-read>true</allow-read>
+            <allow-update>true</allow-update>
+        </permission>
+
+        <mapped-role-name>role1</mapped-role-name>
+
+    </data-role>
+
+    <data-role name="RoleC">
+        <description>Allow read only</description>
+
+        <permission>
+            <resource-name>modelName.TableA</resource-name>
+            <allow-read>true</allow-read>
+        </permission>
+
+        <permission>
+            <resource-name>modelName.TableA.colum2</resource-name>
+            <allow-read>false</allow-read>
+        </permission>
+
+        <mapped-role-name>role2</mapped-role-name>
+    </data-role>
+</vdb>]]></programlisting>    
+</example>   
+   <para>The above XML defined two data roles, "RoleA" which allows everything except delete on the table, "RoleC" that 
+   allows only read operation on the table. Since Teiid uses deny by default, there is no explicit data-role entry needed for "RoleB".  Note that explicit column permissions are 
+   not needed for RoleA, since the parent resource path, modelName.TableA, permissions still apply.  RoleC however must explicitly disallow read to column2.</para>  
+   
+   <para>The "mapped-role-name" defines the container JAAS roles that are assigned the data role.  For assigning roles to your users in the JBoss AS, 
+   check out the instructions for the selected Login Module. Check the "Admin Guide" for configuring Login Modules.  You may also choose to allow any
+   authenticated user to have a data role by setting the any-authenticated attribute value to true on data-role element.</para>
+   
+   <para>The "allow-create-temporary-tables" data-role boolean attribute is used to explicitly enable or disable temporary table usage for the role.  If it is left unspecified, then the value will be determined by the configuration setting allowCreateTemporaryTablesByDefault located in the &jboss-beans; file in the <code>RuntimeEngineDeployer</code> section.</para> 
+   
+	</section>
+	<section>
+		<title>System Functions</title>
+		<para>The <code>hasRole</code> system function will return true if the current user has the given data role.  
+		The <code>hasRole</code> function can be used in procedure or view definitions to allow for a more dynamic application of security - which allows for things such as value masking or row level security.</para>
+	</section>
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/procedures.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,646 +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="procedures">
-  <title>Procedures</title>
-  <section id="procedure_language">
-    <title>Procedure Language</title>
-    <para>
-      Teiid supports a procedural language for defining
-      <link linkend="virtual_procedures">virtual procedures</link>
-      . These are similar to stored procedures in relational database
-      management systems. You can use this language to define the
-      transformation logic for decomposing INSERT, UPDATE, and DELETE
-      commands against views; these are known as
-      <link linkend="update_procedures">update procedures</link>
-      .
-    </para>
-    <section>
-      <title>Command Statement</title>
-      <para>
-        A command statement executes a
-        <link linkend="sql_commands">SQL command</link>
-        , such as SELECT, INSERT, UPDATE, DELETE, or EXECUTE, against
-        one or more data sources.
-      </para>
-      <example>
-        <title>Example Command Statements</title>
-        <programlisting>SELECT * FROM MySchema.MyTable WHERE ColA &gt; 100;
-INSERT INTO MySchema.MyTable (ColA,ColB) VALUES (50, 'hi');</programlisting>
-        </example>
-      <para><link linkend="exec_command">EXECUTE</link> command statements may access IN/OUT, OUT, and RETURN parameters.  To access the return value the statement will have the form <code>var = EXEC proc...</code>.  
-      To access OUT or IN/OUT values named parameter syntax must be used.  For example, <code>EXEC proc(in_param=>'1', out_param=>var)</code> will assign the value of the out parameter to the variable var.
-      It is expected that the datatype of parameter will be implicitly convertable to the datatype of the variable.</para>
-    </section>
-    <section id="dynamic_sql">
-      <title>Dynamic SQL Command</title>
-      <para>Dynamic SQL allows for the execution of an arbitrary SQL command in a virtual procedure. Dynamic SQL is useful in situations where the exact command form is not known prior to execution.
-      </para>
-      <para>
-        Usage:
-        <synopsis>EXECUTE STRING &lt;expression&gt; <optional>AS &lt;variable&gt; &lt;type&gt; [, &lt;variable&gt; &lt;type&gt;]* [INTO &lt;variable&gt;]</optional> 
-[USING &lt;variable&gt;=&lt;expression&gt; [,&lt;variable&gt;=&lt;expression&gt;]*] [UPDATE &lt;literal&gt;]        
-      </synopsis>
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:</para>
-        <listitem>
-          <para>The "AS" clause is used to define the projected symbols names and types returned by the executed SQL string. The "AS" clause symbols will be matched positionally with the symbols returned by the executed SQL string. Non-convertible types or too few columns returned by the executed SQL string will result in an error.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The "INTO" clause will project the dynamic SQL into the specified temp table. With the "INTO" clause specified, the dynamic command will actually execute a statement that behaves like an INSERT with a QUERY EXPRESSION. If the dynamic SQL command creates a temporary table with the "INTO" clause, then the "AS" clause is required to define the table’s metadata.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The "USING" clause allows the dynamic SQL string to contain variable references that are bound at runtime to specified values. This allows for some independence of the SQL string from the surrounding procedure variable names and input names. In the dynamic command "USING" clause, each variable is specified by short name only. However in the dynamic SQL the "USING" variable must be fully qualified to "UVAR.". The "USING" clause is only for values that will be used in the dynamic SQL as legal expressions. It is not possible to use the "USING" clause to replace table names, keywords, etc. This makes using symbols equivalent in power to normal bind (?) expressions in prepared statements. The "USING" clause helps reduce the amount of string manipulation needed. If a reference is made to a USING symbol in the SQL string that is not bound to a value in the "USING" clause, an exception will occur.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The "UPDATE" clause is used to specify the <link linkend="updating_model_count">updating model count</link>. Accepted values are (0,1,*). 0 is the default value if the clause is not specified.
-          </para>
-        </listitem>
-      </itemizedlist>
-      <example>
-        <title>Example Dynamic SQL</title>
-        <programlisting>... 
-/* Typically complex criteria would be formed based upon inputs to the procedure. 
- In this simple example the criteria is references the using clause to isolate 
- the SQL string from referencing a value from the procedure directly */ 
-DECLARE string criteria = 'Customer.Accounts.Last = DVARS.LastName'; 
-/* Now we create the desired SQL string */ 
-DECLARE string sql_string = 'SELECT ID, First || ‘‘ ‘‘ || Last AS Name, Birthdate FROM Customer.Accounts WHERE ' || criteria; 
-/* The execution of the SQL string will create the #temp table with the columns (ID, Name, Birthdate). 
-  Note that we also have the USING clause to bind a value to LastName, which is referenced in the criteria. */ 
-EXECUTE STRING sql_string AS ID integer, Name string, Birthdate date INTO #temp USING LastName='some name'; 
-/* The temp table can now be used with the values from the Dynamic SQL */ 
-loop on (SELCT ID from #temp) as myCursor 
-...</programlisting>
-      </example>
-      <para>
-      Here is an example showing a more complex approach to building criteria for the dynamic SQL string. In short, the virtual procedure AccountAccess.GetAccounts has inputs ID, LastName, and bday. If a value is specified for ID it will be the only value used in the dynamic SQL criteria. Otherwise if a value is specified for LastName the procedure will detect if the value is a search string. If bday is specified in addition to LastName, it will be used to form compound criteria with LastName.
-      </para>
-      <example>
-        <title>Example Dynamic SQL with USING clause and dynamically built criteria string</title>
-        <programlisting>...
-DECLARE string crit = null; 
-IF (AccountAccess.GetAccounts.ID IS NOT NULL) 
- crit = ‘(Customer.Accounts.ID = DVARS.ID)’; 
-ELSE IF (AccountAccess.GetAccounts.LastName IS NOT NULL) 
-BEGIN 
- IF (AccountAccess.GetAccounts.LastName == ‘%’) 
-   ERROR "Last name cannot be %"; 
- ELSE IF (LOCATE(‘%’, AccountAccess.GetAccounts.LastName) &lt; 0) 
-   crit = ‘(Customer.Accounts.Last = DVARS.LastName)’; 
- ELSE 
-   crit = ‘(Customer.Accounts.Last LIKE DVARS.LastName)’; 
- IF (AccountAccess.GetAccounts.bday IS NOT NULL) 
-   crit = ‘(‘ || crit || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’; 
-END 
-ELSE 
- ERROR "ID or LastName must be specified."; 
-EXECUTE STRING ‘SELECT ID, First || ‘‘ ‘‘ || Last AS Name, Birthdate FROM Customer.Accounts WHERE ’ || crit USING ID=AccountAccess.GetAccounts.ID, LastName=AccountAccess.GetAccounts.LastName, BirthDay=AccountAccess.GetAccounts.Bday;
-...</programlisting>
-      </example>
-      <itemizedlist>
-        <para>Known Limitations and Work-Arounds
-        </para>
-        <listitem>
-          <para>The use of dynamic SQL command results in an assignment statement requires the use of a temp table.
-          </para>
-          <example>
-            <title>Example Assignment
-            </title>
-            <programlisting>EXECUTE STRING &lt;expression&gt; AS x string INTO #temp; 
-DECLARE string VARIABLES.RESULT = (SELECT x FROM #temp);</programlisting>
-          </example>
-        </listitem>
-        <listitem>
-          <para>The construction of appropriate criteria will be cumbersome if parts of the criteria are not present. For example if "criteria" were already NULL, then the following example results in "criteria" remaining NULL.
-          </para>
-          <example>
-            <title>Example Dangerous NULL handling
-            </title>
-            <programlisting>...
-criteria = ‘(‘ || criteria || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
-          </example>
-          <para>The preferred approach is for the user to ensure the criteria is not NULL prior its usage. If this is not possible, a good approach is to specify a default as shown in the following example.
-          </para>
-          <example>
-            <title>Example NULL handling
-            </title>
-            <programlisting>...
-criteria = ‘(‘ || nvl(criteria, ‘(1 = 1)’) || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
-          </example>
-        </listitem>
-        <listitem>
-          <para>If the dynamic SQL is an UPDATE, DELETE, or INSERT command, and the user needs to specify the "AS" clause (which would be the case if the number of rows effected needs to be retrieved).  The user will still need to provide a name and type for the return column if the into clause is specified.
-          </para>
-          <example>
-            <title>Example with AS and INTO clauses</title>
-            <programlisting>/* This name does not need to match the expected update command symbol "count". */
-EXECUTE STRING &lt;expression&gt; AS x integer INTO #temp;</programlisting>
-          </example>
-        </listitem>
-        <listitem>
-          <para>Unless used in other parts of the procedure, tables in the dynamic command will not be seen as sources in the Designer.
-          </para>
-        </listitem>
-        <listitem>
-          <para>When using the "AS" clause only the type information will be available to the Designer. ResultSet columns generated from the "AS" clause then will have a default set of properties for length, precision, etc.
-          </para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section>
-      <title>Declaration Statement</title>
-      <para>A declaration statement declares a variable and its type. After you declare a variable, you can use it in that block within the procedure and any sub-blocks. A variable is initialized to null by default, but can also be assigned the value of an expression as part of the declaration statement. 
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage" >DECLARE &lt;type&gt; [VARIABLES.]&lt;name&gt; [= &lt;expression&gt;];</synopsis>
-      </para>        
-      <itemizedlist>
-        <para>Example Syntax</para>
-        <listitem>
-          <para>declare integer x;
-          </para>
-        </listitem>
-        <listitem>
-          <para>declare string VARIABLES.myvar = 'value';
-          </para>
-        </listitem>        
-      </itemizedlist>
-      <itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>You cannot redeclare a variable with a duplicate name in a sub-block
-          </para>
-        </listitem>
-        <listitem>
-          <para>The VARIABLES group is always implied even if it is not specified.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The assignment value follows the same rules as for an Assignment Statement.
-          </para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section>
-      <title>Assignment Statement</title>
-      <para>An assignment statement assigns a value to a variable by either evaluating an expression.</para>
-      <para>
-        Usage:
-        <synopsis label="Usage" >&lt;variable reference&gt; = &lt;expression&gt;;</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Example Syntax</para>
-        <listitem>
-          <para>myString = 'Thank you';
-          </para>
-        </listitem>
-        <listitem>
-          <para>VARIABLES.x = (SELECT Column1 FROM MySchema.MyTable);
-          </para>
-        </listitem>
-      </itemizedlist>
-      <section>
-	      <title>Special Variables</title>
-	      <para><code>VARIABLES.ROWCOUNT</code> integer variable will contain the numbers of rows affected by the last insert/update/delete command statement executed.  Inserts that are processed by dynamic sql with an into clause will also update the ROWCOUNT.</para>
-	      <example>
-			<title>Sample Usage</title>
-			<programlisting language="SQL"><![CDATA[...
-UPDATE FOO SET X = 1 WHERE Y = 2;
-DECLARE INTEGER UPDATED = VARIABLES.ROWCOUNT;
-...]]></programlisting>
-		  </example>
-  	  </section>
-    </section>
-    <section>
-      <title>If Statement</title>
-      <para>An IF statement evaluates a condition and executes either
-        one of two blocks depending on the result. You can nest IF
-        statements to create complex branching logic. A dependent ELSE
-        statement will execute its block of code only if the IF statement
-        evaluates to false.</para>
-      <example>
-        <title>Example If Statement</title>
-        <programlisting>IF ( var1 = 'North America') 
-BEGIN 
-  ...statement... 
-END ELSE 
-BEGIN 
-  ...statement... 
-END</programlisting>
-      </example>
-      <note>
-        <para>
-          NULL values should be considered in the criteria of an IF statement.  IS NULL criteria can be used to detect the presense of a NULL value.  
-        </para>
-      </note>
-    </section>
-    <section>
-      <title>Loop Statement</title>
-      <para>A LOOP statement is an iterative control construct that is used to cursor through a result set.</para>
-      <para>
-        Usage:
-        <synopsis label="Usage" >LOOP ON &lt;select statement&gt; AS &lt;cursorname&gt; 
-BEGIN 
-  ...
-END</synopsis>
-      </para>
-    </section>
-    <section>
-      <title>While Statement</title>
-      <para>A WHILE statement is an iterative control construct that is used to execute a set of statements repeatedly whenever a specified condition is met.</para>
-      <para>
-        Usage:
-        <synopsis label="Usage" >WHILE &lt;criteria&gt; 
-BEGIN 
-  ...
-END</synopsis>
-      </para>
-    </section>
-    <section>
-      <title>Continue Statement</title>
-      <para>A CONTINUE statement is used inside a LOOP or WHILE construct to continue with the next loop by skipping over the rest of the statements in the loop. It must be used inside a LOOP or WHILE statement.</para>
-    </section>
-    <section>
-      <title>Break Statement</title>
-      <para>A BREAK statement is used inside a LOOP or WHILE construct to break from the loop. It must be used inside a LOOP or WHILE statement.</para>
-    </section>
-    <section>
-      <title>Error Statement</title>
-      <para>An ERROR statement declares that the procedure has entered an error state and should abort. This statement will also roll back the current transaction, if one exists. Any valid expression can be specified after the ERROR keyword.</para>
-      <example>
-        <title>Example Error Statement</title>
-        <programlisting>ERROR 'Invalid input value: ' || nvl(Acct.GetBalance.AcctID, 'null');</programlisting>
-      </example>
-    </section>
-  </section>
-  <section id="virtual_procedures">
-    <title>Virtual Procedures</title>
-    <para>Virtual procedures are defined using the Teiid
-      procedural language. A virtual procedure has zero or more input
-      parameters, and a result set return type. Virtual procedures
-      support the ability to execute queries and other SQL commands,
-      define temporary tables, add data to temporary tables, walk
-      through result sets, use loops, and use conditional logic.</para>
-    <section>
-      <title>Virtual Procedure Definition</title>
-      <para>
-        Usage:
-        <synopsis label="Usage" >CREATE VIRTUAL PROCEDURE 
-BEGIN 
-  ...
-END</synopsis>
-      </para>
-      <para>The CREATE VIRTUAL PROCEDURE line demarcates the beginning of
-        the procedure. The BEGIN and END keywords are used to denote block
-        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
-      </para>
-      <para>There is no explict cursoring or return statement, rather the last command statement executed in the procedure that returns a result set will be
-        returned as the result. The output of that statement must match the
-        expected result set and parameters of the procedure.</para>      
-    </section>
-    <section>
-      <title>Procedure Input Parameters</title>
-      <para>Virtual procedures can take zero or more input parameters. Each input has the following information that is used during runtime processing: </para>
-      <itemizedlist>
-        <listitem>
-          <para>Name - The name of the input parameter</para>
-        </listitem>
-        <listitem>
-          <para>Datatype - The design-time type of the input parameter</para>
-        </listitem>
-        <listitem>
-          <para>Default value - The default value if the input parameter is not specified</para>
-        </listitem>
-        <listitem>
-          <para>Nullable - NO_NULLS, NULLABLE, NULLABLE_UNKNOWN; parameter is optional if nullable, and is not required to be listed when using named parameter syntax</para>
-        </listitem>
-      </itemizedlist>
-      <para>You reference an input to a virtual procedure by using the fully-qualified name of the param (or less if unambiguous). For example, MySchema.MyProc.Param1.
-      </para>
-      <example>
-        <title>Example of Referencing an Input Parameter for 'GetBalance' Procedure</title>
-        <programlisting>
-CREATE VIRTUAL PROCEDURE 
-BEGIN 
-  SELECT Balance FROM MySchema.Accts WHERE MySchema.Accts.AccountID = MySchema.GetBalance.AcctID; 
-END</programlisting>
-      </example>
-    </section>
-    <section>
-      <title>Example Virtual Procedures</title>
-      <para>This example is a LOOP that walks through a cursored table and uses CONTINUE and BREAK.</para>
-      <example>
-        <title>Virtual Procedure Using LOOP, CONTINUE, BREAK
-        </title>
-        <programlisting>
-CREATE VIRTUAL PROCEDURE
-BEGIN
-  DECLARE double total;
-  DECLARE integer transactions;
-  LOOP ON (SELECT amt, type FROM CashTxnTable) AS txncursor
-  BEGIN
-    IF(txncursor.type &lt;&gt; 'Sale')
-    BEGIN
-      CONTINUE;
-    END ELSE 
-    BEGIN
-      total = (total + txncursor.amt);
-      transactions = (transactions + 1);
-      IF(transactions = 100)
-      BEGIN
-        BREAK;
-      END
-    END
-  END
-  SELECT total, (total / transactions) AS avg_transaction;
-END
-        </programlisting>
-      </example>
-      <para>This example is uses conditional logic to determine which of two SELECT statements to execute.</para>
-      <example>
-        <title>Virtual Procedure with Conditional SELECT
-        </title>
-        <programlisting>
-CREATE VIRTUAL PROCEDURE 
-BEGIN 
-  DECLARE string VARIABLES.SORTDIRECTION; 
-  VARIABLES.SORTDIRECTION = PartsVirtual.OrderedQtyProc.SORTMODE; 
-  IF ( ucase(VARIABLES.SORTDIRECTION) = 'ASC' ) 
-  BEGIN 
-    SELECT * FROM PartsVirtual.SupplierInfo WHERE QUANTITY &gt; PartsVirtual.OrderedQtyProc.QTYIN ORDER BY PartsVirtual.SupplierInfo.PART_ID; 
-  END ELSE 
-  BEGIN 
-    SELECT * FROM PartsVirtual.SupplierInfo WHERE QUANTITY > PartsVirtual.OrderedQtyProc.QTYIN ORDER BY PartsVirtual.SupplierInfo.PART_ID DESC;
-  END
-END 
-        </programlisting>
-      </example>
-    </section>
-    <section>
-      <title>Executing Virtual Procedures</title>
-      <para>You execute procedures using the SQL <link linkend="exec_command">EXECUTE</link> command. If
-        the procedure has defined inputs, you specify those in a
-        sequential list, or using "name=value" syntax. You must use the
-        name of the input parameter, scoped by the full procedure name if
-        the parameter name is ambiguous in the context of other columns
-        or variables in the procedure.</para>
-      <para> A virtual procedure call will return a result set just like any
-        SELECT, so you can use this in many places you can use a SELECT.
-        Typically you'll use the following syntax:</para>
-      <programlisting>SELECT * FROM (EXEC ...) AS x</programlisting>  
-    </section>
-    <section>
-    	<title>Limitations</title>
-    	<para>Teiid virtual procedures can only be defined in Teiid Designer.  They also cannot use IN/OUT, OUT, or RETURN paramters and may only return 1 result set.</para>
-    </section>
-  </section>  
-  <section id="update_procedures">
-    <title>Update Procedures</title>
-    <para>
-      Views are abstractions above physical sources. They typically
-      union or join information from multiple tables, often from multiple
-      data sources or other views. Teiid can perform update operations
-      against views. Update commands - INSERT, UPDATE, or DELETE -
-      against a view require logic to define how the tables and
-      views integrated by the view are affected by each type of
-      command. This transformation logic is invoked when an update command
-      is issued against a view. Update procedures define the logic
-      for how a user's update command against a view should be
-      decomposed into the individual commands to be executed against the
-      underlying physical sources. Similar to
-      <link linkend="virtual_procedures">virtual procedures</link>
-      , update procedures have the ability to execute queries or other
-      commands, define temporary tables, add data to temporary tables, walk
-      through result sets, use loops, and use conditional logic.
-    </para>
-    <section>
-      <title>Update Procedure Definition</title>
-      <para>
-        Usage:
-        <synopsis label="Usage" >CREATE PROCEDURE 
-BEGIN 
-  ...
-END</synopsis>
-      </para>
-      <para>The CREATE PROCEDURE line demarcates the beginning of
-        the procedure. The BEGIN and END keywords are used to denote block
-        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
-      </para>
-    </section>
-    <section>
-      <title>Special Variables</title>
-      <para>You can use a number of special variables when defining your update procedure.</para>
-      <section id="input_variables">
-        <title>INPUT Variables</title>
-        <para>Every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named INPUTS.&lt;column_name&gt;</para>
-        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to the values in the INSERT VALUES clause or the UPDATE SET clause respectively.</para>
-        <para>In an UPDATE procedure, the default value of these variables, if they are not set by the command, is null. In an INSERT procedure, the default value of these variables is the default value of the virtual table attributes, based on their defined types.  See <link linkend="changing_variables">CHANGING Variables</link> for distinguishing defaults from passed values.</para>
-      	<warning>
-      		<para>In prior release of Teiid INPUT was also accepted as the quailifer for an input variable.  As of Teidd 7, INPUT is a reserved word, so INPUTS is the preferred qualifier.</para>
-      	</warning>
-      </section>
-      <section id="changing_variables">
-        <title>CHANGING Variables</title>
-        <para>Similar to INPUT Variables, every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named CHANGING.&lt;column_name&gt;</para>
-        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to <literal>true</literal> or <literal>false</literal> depending on whether the INPUT variable was set by the command.</para>
-        <para>For example, for a view with columns A, B, C:</para>
-        <informaltable>
-          <tgroup cols="2">
-            <thead>
-              <row>
-                <entry>If User Executes...</entry>
-                <entry>Then...</entry>
-              </row>
-            </thead>
-            <tbody>
-              <row>
-                <entry><code>INSERT INTO VT (A, B) VALUES (0, 1)</code></entry>
-                <entry>CHANGING.A = true, CHANGING.B = true, CHANGING.C = false</entry>
-              </row>
-              <row>
-                <entry><code>UPDATE VT SET C = 2</code></entry>
-                <entry>CHANGING.A = false, CHANGING.B = false, CHANGING.C = true</entry>
-              </row>
-            </tbody>
-          </tgroup>
-        </informaltable>
-      </section>
-      <section id="rowsupdated_variable">
-        <title>ROWS_UPDATED Variable</title>
-        <para> Teiid returns the value of the integer VARIABLES.ROWS_UPDATED variable as a response to an update command executed against
-          the view. Your procedure must set the value that returns
-          when an application executes an update command against the view, 
-          which triggers invocation of the update procedure. For
-          example, if an UPDATE command is issued that affects 5 records, the
-          ROWS_UPDATED should be set appropriately so that the user will
-          receive '5' for the count of records affected.</para>
-          <example>
-			<title>Sample Usage</title>
-			<programlisting language="SQL"><![CDATA[...
-UPDATE FOO SET X = 1 WHERE TRANSLATE CRITERIA;
-VARIABLES.ROWS_UPDATED = VARIABLES.ROWCOUNT;
-...]]></programlisting>
-		  </example>
-      </section>
-    </section>  
-    <section>
-      <title>Update Procedure Command Criteria</title>
-      <para> You can use a number of special SQL clauses when defining
-        UPDATE or DELETE procedures. These make it easier to do variable
-        substitutions in WHERE clauses or to check on the change state of
-        variables without using a lot of conditional logic.</para>
-        <section>
-          <title>HAS CRITERIA</title>
-          <para>You can use the HAS CRITERIA clause to check whether the user’s command has a particular kind of criteria on a particular set of attributes. This clause evaluates to either true or false. You can use it anywhere you can use a criteria within a procedure.</para>
-          <para>
-            Usage:
-            <synopsis>HAS [criteria operator] CRITERIA [ON (column list)]</synopsis>
-          </para>
-          <itemizedlist>
-            <para>Syntax Rules</para>
-            <listitem>
-              <para>The criteria operator, can be one of =, &lt;, &gt;, &lt;=, &gt;=, &lt;&gt;, LIKE, IS NULL, or IN.
-              </para>
-            </listitem>
-            <listitem>
-              <para>If the ON clause is present, HAS CRITERIA will return true only if criteria was present on all of the specified columns.
-              </para>
-            </listitem>
-            <listitem>
-              <para>The columns in a HAS CRITERIA ON clause always refer to view columns.
-              </para>
-            </listitem>
-          </itemizedlist>
-          <para>Some samples of the HAS CRITERIA clause:</para>
-          <informaltable>
-            <tgroup cols="2">
-              <thead>
-                <row>
-                  <entry>SQL</entry>
-                  <entry>Result</entry>
-                </row>
-              </thead>
-              <tbody>
-                <row>
-                  <entry><code>HAS CRITERIA</code></entry>
-                  <entry>Checks simply whether there was any criteria at all.</entry>
-                </row>
-                <row>
-                  <entry><code>HAS CRITERIA ON (column1, column2)</code></entry>
-                  <entry>Checks whether the criteria uses column1 and column2.</entry>
-                </row>
-                <row>
-                  <entry><code>HAS = CRITERIA ON (column1)</code></entry>
-                  <entry>Checks whether the criteria has a comparison criteria with = operator.</entry>
-                </row>
-                <row>
-                  <entry><code>HAS LIKE CRITERIA</code></entry>
-                  <entry>Checks whether the criteria has a match criteria using LIKE.</entry>
-                </row>
-              </tbody>
-            </tgroup>
-          </informaltable>
-          <para>The HAS CRITERIA predicate is most commonly used in
-            an IF clause, to determine if the user issued a particular form of
-            command and to respond appropriately.</para>
-        </section>
-        <section>
-          <title>TRANSLATE CRITERIA</title>
-          <warning><para>TRANSLATE CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.</para></warning>
-          <para>You can use the TRANSLATE CRITERIA clause to convert the criteria from the user application’s SQL command into the form required to interact with the target source or view tables. The TRANSLATE CRITERIA statement uses the SELECT transformation to infer the column mapping. This clause evaluates to a translated criteria that is evaluated in the context of a command.
-          You can use these mappings either to replace the default mappings generated from the SELECT transformation or to specify a reverse expression when a virtual column is defined by an expression.</para>
-          <para>
-            Usage:
-            <synopsis>TRANSLATE [criteria operator] CRITERIA [ON (column list)] [WITH (mapping list)]</synopsis>
-          </para>
-          <para>If there is no user criteria, then the translated criteria is always treated as TRUE.</para>
-          <itemizedlist>
-            <para>Syntax Rules</para>
-            <listitem>
-              <para>The criteria operator, can be one of =, &lt;, &gt;, &lt;=, &gt;=, &lt;&gt;, LIKE, IS NULL, or IN.
-              </para>
-            </listitem>
-            <listitem>
-              <para>If the ON clause is present, TRANSLATE CRITERIA will only form criteria using the specified columns.
-              </para>
-            </listitem>
-            <listitem>
-              <para>The columns in a TRANSLATE CRITERIA ON clause always refer to view columns.
-              </para>
-            </listitem>
-            <listitem>
-              <para>The WITH clause always has items with form &lt;elem&gt; = &lt;expression&gt; where the left hand side must refer to a view column.
-              </para>
-            </listitem>
-            <listitem>
-              <para>If the WITH clause or a specific mapping is not specified, then a mapping is created based on the SELECT clause of the SELECT transformation (the view column gets mapped to expression in SELECT clause at same  position). 
-              </para>
-            </listitem>
-          </itemizedlist>
-          <para>Some samples of TRANSLATE CRITERIA:</para>
-          <informaltable>
-            <tgroup cols="2">
-              <colspec colwidth="1*"/>
-              <colspec colwidth="1*"/>
-              <thead>
-                <row>
-                  <entry>SQL</entry>
-                  <entry>Result</entry>
-                </row>
-              </thead>
-              <tbody>
-                <row>
-                  <entry><code>TRANSLATE CRITERIA</code></entry>
-                  <entry>Translates any user criteria using the default mappings.</entry>
-                </row>
-                <row>
-                  <entry>TRANSLATE CRITERIA WITH (column1 = 'A', column2 = INPUTS.column2 + 2)</entry>
-                  <entry>Translates any criteria with some additional mappings: column1 is always mapped to 'A' and column2 is mapped to the incoming column2 value + 2.</entry>
-                </row>
-                <row>
-                  <entry><code>TRANSLATE = CRITERIA ON (column1)</code></entry>
-                  <entry>Translates only criteria that have = comparison operator and involve column1.</entry>
-                </row>
-              </tbody>
-            </tgroup>
-          </informaltable>
-          <note><para>If a specific predicate type or column set is specified by TRANSALATE CRITERIA, but the user criteria has predicates that do not match, then an exception will be thrown.</para></note>
-        </section>      
-    </section>
-    <section>
-      <title>Update Procedure Processing</title>
-      <orderedlist>
-        <listitem>
-          <para>The user application submits the SQL command through one of SOAP, JDBC, or ODBC.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The view this SQL command is executed against is detected.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The correct procedure is chosen depending upon whether the command is an INSERT, UPDATE, or DELETE.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The procedure is executed. The procedure itself can contain SQL commands of its own which can be of different types than the command submitted by the user application that invoked the procedure.
-          </para>
-        </listitem>
-        <listitem>
-          <para>Commands, as described in the procedure, as issued to the individual physical data sources or other views.
-          </para>
-        </listitem>
-        <listitem>
-          <para>A value representing the number of rows changed is returned to the calling application.
-          </para>
-        </listitem>
-      </orderedlist>
-    </section>  
-  </section>
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml (from rev 2774, trunk/documentation/reference/src/main/docbook/en-US/content/procedures.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/procedures.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,736 @@
+<?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="procedures">
+  <title>Procedures</title>
+  <section id="procedure_language">
+    <title>Procedure Language</title>
+    <para>
+      Teiid supports a procedural language for defining
+      <link linkend="virtual_procedures">virtual procedures</link>
+      . These are similar to stored procedures in relational database
+      management systems. You can use this language to define the
+      transformation logic for decomposing INSERT, UPDATE, and DELETE
+      commands against views; these are known as
+      <link linkend="update_procedures">update procedures</link>
+      .
+    </para>
+    <section>
+      <title>Command Statement</title>
+      <para>
+        A command statement executes a
+        <link linkend="sql_commands">SQL command</link>
+        , such as SELECT, INSERT, UPDATE, DELETE, or EXECUTE, against
+        one or more data sources.
+      </para>
+      <example>
+        <title>Example Command Statements</title>
+        <programlisting>SELECT * FROM MySchema.MyTable WHERE ColA &gt; 100;
+INSERT INTO MySchema.MyTable (ColA,ColB) VALUES (50, 'hi');</programlisting>
+        </example>
+      <para><link linkend="exec_command">EXECUTE</link> command statements may access IN/OUT, OUT, and RETURN parameters.  To access the return value the statement will have the form <code>var = EXEC proc...</code>.  
+      To access OUT or IN/OUT values named parameter syntax must be used.  For example, <code>EXEC proc(in_param=>'1', out_param=>var)</code> will assign the value of the out parameter to the variable var.
+      It is expected that the datatype of parameter will be implicitly convertable to the datatype of the variable.</para>
+    </section>
+    <section id="dynamic_sql">
+      <title>Dynamic SQL Command</title>
+      <para>Dynamic SQL allows for the execution of an arbitrary SQL command in a virtual procedure. Dynamic SQL is useful in situations where the exact command form is not known prior to execution.
+      </para>
+      <para>
+        Usage:
+        <synopsis>EXECUTE STRING &lt;expression&gt; <optional>AS &lt;variable&gt; &lt;type&gt; [, &lt;variable&gt; &lt;type&gt;]* [INTO &lt;variable&gt;]</optional> 
+[USING &lt;variable&gt;=&lt;expression&gt; [,&lt;variable&gt;=&lt;expression&gt;]*] [UPDATE &lt;literal&gt;]        
+      </synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:</para>
+        <listitem>
+          <para>The "AS" clause is used to define the projected symbols names and types returned by the executed SQL string. The "AS" clause symbols will be matched positionally with the symbols returned by the executed SQL string. Non-convertible types or too few columns returned by the executed SQL string will result in an error.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The "INTO" clause will project the dynamic SQL into the specified temp table. With the "INTO" clause specified, the dynamic command will actually execute a statement that behaves like an INSERT with a QUERY EXPRESSION. If the dynamic SQL command creates a temporary table with the "INTO" clause, then the "AS" clause is required to define the table’s metadata.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The "USING" clause allows the dynamic SQL string to contain variable references that are bound at runtime to specified values. This allows for some independence of the SQL string from the surrounding procedure variable names and input names. In the dynamic command "USING" clause, each variable is specified by short name only. However in the dynamic SQL the "USING" variable must be fully qualified to "UVAR.". The "USING" clause is only for values that will be used in the dynamic SQL as legal expressions. It is not possible to use the "USING" clause to replace table names, keywords, etc. This makes using symbols equivalent in power to normal bind (?) expressions in prepared statements. The "USING" clause helps reduce the amount of string manipulation needed. If a reference is made to a USING symbol in the SQL string that is not bound to a value in the "USING" clause, an exception will occur.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The "UPDATE" clause is used to specify the <link linkend="updating_model_count">updating model count</link>. Accepted values are (0,1,*). 0 is the default value if the clause is not specified.
+          </para>
+        </listitem>
+      </itemizedlist>
+      <example>
+        <title>Example Dynamic SQL</title>
+        <programlisting>... 
+/* Typically complex criteria would be formed based upon inputs to the procedure. 
+ In this simple example the criteria is references the using clause to isolate 
+ the SQL string from referencing a value from the procedure directly */ 
+DECLARE string criteria = 'Customer.Accounts.Last = DVARS.LastName'; 
+/* Now we create the desired SQL string */ 
+DECLARE string sql_string = 'SELECT ID, First || ‘‘ ‘‘ || Last AS Name, Birthdate FROM Customer.Accounts WHERE ' || criteria; 
+/* The execution of the SQL string will create the #temp table with the columns (ID, Name, Birthdate). 
+  Note that we also have the USING clause to bind a value to LastName, which is referenced in the criteria. */ 
+EXECUTE STRING sql_string AS ID integer, Name string, Birthdate date INTO #temp USING LastName='some name'; 
+/* The temp table can now be used with the values from the Dynamic SQL */ 
+loop on (SELCT ID from #temp) as myCursor 
+...</programlisting>
+      </example>
+      <para>
+      Here is an example showing a more complex approach to building criteria for the dynamic SQL string. In short, the virtual procedure AccountAccess.GetAccounts has inputs ID, LastName, and bday. If a value is specified for ID it will be the only value used in the dynamic SQL criteria. Otherwise if a value is specified for LastName the procedure will detect if the value is a search string. If bday is specified in addition to LastName, it will be used to form compound criteria with LastName.
+      </para>
+      <example>
+        <title>Example Dynamic SQL with USING clause and dynamically built criteria string</title>
+        <programlisting>...
+DECLARE string crit = null; 
+IF (AccountAccess.GetAccounts.ID IS NOT NULL) 
+ crit = ‘(Customer.Accounts.ID = DVARS.ID)’; 
+ELSE IF (AccountAccess.GetAccounts.LastName IS NOT NULL) 
+BEGIN 
+ IF (AccountAccess.GetAccounts.LastName == ‘%’) 
+   ERROR "Last name cannot be %"; 
+ ELSE IF (LOCATE(‘%’, AccountAccess.GetAccounts.LastName) &lt; 0) 
+   crit = ‘(Customer.Accounts.Last = DVARS.LastName)’; 
+ ELSE 
+   crit = ‘(Customer.Accounts.Last LIKE DVARS.LastName)’; 
+ IF (AccountAccess.GetAccounts.bday IS NOT NULL) 
+   crit = ‘(‘ || crit || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’; 
+END 
+ELSE 
+ ERROR "ID or LastName must be specified."; 
+EXECUTE STRING ‘SELECT ID, First || ‘‘ ‘‘ || Last AS Name, Birthdate FROM Customer.Accounts WHERE ’ || crit USING ID=AccountAccess.GetAccounts.ID, LastName=AccountAccess.GetAccounts.LastName, BirthDay=AccountAccess.GetAccounts.Bday;
+...</programlisting>
+      </example>
+      <itemizedlist>
+        <para>Known Limitations and Work-Arounds
+        </para>
+        <listitem>
+          <para>The use of dynamic SQL command results in an assignment statement requires the use of a temp table.
+          </para>
+          <example>
+            <title>Example Assignment
+            </title>
+            <programlisting>EXECUTE STRING &lt;expression&gt; AS x string INTO #temp; 
+DECLARE string VARIABLES.RESULT = (SELECT x FROM #temp);</programlisting>
+          </example>
+        </listitem>
+        <listitem>
+          <para>The construction of appropriate criteria will be cumbersome if parts of the criteria are not present. For example if "criteria" were already NULL, then the following example results in "criteria" remaining NULL.
+          </para>
+          <example>
+            <title>Example Dangerous NULL handling
+            </title>
+            <programlisting>...
+criteria = ‘(‘ || criteria || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
+          </example>
+          <para>The preferred approach is for the user to ensure the criteria is not NULL prior its usage. If this is not possible, a good approach is to specify a default as shown in the following example.
+          </para>
+          <example>
+            <title>Example NULL handling
+            </title>
+            <programlisting>...
+criteria = ‘(‘ || nvl(criteria, ‘(1 = 1)’) || ‘ and (Customer.Accounts.Birthdate = DVARS.BirthDay))’;</programlisting>
+          </example>
+        </listitem>
+        <listitem>
+          <para>If the dynamic SQL is an UPDATE, DELETE, or INSERT command, and the user needs to specify the "AS" clause (which would be the case if the number of rows effected needs to be retrieved).  The user will still need to provide a name and type for the return column if the into clause is specified.
+          </para>
+          <example>
+            <title>Example with AS and INTO clauses</title>
+            <programlisting>/* This name does not need to match the expected update command symbol "count". */
+EXECUTE STRING &lt;expression&gt; AS x integer INTO #temp;</programlisting>
+          </example>
+        </listitem>
+        <listitem>
+          <para>Unless used in other parts of the procedure, tables in the dynamic command will not be seen as sources in the Designer.
+          </para>
+        </listitem>
+        <listitem>
+          <para>When using the "AS" clause only the type information will be available to the Designer. ResultSet columns generated from the "AS" clause then will have a default set of properties for length, precision, etc.
+          </para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section>
+      <title>Declaration Statement</title>
+      <para>A declaration statement declares a variable and its type. After you declare a variable, you can use it in that block within the procedure and any sub-blocks. A variable is initialized to null by default, but can also be assigned the value of an expression as part of the declaration statement. 
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >DECLARE &lt;type&gt; [VARIABLES.]&lt;name&gt; [= &lt;expression&gt;];</synopsis>
+      </para>        
+      <itemizedlist>
+        <para>Example Syntax</para>
+        <listitem>
+          <para>declare integer x;
+          </para>
+        </listitem>
+        <listitem>
+          <para>declare string VARIABLES.myvar = 'value';
+          </para>
+        </listitem>        
+      </itemizedlist>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>You cannot redeclare a variable with a duplicate name in a sub-block
+          </para>
+        </listitem>
+        <listitem>
+          <para>The VARIABLES group is always implied even if it is not specified.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The assignment value follows the same rules as for an Assignment Statement.
+          </para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section>
+      <title>Assignment Statement</title>
+      <para>An assignment statement assigns a value to a variable by either evaluating an expression.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >&lt;variable reference&gt; = &lt;expression&gt;;</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Example Syntax</para>
+        <listitem>
+          <para>myString = 'Thank you';
+          </para>
+        </listitem>
+        <listitem>
+          <para>VARIABLES.x = (SELECT Column1 FROM MySchema.MyTable);
+          </para>
+        </listitem>
+      </itemizedlist>
+      <section>
+	      <title>Special Variables</title>
+	      <para><code>VARIABLES.ROWCOUNT</code> integer variable will contain the numbers of rows affected by the last insert/update/delete command statement executed.  Inserts that are processed by dynamic sql with an into clause will also update the ROWCOUNT.</para>
+	      <example>
+			<title>Sample Usage</title>
+			<programlisting language="SQL"><![CDATA[...
+UPDATE FOO SET X = 1 WHERE Y = 2;
+DECLARE INTEGER UPDATED = VARIABLES.ROWCOUNT;
+...]]></programlisting>
+		  </example>
+  	  </section>
+    </section>
+    <section>
+      <title>If Statement</title>
+      <para>An IF statement evaluates a condition and executes either
+        one of two blocks depending on the result. You can nest IF
+        statements to create complex branching logic. A dependent ELSE
+        statement will execute its block of code only if the IF statement
+        evaluates to false.</para>
+      <example>
+        <title>Example If Statement</title>
+        <programlisting>IF ( var1 = 'North America') 
+BEGIN 
+  ...statement... 
+END ELSE 
+BEGIN 
+  ...statement... 
+END</programlisting>
+      </example>
+      <note>
+        <para>
+          NULL values should be considered in the criteria of an IF statement.  IS NULL criteria can be used to detect the presense of a NULL value.  
+        </para>
+      </note>
+    </section>
+    <section>
+      <title>Loop Statement</title>
+      <para>A LOOP statement is an iterative control construct that is used to cursor through a result set.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >LOOP ON &lt;select statement&gt; AS &lt;cursorname&gt; 
+BEGIN 
+  ...
+END</synopsis>
+      </para>
+    </section>
+    <section>
+      <title>While Statement</title>
+      <para>A WHILE statement is an iterative control construct that is used to execute a set of statements repeatedly whenever a specified condition is met.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >WHILE &lt;criteria&gt; 
+BEGIN 
+  ...
+END</synopsis>
+      </para>
+    </section>
+    <section>
+      <title>Continue Statement</title>
+      <para>A CONTINUE statement is used inside a LOOP or WHILE construct to continue with the next loop by skipping over the rest of the statements in the loop. It must be used inside a LOOP or WHILE statement.</para>
+    </section>
+    <section>
+      <title>Break Statement</title>
+      <para>A BREAK statement is used inside a LOOP or WHILE construct to break from the loop. It must be used inside a LOOP or WHILE statement.</para>
+    </section>
+    <section>
+      <title>Error Statement</title>
+      <para>An ERROR statement declares that the procedure has entered an error state and should abort. This statement will also roll back the current transaction, if one exists. Any valid expression can be specified after the ERROR keyword.</para>
+      <example>
+        <title>Example Error Statement</title>
+        <programlisting>ERROR 'Invalid input value: ' || nvl(Acct.GetBalance.AcctID, 'null');</programlisting>
+      </example>
+    </section>
+  </section>
+  <section id="virtual_procedures">
+    <title>Virtual Procedures</title>
+    <para>Virtual procedures are defined using the Teiid
+      procedural language. A virtual procedure has zero or more input
+      parameters, and a result set return type. Virtual procedures
+      support the ability to execute queries and other SQL commands,
+      define temporary tables, add data to temporary tables, walk
+      through result sets, use loops, and use conditional logic.</para>
+    <section>
+      <title>Virtual Procedure Definition</title>
+      <para>
+        Usage:
+        <synopsis label="Usage" >CREATE VIRTUAL PROCEDURE 
+BEGIN 
+  ...
+END</synopsis>
+      </para>
+      <para>The CREATE VIRTUAL PROCEDURE line demarcates the beginning of
+        the procedure. The BEGIN and END keywords are used to denote block
+        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
+      </para>
+      <para>There is no explict cursoring or return statement, rather the last command statement executed in the procedure that returns a result set will be
+        returned as the result. The output of that statement must match the
+        expected result set and parameters of the procedure.</para>      
+    </section>
+    <section>
+      <title>Procedure Input Parameters</title>
+      <para>Virtual procedures can take zero or more input parameters. Each input has the following information that is used during runtime processing: </para>
+      <itemizedlist>
+        <listitem>
+          <para>Name - The name of the input parameter</para>
+        </listitem>
+        <listitem>
+          <para>Datatype - The design-time type of the input parameter</para>
+        </listitem>
+        <listitem>
+          <para>Default value - The default value if the input parameter is not specified</para>
+        </listitem>
+        <listitem>
+          <para>Nullable - NO_NULLS, NULLABLE, NULLABLE_UNKNOWN; parameter is optional if nullable, and is not required to be listed when using named parameter syntax</para>
+        </listitem>
+      </itemizedlist>
+      <para>You reference an input to a virtual procedure by using the fully-qualified name of the param (or less if unambiguous). For example, MySchema.MyProc.Param1.
+      </para>
+      <example>
+        <title>Example of Referencing an Input Parameter for 'GetBalance' Procedure</title>
+        <programlisting>
+CREATE VIRTUAL PROCEDURE 
+BEGIN 
+  SELECT Balance FROM MySchema.Accts WHERE MySchema.Accts.AccountID = MySchema.GetBalance.AcctID; 
+END</programlisting>
+      </example>
+    </section>
+    <section>
+      <title>Example Virtual Procedures</title>
+      <para>This example is a LOOP that walks through a cursored table and uses CONTINUE and BREAK.</para>
+      <example>
+        <title>Virtual Procedure Using LOOP, CONTINUE, BREAK
+        </title>
+        <programlisting>
+CREATE VIRTUAL PROCEDURE
+BEGIN
+  DECLARE double total;
+  DECLARE integer transactions;
+  LOOP ON (SELECT amt, type FROM CashTxnTable) AS txncursor
+  BEGIN
+    IF(txncursor.type &lt;&gt; 'Sale')
+    BEGIN
+      CONTINUE;
+    END ELSE 
+    BEGIN
+      total = (total + txncursor.amt);
+      transactions = (transactions + 1);
+      IF(transactions = 100)
+      BEGIN
+        BREAK;
+      END
+    END
+  END
+  SELECT total, (total / transactions) AS avg_transaction;
+END
+        </programlisting>
+      </example>
+      <para>This example is uses conditional logic to determine which of two SELECT statements to execute.</para>
+      <example>
+        <title>Virtual Procedure with Conditional SELECT
+        </title>
+        <programlisting>
+CREATE VIRTUAL PROCEDURE 
+BEGIN 
+  DECLARE string VARIABLES.SORTDIRECTION; 
+  VARIABLES.SORTDIRECTION = PartsVirtual.OrderedQtyProc.SORTMODE; 
+  IF ( ucase(VARIABLES.SORTDIRECTION) = 'ASC' ) 
+  BEGIN 
+    SELECT * FROM PartsVirtual.SupplierInfo WHERE QUANTITY &gt; PartsVirtual.OrderedQtyProc.QTYIN ORDER BY PartsVirtual.SupplierInfo.PART_ID; 
+  END ELSE 
+  BEGIN 
+    SELECT * FROM PartsVirtual.SupplierInfo WHERE QUANTITY > PartsVirtual.OrderedQtyProc.QTYIN ORDER BY PartsVirtual.SupplierInfo.PART_ID DESC;
+  END
+END 
+        </programlisting>
+      </example>
+    </section>
+    <section>
+      <title>Executing Virtual Procedures</title>
+      <para>You execute procedures using the SQL <link linkend="exec_command">EXECUTE</link> command. If
+        the procedure has defined inputs, you specify those in a
+        sequential list, or using "name=value" syntax. You must use the
+        name of the input parameter, scoped by the full procedure name if
+        the parameter name is ambiguous in the context of other columns
+        or variables in the procedure.</para>
+      <para> A virtual procedure call will return a result set just like any
+        SELECT, so you can use this in many places you can use a SELECT.
+        Typically you'll use the following syntax:</para>
+      <programlisting>SELECT * FROM (EXEC ...) AS x</programlisting>  
+    </section>
+    <section>
+    	<title>Limitations</title>
+    	<para>Teiid virtual procedures can only be defined in Teiid Designer.  They also cannot use IN/OUT, OUT, or RETURN paramters and may only return 1 result set.</para>
+    </section>
+  </section>  
+  <section id="update_procedures">
+    <title>Update Procedures</title>
+    <para>
+      Views are abstractions above physical sources. They typically
+      union or join information from multiple tables, often from multiple
+      data sources or other views. Teiid can perform update operations
+      against views. Update commands - INSERT, UPDATE, or DELETE -
+      against a view require logic to define how the tables and
+      views integrated by the view are affected by each type of
+      command. This transformation logic is invoked when an update command
+      is issued against a view. Update procedures define the logic
+      for how a user's update command against a view should be
+      decomposed into the individual commands to be executed against the
+      underlying physical sources. Similar to
+      <link linkend="virtual_procedures">virtual procedures</link>
+      , update procedures have the ability to execute queries or other
+      commands, define temporary tables, add data to temporary tables, walk
+      through result sets, use loops, and use conditional logic.
+    </para>
+    <section>
+      <title>Update Procedure Processing</title>
+      <orderedlist>
+        <listitem>
+          <para>The user application submits the SQL command through one of SOAP, JDBC, or ODBC.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The view this SQL command is executed against is detected.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The correct procedure is chosen depending upon whether the command is an INSERT, UPDATE, or DELETE.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The procedure is executed. The procedure itself can contain SQL commands of its own which can be of different types than the command submitted by the user application that invoked the procedure.
+          </para>
+        </listitem>
+        <listitem>
+          <para>Commands, as described in the procedure, are issued to the individual physical data sources or other views.
+          </para>
+        </listitem>
+        <listitem>
+          <para>A value representing the number of rows changed is returned to the calling application.
+          </para>
+        </listitem>
+      </orderedlist>
+    </section>  
+    <section>
+    	<title>For Each Row</title>
+    	<para>A FOR EACH ROW procedure will evaluate its block for each row of the view affected by the update statement.  
+    	For UPDATE and DELETE statements this will be every row that passes the WHERE condition.  For INSERT statements there will be 1 new row for each set of values from the VALUES or query expression.  
+    	The rows updated is reported as this number regardless of the affect of the underlying procedure logic.</para>
+    	<section>
+	      <title>Definition</title>
+	      <para>
+	        Usage:
+	        <synopsis label="Usage" >FOR EACH ROW 
+	BEGIN 
+	  ...
+	END</synopsis>
+	      </para>
+	      <para>The BEGIN and END keywords are used to denote block
+	        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
+	      </para>
+	    </section>
+	    <section>
+	      <title>Special Variables</title>
+	      <para>You can use a number of special variables when defining your update procedure.</para>
+	      <section id="new_variables">
+	        <title>NEW Variables</title>
+	        <para>Every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named NEW.&lt;column_name&gt;</para>
+	        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to the values in the INSERT VALUES clause or the UPDATE SET clause respectively.</para>
+	        <para>In an UPDATE procedure, the default value of these variables, if they are not set by the command, is the old value. In an INSERT procedure, the default value of these variables is the default value of the virtual table attributes.  See CHANGING Variables for distinguishing defaults from passed values.</para>
+	      </section>
+	      <section id="old_variables">
+	        <title>OLD Variables</title>
+	        <para>Every attribute in the view whose UPDATE and DELETE transformations you are defining has an equivalent variable named OLD.&lt;column_name&gt;</para>
+	        <para>When a DELETE or UPDATE command is executed against the view, these variables are initialized to the current values of the row being deleted or updated respectively.</para>
+	      </section>
+	      <section id="changing_variables">
+	        <title>CHANGING Variables</title>
+	        <para>Every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named CHANGING.&lt;column_name&gt;</para>
+	        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to <literal>true</literal> or <literal>false</literal> depending on whether the INPUT variable was set by the command.
+	          A CHANGING variable is commonly used to differentiate between a default insert value and one specified in the user query.</para>
+	        <para>For example, for a view with columns A, B, C:</para>
+	        <informaltable>
+	          <tgroup cols="2">
+	            <thead>
+	              <row>
+	                <entry>If User Executes...</entry>
+	                <entry>Then...</entry>
+	              </row>
+	            </thead>
+	            <tbody>
+	              <row>
+	                <entry><code>INSERT INTO VT (A, B) VALUES (0, 1)</code></entry>
+	                <entry>CHANGING.A = true, CHANGING.B = true, CHANGING.C = false</entry>
+	              </row>
+	              <row>
+	                <entry><code>UPDATE VT SET C = 2</code></entry>
+	                <entry>CHANGING.A = false, CHANGING.B = false, CHANGING.C = true</entry>
+	              </row>
+	            </tbody>
+	          </tgroup>
+	        </informaltable>
+	      </section>
+		</section>
+		<section>
+			<title>Examples</title>
+			<para>For example, for a view with columns A, B, C:</para>
+	        <example>
+				<title>Sample DELETE Procedure</title>
+				<programlisting language="SQL"><![CDATA[FOR EACH ROW
+BEGIN
+	DELETE FROM X WHERE Y = OLD.A;
+	DELETE FROM Z WHERE Y = OLD.A; // cascade the delete
+END]]></programlisting>
+           </example>
+	        <example>
+				<title>Sample UPDATE Procedure</title>
+				<programlisting language="SQL"><![CDATA[FOR EACH ROW
+BEGIN
+    IF (CHANGING.B)
+    BEGIN
+		UPDATE Z SET Y = NEW.B WHERE Y = OLD.B;
+    END
+END]]></programlisting>
+           </example>
+		</section>
+    </section>
+    <section>
+    	<title>Create Procedure</title>
+    	<para>Update procedures defined by "CREATE PROCEDURE ..." have been deprecated.  
+    	The TRANSLATE CRITERIA mechanism and associated logic is typically not adequite to correctly define an updatable view.</para>
+	    <section>
+	      <title>Definition</title>
+	      <para>
+	        Usage:
+	        <synopsis label="Usage" >CREATE PROCEDURE 
+	BEGIN 
+	  ...
+	END</synopsis>
+	      </para>
+	      <para>The CREATE PROCEDURE line demarcates the beginning of
+	        the procedure. The BEGIN and END keywords are used to denote block
+	        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
+	      </para>
+	    </section>
+	    <section>
+	      <title>Special Variables</title>
+	      <para>You can use a number of special variables when defining your update procedure.</para>
+	      <section id="input_variables">
+	        <title>INPUT Variables</title>
+	        <para>Every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named INPUTS.&lt;column_name&gt;</para>
+	        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to the values in the INSERT VALUES clause or the UPDATE SET clause respectively.</para>
+	        <para>In an UPDATE procedure, the default value of these variables, if they are not set by the command, is null. In an INSERT procedure, the default value of these variables is the default value of the virtual table attributes, based on their defined types.  See CHANGING Variables for distinguishing defaults from passed values.</para>
+	      	<warning>
+	      		<para>In prior release of Teiid INPUT was also accepted as the quailifer for an input variable.  As of Teidd 7, INPUT is a reserved word, so INPUTS is the preferred qualifier.</para>
+	      	</warning>
+	      </section>
+	      <section>
+	        <title>CHANGING Variables</title>
+	        <para>Similar to INPUT Variables, every attribute in the view whose UPDATE and INSERT transformations you are defining has an equivalent variable named CHANGING.&lt;column_name&gt;</para>
+	        <para>When an INSERT or an UPDATE command is executed against the view, these variables are initialized to <literal>true</literal> or <literal>false</literal> depending on whether the INPUT variable was set by the command.</para>
+	        <para>For example, for a view with columns A, B, C:</para>
+	        <informaltable>
+	          <tgroup cols="2">
+	            <thead>
+	              <row>
+	                <entry>If User Executes...</entry>
+	                <entry>Then...</entry>
+	              </row>
+	            </thead>
+	            <tbody>
+	              <row>
+	                <entry><code>INSERT INTO VT (A, B) VALUES (0, 1)</code></entry>
+	                <entry>CHANGING.A = true, CHANGING.B = true, CHANGING.C = false</entry>
+	              </row>
+	              <row>
+	                <entry><code>UPDATE VT SET C = 2</code></entry>
+	                <entry>CHANGING.A = false, CHANGING.B = false, CHANGING.C = true</entry>
+	              </row>
+	            </tbody>
+	          </tgroup>
+	        </informaltable>
+	      </section>
+	      <section id="rowsupdated_variable">
+	        <title>ROWS_UPDATED Variable</title>
+	        <para> Teiid returns the value of the integer VARIABLES.ROWS_UPDATED variable as a response to an update command executed against
+	          the view. Your procedure must set the value that returns
+	          when an application executes an update command against the view, 
+	          which triggers invocation of the update procedure. For
+	          example, if an UPDATE command is issued that affects 5 records, the
+	          ROWS_UPDATED should be set appropriately so that the user will
+	          receive '5' for the count of records affected.</para>
+	          <example>
+				<title>Sample Usage</title>
+				<programlisting language="SQL"><![CDATA[...
+	UPDATE FOO SET X = 1 WHERE TRANSLATE CRITERIA;
+	VARIABLES.ROWS_UPDATED = VARIABLES.ROWCOUNT;
+	...]]></programlisting>
+			  </example>
+	      </section>
+	    </section>  
+	    <section>
+	      <title>Update Procedure Command Criteria</title>
+	      <para> You can use a number of special SQL clauses when defining
+	        UPDATE or DELETE procedures. These make it easier to do variable
+	        substitutions in WHERE clauses or to check on the change state of
+	        variables without using a lot of conditional logic.</para>
+	        <section>
+	          <title>HAS CRITERIA</title>
+	          <warning><para>HAS CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.</para></warning>
+	          <para>You can use the HAS CRITERIA clause to check whether the user’s command has a particular kind of criteria on a particular set of attributes. This clause evaluates to either true or false. You can use it anywhere you can use a criteria within a procedure.</para>
+	          <para>
+	            Usage:
+	            <synopsis>HAS [criteria operator] CRITERIA [ON (column list)]</synopsis>
+	          </para>
+	          <itemizedlist>
+	            <para>Syntax Rules</para>
+	            <listitem>
+	              <para>The criteria operator, can be one of =, &lt;, &gt;, &lt;=, &gt;=, &lt;&gt;, LIKE, IS NULL, or IN.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>If the ON clause is present, HAS CRITERIA will return true only if criteria was present on all of the specified columns.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>The columns in a HAS CRITERIA ON clause always refer to view columns.
+	              </para>
+	            </listitem>
+	          </itemizedlist>
+	          <para>Each unoptimized conjunct of the user criteria is evaluated against the criteria selector.  If any conjunct matches then HAS CRITERIA evaluates to TRUE.  The use of OR or NOT will prevent contained predicates from matching the criteria selector.</para>
+	          <para>Some samples of the HAS CRITERIA clause:</para>
+	          <informaltable>
+	            <tgroup cols="2">
+	              <thead>
+	                <row>
+	                  <entry>SQL</entry>
+	                  <entry>Result</entry>
+	                </row>
+	              </thead>
+	              <tbody>
+	                <row>
+	                  <entry><code>HAS CRITERIA</code></entry>
+	                  <entry>Checks simply whether there was any criteria at all.</entry>
+	                </row>
+	                <row>
+	                  <entry><code>HAS CRITERIA ON (column1, column2)</code></entry>
+	                  <entry>Checks whether the criteria uses column1 and column2.</entry>
+	                </row>
+	                <row>
+	                  <entry><code>HAS = CRITERIA ON (column1)</code></entry>
+	                  <entry>Checks whether the criteria has a comparison criteria with = operator.</entry>
+	                </row>
+	                <row>
+	                  <entry><code>HAS LIKE CRITERIA</code></entry>
+	                  <entry>Checks whether the criteria has a match criteria using LIKE.</entry>
+	                </row>
+	              </tbody>
+	            </tgroup>
+	          </informaltable>
+	          <para>The HAS CRITERIA predicate is most commonly used in
+	            an IF clause, to determine if the user issued a particular form of
+	            command and to respond appropriately.</para>
+	        </section>
+	        <section>
+	          <title>TRANSLATE CRITERIA</title>
+	          <warning><para>TRANSLATE CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.</para></warning>
+	          <para>You can use the TRANSLATE CRITERIA clause to convert the criteria from the user application’s SQL command into the form required to interact with the target source or view tables. The TRANSLATE CRITERIA statement uses the SELECT transformation to infer the column mapping. This clause evaluates to a translated criteria that is evaluated in the context of a command.
+	          You can use these mappings either to replace the default mappings generated from the SELECT transformation or to specify a reverse expression when a virtual column is defined by an expression.</para>
+	          <para>
+	            Usage:
+	            <synopsis>TRANSLATE [criteria operator] CRITERIA [ON (column list)] [WITH (mapping list)]</synopsis>
+	          </para>
+	          <para>If there is no user criteria, then the translated criteria is always treated as TRUE.</para>
+	          <itemizedlist>
+	            <para>Syntax Rules</para>
+	            <listitem>
+	              <para>The criteria operator, can be one of =, &lt;, &gt;, &lt;=, &gt;=, &lt;&gt;, LIKE, IS NULL, or IN.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>If the ON clause is present, TRANSLATE CRITERIA will only form criteria using the specified columns.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>The columns in a TRANSLATE CRITERIA ON clause always refer to view columns.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>The WITH clause always has items with form &lt;elem&gt; = &lt;expression&gt; where the left hand side must refer to a view column.
+	              </para>
+	            </listitem>
+	            <listitem>
+	              <para>If the WITH clause or a specific mapping is not specified, then a mapping is created based on the SELECT clause of the SELECT transformation (the view column gets mapped to expression in SELECT clause at same  position). 
+	              </para>
+	            </listitem>
+	          </itemizedlist>
+	          <para>Each unoptimized conjunct of the user criteria is translated using the criteria selector.  If a conjunct does not match the selector, it will not be translated - which effectively treats the conjunct as TRUE.  The use of OR or NOT will prevent contained predicates from matching the criteria selector.</para>
+              <para>Some samples of TRANSLATE CRITERIA:</para>
+	          <informaltable>
+	            <tgroup cols="2">
+	              <colspec colwidth="1*"/>
+	              <colspec colwidth="1*"/>
+	              <thead>
+	                <row>
+	                  <entry>SQL</entry>
+	                  <entry>Result</entry>
+	                </row>
+	              </thead>
+	              <tbody>
+	                <row>
+	                  <entry><code>TRANSLATE CRITERIA</code></entry>
+	                  <entry>Translates any user criteria using the default mappings.</entry>
+	                </row>
+	                <row>
+	                  <entry>TRANSLATE CRITERIA WITH (column1 = 'A', column2 = INPUTS.column2 + 2)</entry>
+	                  <entry>Translates any criteria with some additional mappings: column1 is always mapped to 'A' and column2 is mapped to the incoming column2 value + 2.</entry>
+	                </row>
+	                <row>
+	                  <entry><code>TRANSLATE = CRITERIA ON (column1)</code></entry>
+	                  <entry>Translates only criteria that have = comparison operator and involve column1.</entry>
+	                </row>
+	              </tbody>
+	            </tgroup>
+	          </informaltable>
+	        </section>      
+	    </section>
+    </section>
+  </section>
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,2119 +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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="scalar_functions">
-	<title>Scalar Functions</title>
-	<para>
-		Teiid provides an extensive set of built-in scalar functions. See also
-		<link linkend="sql_support">SQL Support</link>
-		and
-		<link linkend="datatypes">Datatypes</link>
-		. In addition, Teiid provides the capability for user defined functions or UDFs.  See the Developers Guide for adding UDFs.  Once added UDFs may be called just like any other function.
-	</para>
-	<section id="numeric_functions">
-		<title>Numeric Functions</title>
-		<para>Numeric functions return numeric values (integer, long,
-			float, double, biginteger, bigdecimal). They generally take numeric
-			values as inputs, though some take strings.</para>
-		<informaltable frame="all">
-			<tgroup cols="3">
-				<thead>
-					<row>
-						<entry>
-							<para>Function</para>
-						</entry>
-						<entry>
-							<para>Definition</para>
-						</entry>
-						<entry>
-							<para>Datatype Constraint</para>
-						</entry>
-					</row>
-				</thead>
-				<tbody>
-					<row>
-						<entry>
-							<para>+ - * /</para>
-						</entry>
-						<entry>
-							<para>Standard numeric operators</para>
-						</entry>
-						<entry>
-							<para>x in {integer, long, float, double, biginteger,
-								bigdecimal}, return type is same as x <footnote>The precision and scale of non-bigdecimal arithmetic function functions results matches that of Java.  The results of bigdecimal operations match Java, except for division, which uses a preferred scale of max(16, dividend.scale + divisor.precision + 1), which then has trailing zeros removed by setting the scale to max(dividend.scale, normalized scale)</footnote></para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ABS(x)</para>
-						</entry>
-						<entry>
-							<para>Absolute value of x</para>
-						</entry>
-						<entry>
-							<para>See standard numeric operators above</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ACOS(x)</para>
-						</entry>
-						<entry>
-							<para>Arc cosine of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ASIN(x)</para>
-						</entry>
-						<entry>
-							<para>Arc sine of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ATAN(x)</para>
-						</entry>
-						<entry>
-							<para>Arc tangent of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ATAN2(x,y)</para>
-						</entry>
-						<entry>
-							<para>Arc tangent of x and y</para>
-						</entry>
-						<entry>
-							<para>x, y in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>CEILING(x)</para>
-						</entry>
-						<entry>
-							<para>Ceiling of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, float}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>COS(x)</para>
-						</entry>
-						<entry>
-							<para>Cosine of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>COT(x)</para>
-						</entry>
-						<entry>
-							<para>Cotangent of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>DEGREES(x)</para>
-						</entry>
-						<entry>
-							<para>Convert x degrees to radians</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>EXP(x)</para>
-						</entry>
-						<entry>
-							<para>e^x</para>
-						</entry>
-						<entry>
-							<para>x in {double, float}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FLOOR(x)</para>
-						</entry>
-						<entry>
-							<para>Floor of x</para>
-						</entry>
-						<entry>
-							<para>x in {double, float}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATBIGDECIMAL(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is bigdecimal, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATBIGINTEGER(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is biginteger, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATDOUBLE(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is double, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATFLOAT(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is float, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATINTEGER(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is integer, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>FORMATLONG(x, y)</para>
-						</entry>
-						<entry>
-							<para>Formats x using format y</para>
-						</entry>
-						<entry>
-							<para>x is long, y is string, returns string</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>LOG(x)</para>
-						</entry>
-						<entry>
-							<para>Natural log of x (base e)</para>
-						</entry>
-						<entry>
-							<para>x in {double, float}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>LOG10(x)</para>
-						</entry>
-						<entry>
-							<para>Log of x (base 10)</para>
-						</entry>
-						<entry>
-							<para>x in {double, float}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>MOD(x, y)</para>
-						</entry>
-						<entry>
-							<para>Modulus (remainder of x / y)</para>
-						</entry>
-						<entry>
-							<para>x in {integer, long, float, double, biginteger, bigdecimal}, return
-								type is same as x</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSEBIGDECIMAL(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns bigdecimal</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSEBIGINTEGER(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns biginteger</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSEDOUBLE(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSEFLOAT(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns float</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSEINTEGER(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns integer</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PARSELONG(x, y)</para>
-						</entry>
-						<entry>
-							<para>Parses x using format y</para>
-						</entry>
-						<entry>
-							<para>x, y are strings, returns long</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>PI()</para>
-						</entry>
-						<entry>
-							<para>Value of Pi</para>
-						</entry>
-						<entry>
-							<para>return is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>POWER(x,y)</para>
-						</entry>
-						<entry>
-							<para>x to the y power</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal, biginteger}, return is the same type as x</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>RADIANS(x)</para>
-						</entry>
-						<entry>
-							<para>Convert x radians to degrees</para>
-						</entry>
-						<entry>
-							<para>x in {double, bigdecimal}, return type is double</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>RAND()</para>
-						</entry>
-						<entry>
-							<para>Returns a random number, using generator established
-								so far in the query or initializing with system clock if
-								necessary.</para>
-						</entry>
-						<entry>
-							<para>Returns double.</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>RAND(x)</para>
-						</entry>
-						<entry>
-							<para>Returns a random number, using new generator seeded
-								with x.</para>
-						</entry>
-						<entry>
-							<para>x is integer, returns double.</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>ROUND(x,y)</para>
-						</entry>
-						<entry>
-							<para>Round x to y places; negative values of y indicate
-								places to the left of the decimal point</para>
-						</entry>
-						<entry>
-							<para>x in {integer, float, double, bigdecimal} y is integer, return is same
-								type as x</para>
-						</entry>
-					</row>
-					<row>
-						<entry>
-							<para>SIGN(x)</para>
-						</entry>
-						<entry>
-							<para>1 if x &gt; 0, 0 if x = 0, -1 if x &lt; 0</para>
-            </entry>
-              <entry>
-                <para>x in {integer, long, float, double, biginteger, bigdecimal},
-                  return type is integer</para>
-              </entry>
-          </row>
-          <row>
-            <entry>
-              <para>SIN(x)</para>
-            </entry>
-            <entry>
-              <para>Sine value of x</para>
-            </entry>
-            <entry>
-              <para>x in {double, bigdecimal}, return type is double</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>SQRT(x)</para>
-            </entry>
-            <entry>
-              <para>Square root of x</para>
-            </entry>
-            <entry>
-              <para>x in {long, double, bigdecimal}, return type is double</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TAN(x)</para>
-            </entry>
-            <entry>
-              <para>Tangent of x</para>
-            </entry>
-            <entry>
-              <para>x in {double, bigdecimal}, return type is double</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>BITAND(x, y)</para>
-            </entry>
-            <entry>
-              <para>Bitwise AND of x and y</para>
-            </entry>
-            <entry>
-              <para>x, y in {integer}, return type is integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>BITOR(x, y)</para>
-            </entry>
-            <entry>
-              <para>Bitwise OR of x and y</para>
-            </entry>
-            <entry>
-              <para>x, y in {integer}, return type is integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>BITXOR(x, y)</para>
-            </entry>
-            <entry>
-              <para>Bitwise XOR of x and y</para>
-            </entry>
-            <entry>
-              <para>x, y in {integer}, return type is integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>BITNOT(x)</para>
-            </entry>
-            <entry>
-              <para>Bitwise NOT of x</para>
-            </entry>
-            <entry>
-              <para>x in {integer}, return type is integer</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-    <section>
-      <title>Parsing Numeric Datatypes from Strings</title>
-      <para>
-        Teiid offers a set of functions you can use to parse numbers from
-        strings. For each string, you need to provide the formatting of the
-        string. These functions use the convention established by the
-        java.text.DecimalFormat class to define the formats you can use with
-        these functions. You can learn more about how this class defines
-        numeric string formats by visiting the Sun Java Web site at the
-        following
-        <ulink
-          url="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html">URL for Sun Java</ulink>.
-      </para>
-      <para>For example, you could use these function calls, with the
-        formatting string that adheres to the java.text.DecimalFormat
-        convention, to parse strings and return the datatype you need:
-      </para>
-      <informaltable frame="all">
-        <tgroup cols="4">
-          <thead>
-            <row>
-              <entry>
-                <para>Input String</para>
-              </entry>
-              <entry>
-                <para>Function Call to Format String</para>
-              </entry>
-              <entry>
-                <para>Output Value</para>
-              </entry>
-              <entry>
-                <para>Output Datatype</para>
-              </entry>
-            </row>          
-          </thead>
-          <tbody>
-            <row>
-              <entry>
-                <para>'$25.30'</para>
-              </entry>
-              <entry>
-                <para>parseDouble(cost, '$#,##0.00;($#,##0.00)')</para>
-              </entry>
-              <entry>
-                <para>25.3</para>
-              </entry>
-              <entry>
-                <para>double</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'25%'</para>
-              </entry>
-              <entry>
-                <para>parseFloat(percent, '#,##0%')</para>
-              </entry>
-              <entry>
-                <para>25</para>
-              </entry>
-              <entry>
-                <para>float</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'2,534.1'</para>
-              </entry>
-              <entry>
-                <para>parseFloat(total, '#,##0.###;-#,##0.###')
-                </para>
-              </entry>
-              <entry>
-                <para>2534.1</para>
-              </entry>
-              <entry>
-                <para>float</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'1.234E3'</para>
-              </entry>
-              <entry>
-                <para>parseLong(amt, '0.###E0')</para>
-              </entry>
-              <entry>
-                <para>1234</para>
-              </entry>
-              <entry>
-                <para>long</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'1,234,567'</para>
-              </entry>
-              <entry>
-                <para>parseInteger(total, '#,##0;-#,##0')
-                </para>
-              </entry>
-              <entry>
-                <para>1234567</para>
-              </entry>
-              <entry>
-                <para>integer</para>
-              </entry>
-            </row>
-          </tbody>
-        </tgroup>
-      </informaltable>
-    </section>
-    <section>
-      <title>Formatting Numeric Datatypes as Strings</title>
-      <para>
-        Teiid offers a set of functions you can use to convert numeric
-        datatypes into strings. For each string, you need to provide the
-        formatting. These functions use the convention established within
-        the java.text.DecimalFormat class to define the formats you can
-        use with these functions. You can learn more about how this class
-        defines numeric string formats by visiting the Sun Java Web site
-        at the following
-        <ulink
-          url="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html">URL for Sun Java</ulink>
-        .
-      </para>
-      <para>For example, you could use these function calls, with the
-        formatting string that adheres to the java.text.DecimalFormat
-        convention, to format the numeric datatypes into strings:</para>
-      <informaltable frame="all">
-        <tgroup cols="4">
-          <thead>
-            <row>
-              <entry>
-                <para>Input Value</para>
-              </entry>
-              <entry>
-                <para>Input Datatype</para>
-              </entry>
-              <entry>
-                <para>Function Call to Format String</para>
-              </entry>
-              <entry>
-                <para>Output String</para>
-              </entry>
-            </row>
-          </thead>
-          <tbody>
-            <row>
-              <entry>
-                <para>25.3</para>
-              </entry>
-              <entry>
-                <para>double</para>
-              </entry>
-              <entry>
-                <para>formatDouble(cost, '$#,##0.00;($#,##0.00)')</para>
-              </entry>
-              <entry>
-                <para>'$25.30'</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>25</para>
-              </entry>
-              <entry>
-                <para>float</para>
-              </entry>
-              <entry>
-                <para>formatFloat(percent, '#,##0%')</para>
-              </entry>
-              <entry>
-                <para>'25%'</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>2534.1</para>
-              </entry>
-              <entry>
-                <para>float</para>
-              </entry>
-              <entry>
-                <para>formatFloat(total, '#,##0.###;-#,##0.###')
-                </para>
-              </entry>
-              <entry>
-                <para>'2,534.1'</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>1234</para>
-              </entry>
-              <entry>
-                <para>long</para>
-              </entry>
-              <entry>
-                <para>formatLong(amt, '0.###E0')</para>
-              </entry>
-              <entry>
-                <para>'1.234E3'</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>1234567</para>
-              </entry>
-              <entry>
-                <para>integer</para>
-              </entry>
-              <entry>
-                <para>formatInteger(total, '#,##0;-#,##0')
-                </para>
-              </entry>
-              <entry>
-                <para>'1,234,567'</para>
-              </entry>
-            </row>
-          </tbody>
-        </tgroup>
-      </informaltable>
-    </section>
-  </section>
-  <section id="string_functions">
-    <title>String Functions</title>
-    <para>String functions generally take strings as inputs and return strings as outputs. </para>
-    <para>Unless specified, all of the arguments and return types in the following table are strings and all indexes are 1-based. The 0 index is considered to be before the start of the string.</para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para>x || y</para>
-            </entry>
-            <entry>
-              <para>Concatenation operator</para>
-            </entry>
-            <entry>
-              <para>x,y in {string}, return type is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>ASCII(x)</para>
-            </entry>
-            <entry>
-              <para>Provide ASCII value of the left most character in x.  The empty string will as input will return null. <footnoteref linkend="nonAscii"/></para>
-            </entry>
-            <entry>
-              <para>return type is integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>CHR(x) CHAR(x)</para>
-            </entry>
-            <entry>
-              <para>Provide the character for ASCII value x 
-              	<footnote id="nonAscii"><para>Non-ASCII range characters or integers used in these functions 
-              	may produce different results or exceptions depending on where the function is evalutated (Teiid vs. source).  
-              	Teiid's uses Java default int to char and char to int conversions, which operates over UTF16 values.</para></footnote>
-              </para>
-            </entry>
-            <entry>
-              <para>x in {integer}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>CONCAT(x, y)</para>
-            </entry>
-            <entry>
-              <para>Concatenates x and y with ANSI semantics. If
-                x and/or y is null, returns null.</para>
-            </entry>
-            <entry>
-              <para>x, y in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>CONCAT2(x, y)</para>
-            </entry>
-            <entry>
-              <para>Concatenates x and y with non-ANSI null
-                semantics. If x and y is null, returns null. If only x or y
-                is null, returns the other value.</para>
-            </entry>
-            <entry>
-              <para>x, y in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>INITCAP(x)</para>
-            </entry>
-            <entry>
-              <para>Make first letter of each word in string x capital
-                and all others lowercase</para>
-            </entry>
-            <entry>
-              <para>x in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>INSERT(str1, start, length, str2)</para>
-            </entry>
-            <entry>
-              <para>Insert string2 into string1</para>
-            </entry>
-            <entry>
-              <para>str1 in {string}, start in {integer}, length in
-                {integer}, str2 in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LCASE(x)</para>
-            </entry>
-            <entry>
-              <para>Lowercase of x</para>
-            </entry>
-            <entry>
-              <para>x in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LEFT(x, y)</para>
-            </entry>
-            <entry>
-              <para>Get left y characters of x</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LENGTH(x)</para>
-            </entry>
-            <entry>
-              <para>Length of x</para>
-            </entry>
-            <entry>
-              <para>return type is integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LOCATE(x, y)</para>
-            </entry>
-            <entry>
-              <para>Find position of x in y starting at beginning of y
-              </para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, return integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LOCATE(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Find position of x in y starting at z</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, z in {integer}, return
-                integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LPAD(x, y)</para>
-            </entry>
-            <entry>
-              <para>Pad input string x with spaces on the left to the
-                length of y</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {integer}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LPAD(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Pad input string x on the left to the length of y
-                using character z</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, z in {character}, return
-                string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>LTRIM(x)</para>
-            </entry>
-            <entry>
-              <para>Left trim x of white space</para>
-            </entry>
-            <entry>
-              <para>x in {string}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>QUERYSTRING(path [, expr [AS name] ...])</para>
-            </entry>
-            <entry>
-              <para>Returns a properly encoded query string appended to the given path.  Null valued expressions are omitted, and a null path is treated as ''.</para>
-              <para>Names are optional for column reference expressions.</para>
-              <para>e.g. QUERYSTRING('path', 'value' as "&amp;x", ' &amp; ' as y, null as z) returns 'path?%26x=value&amp;y=%20%26%20'</para>
-            </entry>
-            <entry>
-              <para>path, expr in {string}.  name is an identifier</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>REPEAT(str1,instances)</para>
-            </entry>
-            <entry>
-              <para>Repeat string1 a specified number of times</para>
-            </entry>
-            <entry>
-              <para>str1 in {string}, instances in {integer} return
-                string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>REPLACE(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Replace all y in x with z</para>
-            </entry>
-            <entry>
-              <para>x,y,z in {string}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>RIGHT(x, y)</para>
-            </entry>
-            <entry>
-              <para>Get right y characters of x</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>RPAD(input string x, pad length y)</para>
-            </entry>
-            <entry>
-              <para>Pad input string x with spaces on the right to the
-                length of y</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {integer}, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>RPAD(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Pad input string x on the right to the length of y
-                using character z</para>
-            </entry>
-            <entry>
-              <para>x in {string}, y in {string}, z in {character}, return
-                string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>RTRIM(x)</para>
-            </entry>
-            <entry>
-              <para>Right trim x of white space</para>
-            </entry>
-            <entry>
-              <para>x is string, return string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>SUBSTRING(x, y)</para>
-            </entry>
-            <entry>
-              <para>Get substring from x, from position y to the end of x
-              </para>
-            </entry>
-            <entry>
-              <para>y in {integer}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>SUBSTRING(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Get substring from x from position y with length z
-              </para>
-            </entry>
-            <entry>
-              <para>y, z in {integer}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TO_CHARS(x, encoding)</para>
-            </entry>
-            <entry>
-              <para>Return a clob from the blob with the given encoding.  
-              BASE64, HEX, and the builtin Java Charset names are valid values for the encoding.<footnote id="charset"><para>See the <ulink url="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html">Charset JavaDoc</ulink> for more on supported Charset names.  For charsets, unmappable chars will be replaced with the charset default character.  binary formats, such as BASE64, will error in their conversion to bytes is a unrecognizable character is encountered.</para></footnote></para>
-            </entry>
-            <entry>
-              <para>x is a blob, encoding is a string, and returns a clob</para>
-            </entry>
-          </row><row>
-            <entry>
-              <para id="to_bytes">TO_BYTES(x, encoding)</para>
-            </entry>
-            <entry>
-              <para>Return a blob from the clob with the given encoding.  
-              BASE64, HEX, and the builtin Java Charset names are valid values for the encoding.<footnoteref linkend="charset"/></para>
-            </entry>
-            <entry>
-              <para>x in a clob, encoding is a string, and returns a blob</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TRANSLATE(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Translate string x by replacing each character
-                in y with the character in z at the same position</para>
-            </entry>
-            <entry>
-              <para>x in {string}</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>UCASE(x)</para>
-            </entry>
-            <entry>
-              <para>Uppercase of x</para>
-            </entry>
-            <entry>
-              <para>x in {string}</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-  </section>
-  <section id="date_time_functions">
-    <title>Date/Time Functions</title>
-    <para>Date and time functions return or operate on dates, times, or timestamps. </para>
-    <para>Parse and format Date/Time functions use the convention established within
-        the java.text.SimpleDateFormat class to define the formats you can
-        use with these functions. You can learn more about how this class
-        defines formats by visiting the Sun Java Web site
-        at the following
-        <ulink
-          url="http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html">URL for Sun Java</ulink>.
-    </para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>        
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para>CURDATE()</para>
-            </entry>
-            <entry>
-              <para>Return current date</para>
-            </entry>
-            <entry>
-              <para>returns date</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>CURTIME()</para>
-            </entry>
-            <entry>
-              <para>Return current time</para>
-            </entry>
-            <entry>
-              <para>returns time</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>NOW()</para>
-            </entry>
-            <entry>
-              <para>Return current timestamp (date and time)</para>
-            </entry>
-            <entry>
-              <para>returns timestamp</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DAYNAME(x)</para>
-            </entry>
-            <entry>
-              <para>Return name of day</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DAYOFMONTH(x)</para>
-            </entry>
-            <entry>
-              <para>Return day of month</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DAYOFWEEK(x)</para>
-            </entry>
-            <entry>
-              <para>Return day of week (Sunday=1)</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DAYOFYEAR(x)</para>
-            </entry>
-            <entry>
-              <para>Return Julian day number</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>FORMATDATE(x, y)</para>
-            </entry>
-            <entry>
-              <para>Format date x using format y</para>
-            </entry>
-            <entry>
-              <para>x is date, y is string, returns string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>FORMATTIME(x, y)</para>
-            </entry>
-            <entry>
-              <para>Format time x using format y</para>
-            </entry>
-            <entry>
-              <para>x is time, y is string, returns string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>FORMATTIMESTAMP(x, y)</para>
-            </entry>
-            <entry>
-              <para>Format timestamp x using format y</para>
-            </entry>
-            <entry>
-              <para>x is timestamp, y is string, returns string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>FROM_UNIXTIME (unix_timestamp)</para>
-            </entry>
-            <entry>
-              <para>Return the Unix timestamp (in seconds) as a Timestamp value
-              </para>
-            </entry>
-            <entry>
-              <para>Unix timestamp (in seconds)</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>HOUR(x)</para>
-            </entry>
-            <entry>
-              <para>Return hour (in military 24-hour format)</para>
-            </entry>
-            <entry>
-              <para>x in {time, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>MINUTE(x)</para>
-            </entry>
-            <entry>
-              <para>Return minute</para>
-            </entry>
-            <entry>
-              <para>x in {time, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>MODIFYTIMEZONE (timestamp, startTimeZone,
-                endTimeZone)</para>
-            </entry>
-            <entry>
-              <para>Returns a timestamp based upon the incoming timestamp
-                adjusted for the differential between the start and end time
-                zones.  i.e. if the server is in GMT-6, then modifytimezone({ts
-                '2006-01-10 04:00:00.0'},'GMT-7', 'GMT-8') will return the
-                timestamp {ts '2006-01-10 05:00:00.0'} as read in GMT-6.  The
-                value has been adjusted 1 hour ahead to compensate for the
-                difference between GMT-7 and GMT-8.</para>
-            </entry>
-            <entry>
-              <para>startTimeZone and endTimeZone are strings,
-                returns a timestamp</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>MODIFYTIMEZONE (timestamp, endTimeZone)</para>
-            </entry>
-            <entry>
-              <para>Return a timestamp in the same manner as
-                modifytimezone(timestamp, startTimeZone, endTimeZone), but will
-                assume that the startTimeZone is the same as the server process.
-              </para>
-            </entry>
-            <entry>
-              <para>Timestamp is a timestamp; endTimeZone is a string,
-                returns a timestamp</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>MONTH(x)</para>
-            </entry>
-            <entry>
-              <para>Return month</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>MONTHNAME(x)</para>
-            </entry>
-            <entry>
-              <para>Return name of month</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>PARSEDATE(x, y)</para>
-            </entry>
-            <entry>
-              <para>Parse date from x using format y</para>
-            </entry>
-            <entry>
-              <para>x, y in {string}, returns date</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>PARSETIME(x, y)</para>
-            </entry>
-            <entry>
-              <para>Parse time from x using format y</para>
-            </entry>
-            <entry>
-              <para>x, y in {string}, returns time</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>PARSETIMESTAMP(x,y)</para>
-            </entry>
-            <entry>
-              <para>Parse timestamp from x using format y</para>
-            </entry>
-            <entry>
-              <para>x, y in {string}, returns timestamp</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>QUARTER(x)</para>
-            </entry>
-            <entry>
-              <para>Return quarter</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>SECOND(x)</para>
-            </entry>
-            <entry>
-              <para>Return seconds</para>
-            </entry>
-            <entry>
-              <para>x in {time, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TIMESTAMPCREATE(date, time)</para>
-            </entry>
-            <entry>
-              <para>Create a timestamp from a date and time</para>
-            </entry>
-            <entry>
-              <para>date in {date}, time in {time}, returns timestamp
-              </para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TIMESTAMPADD(interval, count,
-                timestamp)</para>
-            </entry>
-            <entry>
-              <para>Add a specified interval (hour, day of week, month)
-                to the timestamp, where intervals can have the following
-                definition:</para>
-              <orderedlist>
-                <listitem>
-                  <para>SQL_TSI_FRAC_SECOND - fractional
-                    seconds (billionths of a second)</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_SECOND - seconds</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_MINUTE - minutes</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_HOUR - hours</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_DAY - days</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_WEEK - weeks</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_MONTH - months</para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_QUARTER - quarters (3 months)
-                  </para>
-                </listitem>
-                <listitem>
-                  <para>SQL_TSI_YEAR - years</para>
-                </listitem>
-              </orderedlist>
-            </entry>
-            <entry>
-              <para>The interval constant may be specified either as a
-                string literal or a constant value. Interval in {string},
-                count in {integer}, timestamp in {date, time, timestamp}
-              </para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>TIMESTAMPDIFF(interval,
-                startTime, endTime)</para>
-            </entry>
-            <entry>
-              <para>Calculate the approximate number of whole
-                intervals in (endTime - startTime) using a specific interval
-                type (as defined by the constants in TIMESTAMPADD). If
-                (endTime &gt; startTime), a positive number will be returned. If (endTime &lt; startTime), a negative number will be returned. Calculations are approximate and may be less accurate over longer time spans.</para>
-            </entry>
-            <entry>
-              <para>Interval in {string}; startTime, endTime in {timestamp}, returns a long.</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>WEEK(x)</para>
-            </entry>
-            <entry>
-              <para>Return week in year</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>YEAR(x)</para>
-            </entry>
-            <entry>
-              <para>Return four-digit year</para>
-            </entry>
-            <entry>
-              <para>x in {date, timestamp}, returns integer</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-    <section>
-      <title>Parsing Date Datatypes from Strings</title>
-      <para>
-        Teiid does not implicitly convert strings that
-        contain dates presented in different formats, such as ‘19970101’ and
-        ‘31/1/1996’ to date-related datatypes. You can, however, use the
-        parseDate, parseTime, and parseTimestamp functions, described in the
-        next section, to explicitly convert strings with a different format
-        to the appropriate datatype. These functions use the convention
-        established within the java.text.SimpleDateFormat class to define
-        the formats you can use with these functions. You can learn more
-        about how this class defines date and time string formats by
-        visiting the
-        <ulink
-          url="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html">Sun Java Web site</ulink>
-        .
-      </para>
-      <para>For example, you could use these function calls, with the
-        formatting string that adheres to the java.text.SimpleDateFormat
-        convention, to parse strings and return the datatype you need:
-      </para>
-      <informaltable frame="all">
-        <tgroup cols="2">
-          <thead>
-            <row>
-              <entry>
-                <para>String</para>
-              </entry>
-              <entry>
-                <para>Function Call To Parse String</para>
-              </entry>
-            </row>
-          </thead>
-          <tbody>
-            <row>
-              <entry>
-                <para>'1997010'</para>
-              </entry>
-              <entry>
-                <para>parseDate(myDateString, 'yyyyMMdd')</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'31/1/1996'</para>
-              </entry>
-              <entry>
-                <para>parseDate(myDateString, 'dd''/''MM''/''yyyy')</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'22:08:56 CST'</para>
-              </entry>
-              <entry>
-                <para>parseTime (myTime, 'HH:mm:ss z')</para>
-              </entry>
-            </row>
-            <row>
-              <entry>
-                <para>'03.24.2003 at 06:14:32'</para>
-              </entry>
-              <entry>
-                <para>parseTimestamp(myTimestamp, 'MM.dd.yyyy ''at'' hh:mm:ss')</para>
-              </entry>
-            </row>
-          </tbody>
-        </tgroup>
-      </informaltable>
-    </section>
-    <section>
-      <title>Specifying Time Zones</title>
-      <para>Time zones can be specified in several formats. Common
-        abbreviations such as EST for "Eastern Standard Time" are allowed
-        but discouraged, as they can be ambiguous. Unambiguous time zones
-        are defined in the form continent or ocean/largest city. For
-        example, America/New_York, America/Buenos_Aires, or Europe/London.
-        Additionally, you can specify a custom time zone by GMT offset:
-        GMT[+/-]HH:MM.</para>
-      <para>For example: GMT-05:00</para>
-    </section>
-  </section>
-  <section>
-    <title>Type Conversion Functions</title>
-    <para>
-    Within your queries, you can convert between datatypes using the
-    CONVERT or CAST keyword. See also <link linkend="type_conversions">Data Type Conversions</link>
-    .
-    </para>
-    <informaltable frame="all">
-      <tgroup cols="2">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-          </row>
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para>CONVERT(x, type)</para>
-            </entry>
-            <entry>
-              <para>Convert x to type, where type is a Teiid
-                Base Type</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>CAST(x AS type)</para>
-            </entry>
-            <entry>
-              <para>Convert x to type, where type is a Teiid
-                Base Type</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-    <para>These functions are identical other than syntax; CAST is the standard SQL syntax, CONVERT is the standard JDBC/ODBC syntax. </para>
-  </section>
-  <section id="choice_functions">
-    <title>Choice Functions</title>
-    <para>Choice functions provide a way to select from two values based on some characteristic of one of the values. </para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <tbody>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>COALESCE(x,y+)</para>
-            </entry>
-            <entry>
-              <para>Returns the first non-null parameter</para>
-            </entry>
-            <entry>
-              <para>x and all y's can be any compatible types</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>IFNULL(x,y)</para>
-            </entry>
-            <entry>
-              <para>If x is null, return y; else return x</para>
-            </entry>
-            <entry>
-              <para>x, y, and the return type must be the same type but
-                can be any type</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>NVL(x,y)</para>
-            </entry>
-            <entry>
-              <para>If x is null, return y; else return x</para>
-            </entry>
-            <entry>
-              <para>x, y, and the return type must be the same type but
-                can be any type</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>NULLIF(param1, param2)</para>
-            </entry>
-            <entry>
-              <para>Equivalent to case when (param1 = param2) then null else param1</para>
-            </entry>
-            <entry>
-              <para>param1 and param2 must be compatable comparable types</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-    <para>IFNULL and NVL are aliases of each other. They are the same function. </para>
-  </section>
-  <section>
-    <title>Decode Functions</title>
-    <para>Decode functions allow you to have the Teiid Server
-      examine the contents of a column in a result set and alter, or
-      decode, the value so that your application can better use the
-      results.</para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para>DECODESTRING(x, y)</para>
-            </entry>
-            <entry>
-              <para>Decode column x using string of value pairs y
-                and return the decoded column as a string</para>
-            </entry>
-            <entry>
-              <para>all string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DECODESTRING(x, y, z)</para>
-            </entry>
-            <entry>
-              <para>Decode column x using string of value pairs y
-                with delimiter z and return the decoded column as a string
-              </para>
-            </entry>
-            <entry>
-              <para>all string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DECODEINTEGER(x, y)</para>
-            </entry>
-            <entry>
-              <para>Decode column x using string of value pairs y
-                and return the decoded column as an integer</para>
-            </entry>
-            <entry>
-              <para>all string parameters, return integer</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para>DECODEINTEGER(x,y,z)</para>
-            </entry>
-            <entry>
-              <para>Decode column x using string of value pairs y
-                with delimiter z and return the decoded column as an
-                integer</para>
-            </entry>
-            <entry>
-              <para>all string parameters, return integer</para>
-            </entry>
-          </row>
-        </tbody>
-      </tgroup>
-    </informaltable>
-    <para>Within each function call, you include the following arguments:</para>
-    <orderedlist>
-      <listitem>
-        <para>x is the input value for the decode operation. This will
-          generally be a column name.</para>
-      </listitem>
-      <listitem>
-        <para>y is the literal string that contains a delimited set of
-          input values and output values.</para>
-      </listitem>
-      <listitem>
-        <para>z is an optional parameter on these methods that allows you
-          to specify what delimiter the string specified in y uses.</para>
-      </listitem>
-    </orderedlist>
-    <para>For example, your application might query a table called
-      PARTS that contains a column called IS_IN_STOCK which contains a
-      Boolean value that you need to change into an integer for your
-      application to process. In this case, you can use the DECODEINTEGER
-      function to change the Boolean values to integers:</para>
-    <programlisting>SELECT DECODEINTEGER(IS_IN_STOCK, 'false, 0, true, 1') FROM PartsSupplier.PARTS;</programlisting> 
-    <para>When the Teiid System encounters the value false in the
-      result set, it replaces the value with 0.</para>
-    <para>If, instead of using integers, your application requires
-      string values, you can use the DECODESTRING function to return the
-      string values you need:</para>
-    <programlisting>SELECT DECODESTRING(IS_IN_STOCK, 'false, no, true, yes, null') FROM PartsSupplier.PARTS;</programlisting>
-    <para>In addition to two input/output value pairs, this sample query
-      provides a value to use if the column does not contain any of the
-      preceding input values. If the row in the IS_IN_STOCK column does
-      not contain true or false, the Teiid Server inserts a null into
-      the result set.</para>
-    <para>When you use these DECODE functions, you can provide as many
-      input/output value pairs if you want within the string. By default,
-      the Teiid System expects a comma delimiter, but you can add a
-      third parameter to the function call to specify a different
-      delimiter:</para>
-    <programlisting>SELECT DECODESTRING(IS_IN_STOCK, 'false:no:true:yes:null',’:’) FROM PartsSupplier.PARTS;</programlisting>
-    <para>You can use keyword null in the DECODE string as either an
-      input value or an output value to represent a null value. However,
-      if you need to use the literal string null as an input or output
-      value (which means the word null appears in the column and not a
-      null value) you can put the word in quotes: "null".</para>
-    <programlisting>SELECT DECODESTRING( IS_IN_STOCK, 'null,no,"null",no,nil,no,false,no,true,yes' ) FROM PartsSupplier.PARTS;</programlisting>
-    <para>If the DECODE function does not find a matching output value
-      in the column and you have not specified a default value, the DECODE
-      function will return the original value the Teiid Server found
-      in that column.</para>
-  </section>
-  <section>
-    <title>Lookup Function</title>
-    <para>The Lookup function allows you to cache a key value pair table and access it through a scalar function. This caching
-    accelerates response time to queries that use the lookup tables, known
-    in business terminology as lookup tables or code tables.</para>
-    <para><synopsis>LOOKUP(codeTable, returnColumn, keyColumn, keyValue)</synopsis></para>
-    <para>In the lookup table codeTable, find the row where
-      keyColumn has the value keyValue and return the
-      associated returnColumn. codeTable must be a fully-qualified string
-      literal containing metadata identifiers, keyValue datatype
-      must match datatype of the keyColumn, return datatype
-      matches that of returnColumn. returnColumn and
-      keyColumn parameters should use their shortened names.
-    </para>
-    <para>For example, a StatePostalCodes table used to translate postal codes to
-      complete state names might represent an example of this type of
-      lookup table. One column, PostalCode, represents a key column.
-      Other tables refer to this two-letter code. A
-      second column, StateDisplayName, would represent the complete name
-      of the state. Hence, a query to this lookup table would typically
-      provide the PostalCode and expect the StateDisplayName in response.
-    </para>
-    <para>When you call this function for any combination of codeTable, returnColumn, and
-      keyColumn for the first time, the Teiid System caches the result. 
-      The Teiid System uses this cache for all
-      queries, in all sessions, that later access this lookup table.</para>
-    <para>The Teiid System unloads these cached lookup tables when you stop and restart
-      the Teiid System. Thus, you should not use this function for
-      data that is subject to updates. Instead, you can use it against
-      static data that does not change over time.</para>
-    <note>
-      <itemizedlist>
-        <listitem>
-          <para>The keyColumn is expected to contain unique
-            values. If the column contains duplicate values, an exception will be thrown.</para>
-        </listitem>
-      </itemizedlist>
-    </note>
-  </section>
-  <section>
-    <title>System Functions</title>
-    <para>System functions provide access to information in the Teiid system from within a query. </para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para><code>COMMANDPAYLOAD()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the string form of the command payload
-                or null if no command payload was specified. The command
-                payload is set by a method on the Teiid JDBC API
-                extensions on a per-query basis.</para>
-            </entry>
-            <entry>
-              <para>Returns a string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>COMMANDPAYLOAD(key)</code></para>
-            </entry>
-            <entry>
-              <para>Cast the command payload object to a
-                java.util.Properties object and look up the specified key in
-                the object</para>
-            </entry>
-            <entry>
-              <para>key in {string}, return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>ENV(key)</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve a system environment property. The only key specific to the current session is ‘sessionid’.  
-                However the preferred mechanism for getting the session id is with the session_id() function.  
-                To prevent untrusted access to system properties, the use of this function must be specifically enabled in the &jboss-beans; file.
-                </para>
-            </entry>
-            <entry>
-              <para>key in {string}, return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>SESSION_ID()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the string form of the current session id.</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>USER()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the name of the user executing the
-                query</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>CURRENT_DATABASE()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the catalog name of the database. Currently VDB's name is also the catalog name.</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>          
-        </tbody>
-      </tgroup>
-    </informaltable>
-  </section>
-  <section id="xml_functions">
-    <title>XML Functions</title>
-    <para>XML functions provide functionality for working with XML data. </para>
-    <section>
-    	<title>JSONTOXML</title>
-    	<para>Returns an xml document from JSON.</para>
-        <para><synopsis>JSONTOXML(rootElementName, json)</synopsis></para>
-        <para>rootElementName is a string, json is in {clob, blob}. Return value is xml.</para>
-        <para>The appropriate UTF encoding (8, 16LE. 16BE, 32LE, 32BE) will be detected for JSON blobs.  If another encoding is used, see the to_chars function.</para>
-        <para>The result is always a well-formed XML document.</para>
-        <para>The mapping to XML uses the following rules:
-        <itemizedlist>
-        	<listitem>
-        		<para>The current element name is initially the rootElementName, and becomes the object value name as the JSON structure is traversed.</para>
-        	</listitem>
-        	<listitem>
-        		<para>All element names must be valid xml 1.1 names.  Invalid names are fully escaped according to the SQLXML specification.</para>
-        	</listitem>
-        	<listitem>
-        		<para>Each object or primitive value will be enclosed in an element with the current name.</para>
-        	</listitem>
-        	<listitem>
-        		<para>Unless an array value is the root, it will not be enclosed in an additional element.</para>
-        	</listitem>
-        </itemizedlist> 
-        </para>
-        <example>
-        	<title>Sample JSON to XML for jsonToXml('person', x)</title>
-        	<para>JSON:</para>
-        	<programlisting language="JSON">{ "firstName" : "John" , "children" : [ "Randy", "Judy" ] }</programlisting>
-        	<para>XML:</para>
-        	<programlisting language="XML"><![CDATA[<?xml version="1.0" ?><person><firstName>John</firstName><children>Randy</children><children>Judy<children></person>]]></programlisting>
-        </example>
-        <example>
-        	<title>Sample JSON to XML for jsonToXml('person', x) with a root array.</title>
-        	<para>JSON:</para>
-        	<programlisting language="JSON">[{ "firstName" : "George" }, { "firstName" : "Jerry" }]</programlisting>
-        	<para>XML (Notice there is an extra "person" wrapping element to keep the XML well-formed):</para>
-        	<programlisting language="XML"><![CDATA[<?xml version="1.0" ?><person><person><firstName>George</firstName></person><person><firstName>Jerry</firstName></person></person>]]></programlisting>
-        </example>
-    </section>
-    <section>
-    	<title>XMLCOMMENT</title>
-    	<para>Returns an xml comment.</para>
-    	<para><synopsis>XMLCOMMENT(comment)</synopsis></para>
-    	<para>Comment is a string.  Return value is xml.</para>
-    </section>
-    <section>
-    	<title>XMLCONCAT</title>
-    	<para>Returns an XML with the concatination of the given xml types.</para>
-    	<para><synopsis>XMLCONCAT(content [, content]*)</synopsis></para>
-    	<para>Content is xml. Return value is xml.</para>
-    	<para>If a value is null, it will be ignored.  If all values are null, null is returned.</para>
-    </section>
-    <section>
-    	<title>XMLELEMENT</title>
-    	<para>Returns an XML element with the given name and content.</para>
-    	<para><synopsis>XMLELEMENT([NAME] name [, &lt;NSP&gt;] [, &lt;ATTR&gt;][, content]*)</synopsis></para>
-          <para><synopsis>ATTR:=XMLATTRIBUTES(exp [AS name] [, exp [AS name]]*)</synopsis></para>
-          <para><synopsis>NSP:=XMLNAMESPACES((uri AS prefix | DEFAULT uri | NO DEFAULT))+</synopsis></para>
-          <para>If the content value is of a type other than xml, it will be escaped when added to the parent element.  Null content values are ignored.  
-          Whitespace in XML or the string values of the content is preserved, but no whitespace is added between content values.</para>
-          <para id="xmlnamespaces">XMLNAMESPACES is used provide namespace information.  NO DEFAULT is equivalent to defining the default namespace to the null uri - xmlns="".  
-          Only one DEFAULT or NO DEFAULT namespace item may be specified.  The namespace prefixes xmlns and xml are reserved.</para>
-          <para>If a attribute name is not supplied, the expression must be a column reference, in which case the attribute name will be the column name. Null attribute values are ignored.</para>
-		<para>Name, prefix are identifiers. uri is a string literal. content can be any type. Return value is xml.  The return value is valid for use in places where a document is expected.</para>            
-           <para><emphasis>Example</emphasis>: with an xml_value of &lt;doc/&gt;, <programlisting>xmlelement('elem', 1, '&lt;2/&gt;', xml_value)</programlisting>
-           		Returns: <code>&lt;elem&gt;1&amp;lt;2/&amp;gt;&lt;doc/&gt;&lt;elem/&gt;</code>
-           </para>
-    </section>
-    <section>
-    	<title>XMLFOREST</title>
-    	<para>Returns an concatination of XML elements for each content item.</para>
-    	<para><synopsis>XMLFOREST(content [AS name] [, &lt;NSP&gt;] [, content [AS name]]*)</synopsis></para>
-        <para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para>
-   		<para>Name is an identifier. Content can be any type. Return value is xml.</para>
-		<para>If a name is not supplied for a content item, the expression must be a column reference, in which case the element name will be a partially escaped version of the column name.</para>
-    </section>
-    <section id="xmlparse">
-    	<title>XMLPARSE</title>
-    	<para>Returns an XML type representation of the string value expression.</para>
-        <para><synopsis>XMLPARSE((DOCUMENT|CONTENT) expr [WELLFORMED])</synopsis></para>
-        <para>expr in {string, clob, blob}. Return value is xml.</para>
-        <para>If DOCIMENT is specfied then the expression must have a single
-        root element and may or may not contain an XML declaration.</para>
-        <para>
-              If WELLFORMED is specified then validation is skipped; this is especially useful for CLOB and BLOB known to already be valid.  
-        </para>
-    </section>
-    <section>
-    	<title>XMLPI</title>
-    	<para>Returns an xml processing instruction.</para>
-        <para><synopsis>XMLPI([NAME] name [, content])</synopsis></para>
-        <para>Name is an identifier. Content is a string. Return value is xml.</para>
-    </section>
-    <section id="xmlquery">
-    	<title>XMLQUERY</title>
-    	<para>Returns the XML result from evaluating the given xquery.</para>
-    	<para><synopsis>XMLQUERY([&lt;NSP&gt;] xquery [&lt;PASSING&gt;] [(NULL|EMPTY) ON EMPTY]]</synopsis></para>
-    	<para><synopsis>PASSING:=PASSING exp [AS name] [, exp [AS name]]*</synopsis></para>
-    	<para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para><para>Namespaces may also be directly declared in the xquery prolog.</para>
-             <para id="passing">The optional PASSING clause is used to provide the context item, which does not have a name, and named global variable values.  
-             If the xquery uses a context item and none is provided, then an exception will be raised.  
-             Only one context item may be specified and should be an XML type.  All non-context non-XML passing values will be converted to an appropriate XML type.</para>
-             <para>The ON EMPTY clause is used to specify the result when the evaluted sequence is empty.  
-             EMPTY ON EMPTY, the default, returns an empty XML result.  NULL ON EMPTY returns a null result.</para>
-             <para>xquery in string. Return value is xml.</para>
-             <para>XMLQUERY is part of the SQL/XML 2006 specification.</para>
-             <para>See also <link linkend="xmltable">XMLTABLE</link></para>
-             <note><para>A technique known as document projection is used to reduce the memory footprint of the context item document.  
-             Only the parts of the document needed by the XQuery path expressions will be loaded into memory.  Since document projection analysis uses all relevant path expressions, even 1 expression that could potentially use many nodes, e.g. //x rather than /a/b/x will cause a larger memory footprint.</para></note>
-             
-    </section>
-    <section id="xmlserialize">
-    	<title>XMLSERIALIZE</title>
-    	<para>Returns a character type representation of the xml expression.</para>
-        <para><synopsis>XMLSERIALIZE([(DOCUMENT|CONTENT)] xml [AS datatype])</synopsis></para>
-        <para>Return value mathces datatype.</para>
-		<para>Only a character type (string, varchar, clob) may be specified as the datatype.  CONTENT is the default.  
-              If DOCUMENT is specified and the xml is not a valid document or fragment, then an exception is raised. 
-              </para>
-    </section>
-    <section>
-    	<title>XSLTRANSFORM</title>
-    	<para>Applies an XSL stylesheet to the given document.</para>
-    	<para><synopsis>XSLTRANSFORM(doc, xsl)</synopsis></para>
-    	<para>Doc, xsl in {string, clob, xml}. Return value is a clob.</para>
-    	<para>If either argument is null, the result is null.</para>
-    </section>
-    <section>
-    	<title>XPATHVALUE</title>
-    	<para>Applies the XPATH expression to the document and returns a
-               string value for the first matching result.</para>
-    	<para><synopsis>XPATHVALUE(doc, xpath)</synopsis></para>
-    	<para>Doc and xpath in {string, clob, xml}. Return value is a string.</para>
-    	<para>An attempt is made to provide a meaningful result for non-text nodes.</para>
-    </section>
-  </section>
-  <section>
-    <title>Security Functions</title>
-    <para>Security functions provide the ability to interact
-    with the security system.</para>
-    <section>
-    	<title>HASROLE</title>
-    	<para>Whether the current caller has the role roleName.</para>
-    	<para><synopsis>hasRole([roleType,] roleName)</synopsis></para>
-        <para>roleName must be a string, the return type is boolean.</para>
-        <para>The two argument form is provided for backwards compatibility. roleType is a string and must be 'data'</para>
-    </section>
-  </section>
-  <section id="nondeterministic_functions">
-  	<title>Nondeterministic Function Handling</title>
-	<para>Teiid categorizes functions by varying degrees of determinism.
-		When a function is evaluated and to what extent the result can be
-		cached are based upon its determinism level.</para>
-  	<orderedlist>
-		<listitem>
-			<para>Deterministic - the function will always return the same result
-				for the given inputs. Deterministic functions are evaluated by the
-				engine as soon as all input values are known, which may occur as soon
-				as the rewrite phase. Some functions, such as the lookup function, are
-				not truly deterministic, but is treated as such for performance. All
-				functions not categorized below are considered deterministic.</para>
-		</listitem>
-		<listitem>
-			<para>User Deterministic - the function will return the same
-				result for the given inputs for the same user. This includes the hasRole
-				and user functions. User deterministic functions are evaluated
-				by the engine as soon as all input values are known, which may occur as soon
-				as the rewrite phase. If a user deterministic function is evaluated
-				during the creation of a prepared processing plan, then the resulting
-				plan will be cached only for the user.</para>
-		</listitem>
-		<listitem>
-			<para>Session Deterministic - the function will return the same
-				result for the given inputs under the same user session. This category includes the env
-				function. Session deterministic functions are evaluated
-				by the engine as soon as all input values are known, which may occur as soon
-				as the rewrite phase. If a session deterministic function is evaluated
-				during the creation of a prepared processing plan, then the resulting
-				plan will be cached only for the user's session.</para>
-		</listitem>
-		<listitem>
-			<para>Command Deterministic - the result of function evaluation is
-				only deterministic within the scope of the user command. This category
-				include the curdate, curtime, now, and commandpayload functions.
-				Command deterministic functions are delayed in evaluation until
-				processing to ensure that even prepared plans utilizing these
-				functions will be executed with relevant values. Command deterministic function
-				evaulation will occur prior to pushdown - however multiple occurances
-				of the same command deterministic time function are not guarenteed to
-				evaluate to the same value. </para>
-		</listitem>
-		<listitem>
-			<para>Nondeterministic - the result of function evaluation is fully
-				nondeterministic. This category includes the rand function and UDFs
-				marked as nondeterministic. Nondeterministic functions are delayed in
-				evaluation until processing with a preference for pushdown. If the
-				function is not pushed down, then it may be evaluated for every row in
-				it's execution context (for example if the function is used in the
-				select clause).</para>
-		</listitem>
-  	</orderedlist>
-  </section>
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml (from rev 2764, trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,2131 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="scalar_functions">
+	<title>Scalar Functions</title>
+	<para>
+		Teiid provides an extensive set of built-in scalar functions. See also
+		<link linkend="sql_support">SQL Support</link>
+		and
+		<link linkend="datatypes">Datatypes</link>
+		. In addition, Teiid provides the capability for user defined functions or UDFs.  See the Developers Guide for adding UDFs.  Once added UDFs may be called just like any other function.
+	</para>
+	<section id="numeric_functions">
+		<title>Numeric Functions</title>
+		<para>Numeric functions return numeric values (integer, long,
+			float, double, biginteger, bigdecimal). They generally take numeric
+			values as inputs, though some take strings.</para>
+		<informaltable frame="all">
+			<tgroup cols="3">
+				<thead>
+					<row>
+						<entry>
+							<para>Function</para>
+						</entry>
+						<entry>
+							<para>Definition</para>
+						</entry>
+						<entry>
+							<para>Datatype Constraint</para>
+						</entry>
+					</row>
+				</thead>
+				<tbody>
+					<row>
+						<entry>
+							<para>+ - * /</para>
+						</entry>
+						<entry>
+							<para>Standard numeric operators</para>
+						</entry>
+						<entry>
+							<para>x in {integer, long, float, double, biginteger,
+								bigdecimal}, return type is same as x <footnote>The precision and scale of non-bigdecimal arithmetic function functions results matches that of Java.  The results of bigdecimal operations match Java, except for division, which uses a preferred scale of max(16, dividend.scale + divisor.precision + 1), which then has trailing zeros removed by setting the scale to max(dividend.scale, normalized scale)</footnote></para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ABS(x)</para>
+						</entry>
+						<entry>
+							<para>Absolute value of x</para>
+						</entry>
+						<entry>
+							<para>See standard numeric operators above</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ACOS(x)</para>
+						</entry>
+						<entry>
+							<para>Arc cosine of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ASIN(x)</para>
+						</entry>
+						<entry>
+							<para>Arc sine of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ATAN(x)</para>
+						</entry>
+						<entry>
+							<para>Arc tangent of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ATAN2(x,y)</para>
+						</entry>
+						<entry>
+							<para>Arc tangent of x and y</para>
+						</entry>
+						<entry>
+							<para>x, y in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>CEILING(x)</para>
+						</entry>
+						<entry>
+							<para>Ceiling of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, float}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>COS(x)</para>
+						</entry>
+						<entry>
+							<para>Cosine of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>COT(x)</para>
+						</entry>
+						<entry>
+							<para>Cotangent of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>DEGREES(x)</para>
+						</entry>
+						<entry>
+							<para>Convert x degrees to radians</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>EXP(x)</para>
+						</entry>
+						<entry>
+							<para>e^x</para>
+						</entry>
+						<entry>
+							<para>x in {double, float}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FLOOR(x)</para>
+						</entry>
+						<entry>
+							<para>Floor of x</para>
+						</entry>
+						<entry>
+							<para>x in {double, float}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATBIGDECIMAL(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is bigdecimal, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATBIGINTEGER(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is biginteger, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATDOUBLE(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is double, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATFLOAT(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is float, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATINTEGER(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is integer, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>FORMATLONG(x, y)</para>
+						</entry>
+						<entry>
+							<para>Formats x using format y</para>
+						</entry>
+						<entry>
+							<para>x is long, y is string, returns string</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>LOG(x)</para>
+						</entry>
+						<entry>
+							<para>Natural log of x (base e)</para>
+						</entry>
+						<entry>
+							<para>x in {double, float}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>LOG10(x)</para>
+						</entry>
+						<entry>
+							<para>Log of x (base 10)</para>
+						</entry>
+						<entry>
+							<para>x in {double, float}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>MOD(x, y)</para>
+						</entry>
+						<entry>
+							<para>Modulus (remainder of x / y)</para>
+						</entry>
+						<entry>
+							<para>x in {integer, long, float, double, biginteger, bigdecimal}, return
+								type is same as x</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSEBIGDECIMAL(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns bigdecimal</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSEBIGINTEGER(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns biginteger</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSEDOUBLE(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSEFLOAT(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns float</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSEINTEGER(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns integer</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PARSELONG(x, y)</para>
+						</entry>
+						<entry>
+							<para>Parses x using format y</para>
+						</entry>
+						<entry>
+							<para>x, y are strings, returns long</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>PI()</para>
+						</entry>
+						<entry>
+							<para>Value of Pi</para>
+						</entry>
+						<entry>
+							<para>return is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>POWER(x,y)</para>
+						</entry>
+						<entry>
+							<para>x to the y power</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal, biginteger}, return is the same type as x</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>RADIANS(x)</para>
+						</entry>
+						<entry>
+							<para>Convert x radians to degrees</para>
+						</entry>
+						<entry>
+							<para>x in {double, bigdecimal}, return type is double</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>RAND()</para>
+						</entry>
+						<entry>
+							<para>Returns a random number, using generator established
+								so far in the query or initializing with system clock if
+								necessary.</para>
+						</entry>
+						<entry>
+							<para>Returns double.</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>RAND(x)</para>
+						</entry>
+						<entry>
+							<para>Returns a random number, using new generator seeded
+								with x.</para>
+						</entry>
+						<entry>
+							<para>x is integer, returns double.</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>ROUND(x,y)</para>
+						</entry>
+						<entry>
+							<para>Round x to y places; negative values of y indicate
+								places to the left of the decimal point</para>
+						</entry>
+						<entry>
+							<para>x in {integer, float, double, bigdecimal} y is integer, return is same
+								type as x</para>
+						</entry>
+					</row>
+					<row>
+						<entry>
+							<para>SIGN(x)</para>
+						</entry>
+						<entry>
+							<para>1 if x &gt; 0, 0 if x = 0, -1 if x &lt; 0</para>
+            </entry>
+              <entry>
+                <para>x in {integer, long, float, double, biginteger, bigdecimal},
+                  return type is integer</para>
+              </entry>
+          </row>
+          <row>
+            <entry>
+              <para>SIN(x)</para>
+            </entry>
+            <entry>
+              <para>Sine value of x</para>
+            </entry>
+            <entry>
+              <para>x in {double, bigdecimal}, return type is double</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>SQRT(x)</para>
+            </entry>
+            <entry>
+              <para>Square root of x</para>
+            </entry>
+            <entry>
+              <para>x in {long, double, bigdecimal}, return type is double</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TAN(x)</para>
+            </entry>
+            <entry>
+              <para>Tangent of x</para>
+            </entry>
+            <entry>
+              <para>x in {double, bigdecimal}, return type is double</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>BITAND(x, y)</para>
+            </entry>
+            <entry>
+              <para>Bitwise AND of x and y</para>
+            </entry>
+            <entry>
+              <para>x, y in {integer}, return type is integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>BITOR(x, y)</para>
+            </entry>
+            <entry>
+              <para>Bitwise OR of x and y</para>
+            </entry>
+            <entry>
+              <para>x, y in {integer}, return type is integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>BITXOR(x, y)</para>
+            </entry>
+            <entry>
+              <para>Bitwise XOR of x and y</para>
+            </entry>
+            <entry>
+              <para>x, y in {integer}, return type is integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>BITNOT(x)</para>
+            </entry>
+            <entry>
+              <para>Bitwise NOT of x</para>
+            </entry>
+            <entry>
+              <para>x in {integer}, return type is integer</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+    <section>
+      <title>Parsing Numeric Datatypes from Strings</title>
+      <para>
+        Teiid offers a set of functions you can use to parse numbers from
+        strings. For each string, you need to provide the formatting of the
+        string. These functions use the convention established by the
+        java.text.DecimalFormat class to define the formats you can use with
+        these functions. You can learn more about how this class defines
+        numeric string formats by visiting the Sun Java Web site at the
+        following
+        <ulink
+          url="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html">URL for Sun Java</ulink>.
+      </para>
+      <para>For example, you could use these function calls, with the
+        formatting string that adheres to the java.text.DecimalFormat
+        convention, to parse strings and return the datatype you need:
+      </para>
+      <informaltable frame="all">
+        <tgroup cols="4">
+          <thead>
+            <row>
+              <entry>
+                <para>Input String</para>
+              </entry>
+              <entry>
+                <para>Function Call to Format String</para>
+              </entry>
+              <entry>
+                <para>Output Value</para>
+              </entry>
+              <entry>
+                <para>Output Datatype</para>
+              </entry>
+            </row>          
+          </thead>
+          <tbody>
+            <row>
+              <entry>
+                <para>'$25.30'</para>
+              </entry>
+              <entry>
+                <para>parseDouble(cost, '$#,##0.00;($#,##0.00)')</para>
+              </entry>
+              <entry>
+                <para>25.3</para>
+              </entry>
+              <entry>
+                <para>double</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'25%'</para>
+              </entry>
+              <entry>
+                <para>parseFloat(percent, '#,##0%')</para>
+              </entry>
+              <entry>
+                <para>25</para>
+              </entry>
+              <entry>
+                <para>float</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'2,534.1'</para>
+              </entry>
+              <entry>
+                <para>parseFloat(total, '#,##0.###;-#,##0.###')
+                </para>
+              </entry>
+              <entry>
+                <para>2534.1</para>
+              </entry>
+              <entry>
+                <para>float</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'1.234E3'</para>
+              </entry>
+              <entry>
+                <para>parseLong(amt, '0.###E0')</para>
+              </entry>
+              <entry>
+                <para>1234</para>
+              </entry>
+              <entry>
+                <para>long</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'1,234,567'</para>
+              </entry>
+              <entry>
+                <para>parseInteger(total, '#,##0;-#,##0')
+                </para>
+              </entry>
+              <entry>
+                <para>1234567</para>
+              </entry>
+              <entry>
+                <para>integer</para>
+              </entry>
+            </row>
+          </tbody>
+        </tgroup>
+      </informaltable>
+    </section>
+    <section>
+      <title>Formatting Numeric Datatypes as Strings</title>
+      <para>
+        Teiid offers a set of functions you can use to convert numeric
+        datatypes into strings. For each string, you need to provide the
+        formatting. These functions use the convention established within
+        the java.text.DecimalFormat class to define the formats you can
+        use with these functions. You can learn more about how this class
+        defines numeric string formats by visiting the Sun Java Web site
+        at the following
+        <ulink
+          url="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html">URL for Sun Java</ulink>
+        .
+      </para>
+      <para>For example, you could use these function calls, with the
+        formatting string that adheres to the java.text.DecimalFormat
+        convention, to format the numeric datatypes into strings:</para>
+      <informaltable frame="all">
+        <tgroup cols="4">
+          <thead>
+            <row>
+              <entry>
+                <para>Input Value</para>
+              </entry>
+              <entry>
+                <para>Input Datatype</para>
+              </entry>
+              <entry>
+                <para>Function Call to Format String</para>
+              </entry>
+              <entry>
+                <para>Output String</para>
+              </entry>
+            </row>
+          </thead>
+          <tbody>
+            <row>
+              <entry>
+                <para>25.3</para>
+              </entry>
+              <entry>
+                <para>double</para>
+              </entry>
+              <entry>
+                <para>formatDouble(cost, '$#,##0.00;($#,##0.00)')</para>
+              </entry>
+              <entry>
+                <para>'$25.30'</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>25</para>
+              </entry>
+              <entry>
+                <para>float</para>
+              </entry>
+              <entry>
+                <para>formatFloat(percent, '#,##0%')</para>
+              </entry>
+              <entry>
+                <para>'25%'</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>2534.1</para>
+              </entry>
+              <entry>
+                <para>float</para>
+              </entry>
+              <entry>
+                <para>formatFloat(total, '#,##0.###;-#,##0.###')
+                </para>
+              </entry>
+              <entry>
+                <para>'2,534.1'</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>1234</para>
+              </entry>
+              <entry>
+                <para>long</para>
+              </entry>
+              <entry>
+                <para>formatLong(amt, '0.###E0')</para>
+              </entry>
+              <entry>
+                <para>'1.234E3'</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>1234567</para>
+              </entry>
+              <entry>
+                <para>integer</para>
+              </entry>
+              <entry>
+                <para>formatInteger(total, '#,##0;-#,##0')
+                </para>
+              </entry>
+              <entry>
+                <para>'1,234,567'</para>
+              </entry>
+            </row>
+          </tbody>
+        </tgroup>
+      </informaltable>
+    </section>
+  </section>
+  <section id="string_functions">
+    <title>String Functions</title>
+    <para>String functions generally take strings as inputs and return strings as outputs. </para>
+    <para>Unless specified, all of the arguments and return types in the following table are strings and all indexes are 1-based. The 0 index is considered to be before the start of the string.</para>
+    <informaltable frame="all">
+      <tgroup cols="3">
+        <thead>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+            <entry>
+              <para>Datatype Constraint</para>
+            </entry>
+          </row>
+        </thead>
+        <tbody>
+          <row>
+            <entry>
+              <para>x || y</para>
+            </entry>
+            <entry>
+              <para>Concatenation operator</para>
+            </entry>
+            <entry>
+              <para>x,y in {string}, return type is string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>ASCII(x)</para>
+            </entry>
+            <entry>
+              <para>Provide ASCII value of the left most character in x.  The empty string will as input will return null. <footnoteref linkend="nonAscii"/></para>
+            </entry>
+            <entry>
+              <para>return type is integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>CHR(x) CHAR(x)</para>
+            </entry>
+            <entry>
+              <para>Provide the character for ASCII value x 
+              	<footnote id="nonAscii"><para>Non-ASCII range characters or integers used in these functions 
+              	may produce different results or exceptions depending on where the function is evalutated (Teiid vs. source).  
+              	Teiid's uses Java default int to char and char to int conversions, which operates over UTF16 values.</para></footnote>
+              </para>
+            </entry>
+            <entry>
+              <para>x in {integer}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>CONCAT(x, y)</para>
+            </entry>
+            <entry>
+              <para>Concatenates x and y with ANSI semantics. If
+                x and/or y is null, returns null.</para>
+            </entry>
+            <entry>
+              <para>x, y in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>CONCAT2(x, y)</para>
+            </entry>
+            <entry>
+              <para>Concatenates x and y with non-ANSI null
+                semantics. If x and y is null, returns null. If only x or y
+                is null, returns the other value.</para>
+            </entry>
+            <entry>
+              <para>x, y in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>INITCAP(x)</para>
+            </entry>
+            <entry>
+              <para>Make first letter of each word in string x capital
+                and all others lowercase</para>
+            </entry>
+            <entry>
+              <para>x in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>INSERT(str1, start, length, str2)</para>
+            </entry>
+            <entry>
+              <para>Insert string2 into string1</para>
+            </entry>
+            <entry>
+              <para>str1 in {string}, start in {integer}, length in
+                {integer}, str2 in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LCASE(x)</para>
+            </entry>
+            <entry>
+              <para>Lowercase of x</para>
+            </entry>
+            <entry>
+              <para>x in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LEFT(x, y)</para>
+            </entry>
+            <entry>
+              <para>Get left y characters of x</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LENGTH(x)</para>
+            </entry>
+            <entry>
+              <para>Length of x</para>
+            </entry>
+            <entry>
+              <para>return type is integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LOCATE(x, y)</para>
+            </entry>
+            <entry>
+              <para>Find position of x in y starting at beginning of y
+              </para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, return integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LOCATE(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Find position of x in y starting at z</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, z in {integer}, return
+                integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LPAD(x, y)</para>
+            </entry>
+            <entry>
+              <para>Pad input string x with spaces on the left to the
+                length of y</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {integer}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LPAD(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Pad input string x on the left to the length of y
+                using character z</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, z in {character}, return
+                string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>LTRIM(x)</para>
+            </entry>
+            <entry>
+              <para>Left trim x of white space</para>
+            </entry>
+            <entry>
+              <para>x in {string}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>QUERYSTRING(path [, expr [AS name] ...])</para>
+            </entry>
+            <entry>
+              <para>Returns a properly encoded query string appended to the given path.  Null valued expressions are omitted, and a null path is treated as ''.</para>
+              <para>Names are optional for column reference expressions.</para>
+              <para>e.g. QUERYSTRING('path', 'value' as "&amp;x", ' &amp; ' as y, null as z) returns 'path?%26x=value&amp;y=%20%26%20'</para>
+            </entry>
+            <entry>
+              <para>path, expr in {string}.  name is an identifier</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>REPEAT(str1,instances)</para>
+            </entry>
+            <entry>
+              <para>Repeat string1 a specified number of times</para>
+            </entry>
+            <entry>
+              <para>str1 in {string}, instances in {integer} return
+                string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>REPLACE(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Replace all y in x with z</para>
+            </entry>
+            <entry>
+              <para>x,y,z in {string}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>RIGHT(x, y)</para>
+            </entry>
+            <entry>
+              <para>Get right y characters of x</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>RPAD(input string x, pad length y)</para>
+            </entry>
+            <entry>
+              <para>Pad input string x with spaces on the right to the
+                length of y</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {integer}, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>RPAD(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Pad input string x on the right to the length of y
+                using character z</para>
+            </entry>
+            <entry>
+              <para>x in {string}, y in {string}, z in {character}, return
+                string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>RTRIM(x)</para>
+            </entry>
+            <entry>
+              <para>Right trim x of white space</para>
+            </entry>
+            <entry>
+              <para>x is string, return string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>SUBSTRING(x, y)</para>
+            </entry>
+            <entry>
+              <para>Get substring from x, from position y to the end of x
+              </para>
+            </entry>
+            <entry>
+              <para>y in {integer}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>SUBSTRING(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Get substring from x from position y with length z
+              </para>
+            </entry>
+            <entry>
+              <para>y, z in {integer}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TO_CHARS(x, encoding)</para>
+            </entry>
+            <entry>
+              <para>Return a clob from the blob with the given encoding.  
+              BASE64, HEX, and the builtin Java Charset names are valid values for the encoding.<footnote id="charset"><para>See the <ulink url="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html">Charset JavaDoc</ulink> for more on supported Charset names.  For charsets, unmappable chars will be replaced with the charset default character.  binary formats, such as BASE64, will error in their conversion to bytes is a unrecognizable character is encountered.</para></footnote></para>
+            </entry>
+            <entry>
+              <para>x is a blob, encoding is a string, and returns a clob</para>
+            </entry>
+          </row><row>
+            <entry>
+              <para id="to_bytes">TO_BYTES(x, encoding)</para>
+            </entry>
+            <entry>
+              <para>Return a blob from the clob with the given encoding.  
+              BASE64, HEX, and the builtin Java Charset names are valid values for the encoding.<footnoteref linkend="charset"/></para>
+            </entry>
+            <entry>
+              <para>x in a clob, encoding is a string, and returns a blob</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TRANSLATE(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Translate string x by replacing each character
+                in y with the character in z at the same position</para>
+            </entry>
+            <entry>
+              <para>x in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>UCASE(x)</para>
+            </entry>
+            <entry>
+              <para>Uppercase of x</para>
+            </entry>
+            <entry>
+              <para>x in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>UNESCAPE(x)</para>
+            </entry>
+            <entry>
+              <para>Unescaped version of x.  Possible escape sequences are \b - backspace, \t - tab, \n - line feed, \f - form feed, \r - carriage return.  \uXXXX, where X is a hex value, can be used to specify any unicode character.  \XXX, where X is an octal digit, can be used to specify an octal byte value.  
+              If any other character appears after an escape character, that character will appear in the output and the escape character will be ignored.</para>
+            </entry>
+            <entry>
+              <para>x in {string}</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+  </section>
+  <section id="date_time_functions">
+    <title>Date/Time Functions</title>
+    <para>Date and time functions return or operate on dates, times, or timestamps. </para>
+    <para>Parse and format Date/Time functions use the convention established within
+        the java.text.SimpleDateFormat class to define the formats you can
+        use with these functions. You can learn more about how this class
+        defines formats by visiting the Sun Java Web site
+        at the following
+        <ulink
+          url="http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html">URL for Sun Java</ulink>.
+    </para>
+    <informaltable frame="all">
+      <tgroup cols="3">
+        <thead>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+            <entry>
+              <para>Datatype Constraint</para>
+            </entry>
+          </row>        
+        </thead>
+        <tbody>
+          <row>
+            <entry>
+              <para>CURDATE()</para>
+            </entry>
+            <entry>
+              <para>Return current date</para>
+            </entry>
+            <entry>
+              <para>returns date</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>CURTIME()</para>
+            </entry>
+            <entry>
+              <para>Return current time</para>
+            </entry>
+            <entry>
+              <para>returns time</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>NOW()</para>
+            </entry>
+            <entry>
+              <para>Return current timestamp (date and time)</para>
+            </entry>
+            <entry>
+              <para>returns timestamp</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DAYNAME(x)</para>
+            </entry>
+            <entry>
+              <para>Return name of day</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DAYOFMONTH(x)</para>
+            </entry>
+            <entry>
+              <para>Return day of month</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DAYOFWEEK(x)</para>
+            </entry>
+            <entry>
+              <para>Return day of week (Sunday=1)</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DAYOFYEAR(x)</para>
+            </entry>
+            <entry>
+              <para>Return Julian day number</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>FORMATDATE(x, y)</para>
+            </entry>
+            <entry>
+              <para>Format date x using format y</para>
+            </entry>
+            <entry>
+              <para>x is date, y is string, returns string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>FORMATTIME(x, y)</para>
+            </entry>
+            <entry>
+              <para>Format time x using format y</para>
+            </entry>
+            <entry>
+              <para>x is time, y is string, returns string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>FORMATTIMESTAMP(x, y)</para>
+            </entry>
+            <entry>
+              <para>Format timestamp x using format y</para>
+            </entry>
+            <entry>
+              <para>x is timestamp, y is string, returns string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>FROM_UNIXTIME (unix_timestamp)</para>
+            </entry>
+            <entry>
+              <para>Return the Unix timestamp (in seconds) as a Timestamp value
+              </para>
+            </entry>
+            <entry>
+              <para>Unix timestamp (in seconds)</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>HOUR(x)</para>
+            </entry>
+            <entry>
+              <para>Return hour (in military 24-hour format)</para>
+            </entry>
+            <entry>
+              <para>x in {time, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>MINUTE(x)</para>
+            </entry>
+            <entry>
+              <para>Return minute</para>
+            </entry>
+            <entry>
+              <para>x in {time, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>MODIFYTIMEZONE (timestamp, startTimeZone,
+                endTimeZone)</para>
+            </entry>
+            <entry>
+              <para>Returns a timestamp based upon the incoming timestamp
+                adjusted for the differential between the start and end time
+                zones.  i.e. if the server is in GMT-6, then modifytimezone({ts
+                '2006-01-10 04:00:00.0'},'GMT-7', 'GMT-8') will return the
+                timestamp {ts '2006-01-10 05:00:00.0'} as read in GMT-6.  The
+                value has been adjusted 1 hour ahead to compensate for the
+                difference between GMT-7 and GMT-8.</para>
+            </entry>
+            <entry>
+              <para>startTimeZone and endTimeZone are strings,
+                returns a timestamp</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>MODIFYTIMEZONE (timestamp, endTimeZone)</para>
+            </entry>
+            <entry>
+              <para>Return a timestamp in the same manner as
+                modifytimezone(timestamp, startTimeZone, endTimeZone), but will
+                assume that the startTimeZone is the same as the server process.
+              </para>
+            </entry>
+            <entry>
+              <para>Timestamp is a timestamp; endTimeZone is a string,
+                returns a timestamp</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>MONTH(x)</para>
+            </entry>
+            <entry>
+              <para>Return month</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>MONTHNAME(x)</para>
+            </entry>
+            <entry>
+              <para>Return name of month</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>PARSEDATE(x, y)</para>
+            </entry>
+            <entry>
+              <para>Parse date from x using format y</para>
+            </entry>
+            <entry>
+              <para>x, y in {string}, returns date</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>PARSETIME(x, y)</para>
+            </entry>
+            <entry>
+              <para>Parse time from x using format y</para>
+            </entry>
+            <entry>
+              <para>x, y in {string}, returns time</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>PARSETIMESTAMP(x,y)</para>
+            </entry>
+            <entry>
+              <para>Parse timestamp from x using format y</para>
+            </entry>
+            <entry>
+              <para>x, y in {string}, returns timestamp</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>QUARTER(x)</para>
+            </entry>
+            <entry>
+              <para>Return quarter</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>SECOND(x)</para>
+            </entry>
+            <entry>
+              <para>Return seconds</para>
+            </entry>
+            <entry>
+              <para>x in {time, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TIMESTAMPCREATE(date, time)</para>
+            </entry>
+            <entry>
+              <para>Create a timestamp from a date and time</para>
+            </entry>
+            <entry>
+              <para>date in {date}, time in {time}, returns timestamp
+              </para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TIMESTAMPADD(interval, count,
+                timestamp)</para>
+            </entry>
+            <entry>
+              <para>Add a specified interval (hour, day of week, month)
+                to the timestamp, where intervals can have the following
+                definition:</para>
+              <orderedlist>
+                <listitem>
+                  <para>SQL_TSI_FRAC_SECOND - fractional
+                    seconds (billionths of a second)</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_SECOND - seconds</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_MINUTE - minutes</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_HOUR - hours</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_DAY - days</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_WEEK - weeks</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_MONTH - months</para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_QUARTER - quarters (3 months)
+                  </para>
+                </listitem>
+                <listitem>
+                  <para>SQL_TSI_YEAR - years</para>
+                </listitem>
+              </orderedlist>
+            </entry>
+            <entry>
+              <para>The interval constant may be specified either as a
+                string literal or a constant value. Interval in {string},
+                count in {integer}, timestamp in {date, time, timestamp}
+              </para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>TIMESTAMPDIFF(interval,
+                startTime, endTime)</para>
+            </entry>
+            <entry>
+              <para>Calculate the approximate number of whole
+                intervals in (endTime - startTime) using a specific interval
+                type (as defined by the constants in TIMESTAMPADD). If
+                (endTime &gt; startTime), a positive number will be returned. If (endTime &lt; startTime), a negative number will be returned. Calculations are approximate and may be less accurate over longer time spans.</para>
+            </entry>
+            <entry>
+              <para>Interval in {string}; startTime, endTime in {timestamp}, returns a long.</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>WEEK(x)</para>
+            </entry>
+            <entry>
+              <para>Return week in year</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>YEAR(x)</para>
+            </entry>
+            <entry>
+              <para>Return four-digit year</para>
+            </entry>
+            <entry>
+              <para>x in {date, timestamp}, returns integer</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+    <section>
+      <title>Parsing Date Datatypes from Strings</title>
+      <para>
+        Teiid does not implicitly convert strings that
+        contain dates presented in different formats, such as ‘19970101’ and
+        ‘31/1/1996’ to date-related datatypes. You can, however, use the
+        parseDate, parseTime, and parseTimestamp functions, described in the
+        next section, to explicitly convert strings with a different format
+        to the appropriate datatype. These functions use the convention
+        established within the java.text.SimpleDateFormat class to define
+        the formats you can use with these functions. You can learn more
+        about how this class defines date and time string formats by
+        visiting the
+        <ulink
+          url="http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html">Sun Java Web site</ulink>
+        .
+      </para>
+      <para>For example, you could use these function calls, with the
+        formatting string that adheres to the java.text.SimpleDateFormat
+        convention, to parse strings and return the datatype you need:
+      </para>
+      <informaltable frame="all">
+        <tgroup cols="2">
+          <thead>
+            <row>
+              <entry>
+                <para>String</para>
+              </entry>
+              <entry>
+                <para>Function Call To Parse String</para>
+              </entry>
+            </row>
+          </thead>
+          <tbody>
+            <row>
+              <entry>
+                <para>'1997010'</para>
+              </entry>
+              <entry>
+                <para>parseDate(myDateString, 'yyyyMMdd')</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'31/1/1996'</para>
+              </entry>
+              <entry>
+                <para>parseDate(myDateString, 'dd''/''MM''/''yyyy')</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'22:08:56 CST'</para>
+              </entry>
+              <entry>
+                <para>parseTime (myTime, 'HH:mm:ss z')</para>
+              </entry>
+            </row>
+            <row>
+              <entry>
+                <para>'03.24.2003 at 06:14:32'</para>
+              </entry>
+              <entry>
+                <para>parseTimestamp(myTimestamp, 'MM.dd.yyyy ''at'' hh:mm:ss')</para>
+              </entry>
+            </row>
+          </tbody>
+        </tgroup>
+      </informaltable>
+    </section>
+    <section>
+      <title>Specifying Time Zones</title>
+      <para>Time zones can be specified in several formats. Common
+        abbreviations such as EST for "Eastern Standard Time" are allowed
+        but discouraged, as they can be ambiguous. Unambiguous time zones
+        are defined in the form continent or ocean/largest city. For
+        example, America/New_York, America/Buenos_Aires, or Europe/London.
+        Additionally, you can specify a custom time zone by GMT offset:
+        GMT[+/-]HH:MM.</para>
+      <para>For example: GMT-05:00</para>
+    </section>
+  </section>
+  <section>
+    <title>Type Conversion Functions</title>
+    <para>
+    Within your queries, you can convert between datatypes using the
+    CONVERT or CAST keyword. See also <link linkend="type_conversions">Data Type Conversions</link>
+    .
+    </para>
+    <informaltable frame="all">
+      <tgroup cols="2">
+        <thead>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+          </row>
+        </thead>
+        <tbody>
+          <row>
+            <entry>
+              <para>CONVERT(x, type)</para>
+            </entry>
+            <entry>
+              <para>Convert x to type, where type is a Teiid
+                Base Type</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>CAST(x AS type)</para>
+            </entry>
+            <entry>
+              <para>Convert x to type, where type is a Teiid
+                Base Type</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+    <para>These functions are identical other than syntax; CAST is the standard SQL syntax, CONVERT is the standard JDBC/ODBC syntax. </para>
+  </section>
+  <section id="choice_functions">
+    <title>Choice Functions</title>
+    <para>Choice functions provide a way to select from two values based on some characteristic of one of the values. </para>
+    <informaltable frame="all">
+      <tgroup cols="3">
+        <tbody>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+            <entry>
+              <para>Datatype Constraint</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>COALESCE(x,y+)</para>
+            </entry>
+            <entry>
+              <para>Returns the first non-null parameter</para>
+            </entry>
+            <entry>
+              <para>x and all y's can be any compatible types</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>IFNULL(x,y)</para>
+            </entry>
+            <entry>
+              <para>If x is null, return y; else return x</para>
+            </entry>
+            <entry>
+              <para>x, y, and the return type must be the same type but
+                can be any type</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>NVL(x,y)</para>
+            </entry>
+            <entry>
+              <para>If x is null, return y; else return x</para>
+            </entry>
+            <entry>
+              <para>x, y, and the return type must be the same type but
+                can be any type</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>NULLIF(param1, param2)</para>
+            </entry>
+            <entry>
+              <para>Equivalent to case when (param1 = param2) then null else param1</para>
+            </entry>
+            <entry>
+              <para>param1 and param2 must be compatable comparable types</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+    <para>IFNULL and NVL are aliases of each other. They are the same function. </para>
+  </section>
+  <section>
+    <title>Decode Functions</title>
+    <para>Decode functions allow you to have the Teiid Server
+      examine the contents of a column in a result set and alter, or
+      decode, the value so that your application can better use the
+      results.</para>
+    <informaltable frame="all">
+      <tgroup cols="3">
+        <thead>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+            <entry>
+              <para>Datatype Constraint</para>
+            </entry>
+          </row>
+        </thead>
+        <tbody>
+          <row>
+            <entry>
+              <para>DECODESTRING(x, y)</para>
+            </entry>
+            <entry>
+              <para>Decode column x using string of value pairs y
+                and return the decoded column as a string</para>
+            </entry>
+            <entry>
+              <para>all string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DECODESTRING(x, y, z)</para>
+            </entry>
+            <entry>
+              <para>Decode column x using string of value pairs y
+                with delimiter z and return the decoded column as a string
+              </para>
+            </entry>
+            <entry>
+              <para>all string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DECODEINTEGER(x, y)</para>
+            </entry>
+            <entry>
+              <para>Decode column x using string of value pairs y
+                and return the decoded column as an integer</para>
+            </entry>
+            <entry>
+              <para>all string parameters, return integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para>DECODEINTEGER(x,y,z)</para>
+            </entry>
+            <entry>
+              <para>Decode column x using string of value pairs y
+                with delimiter z and return the decoded column as an
+                integer</para>
+            </entry>
+            <entry>
+              <para>all string parameters, return integer</para>
+            </entry>
+          </row>
+        </tbody>
+      </tgroup>
+    </informaltable>
+    <para>Within each function call, you include the following arguments:</para>
+    <orderedlist>
+      <listitem>
+        <para>x is the input value for the decode operation. This will
+          generally be a column name.</para>
+      </listitem>
+      <listitem>
+        <para>y is the literal string that contains a delimited set of
+          input values and output values.</para>
+      </listitem>
+      <listitem>
+        <para>z is an optional parameter on these methods that allows you
+          to specify what delimiter the string specified in y uses.</para>
+      </listitem>
+    </orderedlist>
+    <para>For example, your application might query a table called
+      PARTS that contains a column called IS_IN_STOCK which contains a
+      Boolean value that you need to change into an integer for your
+      application to process. In this case, you can use the DECODEINTEGER
+      function to change the Boolean values to integers:</para>
+    <programlisting>SELECT DECODEINTEGER(IS_IN_STOCK, 'false, 0, true, 1') FROM PartsSupplier.PARTS;</programlisting> 
+    <para>When the Teiid System encounters the value false in the
+      result set, it replaces the value with 0.</para>
+    <para>If, instead of using integers, your application requires
+      string values, you can use the DECODESTRING function to return the
+      string values you need:</para>
+    <programlisting>SELECT DECODESTRING(IS_IN_STOCK, 'false, no, true, yes, null') FROM PartsSupplier.PARTS;</programlisting>
+    <para>In addition to two input/output value pairs, this sample query
+      provides a value to use if the column does not contain any of the
+      preceding input values. If the row in the IS_IN_STOCK column does
+      not contain true or false, the Teiid Server inserts a null into
+      the result set.</para>
+    <para>When you use these DECODE functions, you can provide as many
+      input/output value pairs if you want within the string. By default,
+      the Teiid System expects a comma delimiter, but you can add a
+      third parameter to the function call to specify a different
+      delimiter:</para>
+    <programlisting>SELECT DECODESTRING(IS_IN_STOCK, 'false:no:true:yes:null',’:’) FROM PartsSupplier.PARTS;</programlisting>
+    <para>You can use keyword null in the DECODE string as either an
+      input value or an output value to represent a null value. However,
+      if you need to use the literal string null as an input or output
+      value (which means the word null appears in the column and not a
+      null value) you can put the word in quotes: "null".</para>
+    <programlisting>SELECT DECODESTRING( IS_IN_STOCK, 'null,no,"null",no,nil,no,false,no,true,yes' ) FROM PartsSupplier.PARTS;</programlisting>
+    <para>If the DECODE function does not find a matching output value
+      in the column and you have not specified a default value, the DECODE
+      function will return the original value the Teiid Server found
+      in that column.</para>
+  </section>
+  <section>
+    <title>Lookup Function</title>
+    <para>The Lookup function allows you to cache a key value pair table and access it through a scalar function. This caching
+    accelerates response time to queries that use the lookup tables, known
+    in business terminology as lookup tables or code tables.</para>
+    <para><synopsis>LOOKUP(codeTable, returnColumn, keyColumn, keyValue)</synopsis></para>
+    <para>In the lookup table codeTable, find the row where
+      keyColumn has the value keyValue and return the
+      associated returnColumn. codeTable must be a fully-qualified string
+      literal containing metadata identifiers, keyValue datatype
+      must match datatype of the keyColumn, return datatype
+      matches that of returnColumn. returnColumn and
+      keyColumn parameters should use their shortened names.
+    </para>
+    <para>For example, a StatePostalCodes table used to translate postal codes to
+      complete state names might represent an example of this type of
+      lookup table. One column, PostalCode, represents a key column.
+      Other tables refer to this two-letter code. A
+      second column, StateDisplayName, would represent the complete name
+      of the state. Hence, a query to this lookup table would typically
+      provide the PostalCode and expect the StateDisplayName in response.
+    </para>
+    <para>When you call this function for any combination of codeTable, returnColumn, and
+      keyColumn for the first time, the Teiid System caches the result. 
+      The Teiid System uses this cache for all
+      queries, in all sessions, that later access this lookup table.</para>
+    <para>The Teiid System unloads these cached lookup tables when you stop and restart
+      the Teiid System. Thus, you should not use this function for
+      data that is subject to updates. Instead, you can use it against
+      static data that does not change over time.</para>
+    <note>
+      <itemizedlist>
+        <listitem>
+          <para>The keyColumn is expected to contain unique
+            values. If the column contains duplicate values, an exception will be thrown.</para>
+        </listitem>
+      </itemizedlist>
+    </note>
+  </section>
+  <section>
+    <title>System Functions</title>
+    <para>System functions provide access to information in the Teiid system from within a query. </para>
+    <informaltable frame="all">
+      <tgroup cols="3">
+        <thead>
+          <row>
+            <entry>
+              <para>Function</para>
+            </entry>
+            <entry>
+              <para>Definition</para>
+            </entry>
+            <entry>
+              <para>Datatype Constraint</para>
+            </entry>
+          </row>
+        </thead>
+        <tbody>
+          <row>
+            <entry>
+              <para><code>COMMANDPAYLOAD()</code></para>
+            </entry>
+            <entry>
+              <para>Retrieve the string form of the command payload
+                or null if no command payload was specified. The command
+                payload is set by a method on the Teiid JDBC API
+                extensions on a per-query basis.</para>
+            </entry>
+            <entry>
+              <para>Returns a string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para><code>COMMANDPAYLOAD(key)</code></para>
+            </entry>
+            <entry>
+              <para>Cast the command payload object to a
+                java.util.Properties object and look up the specified key in
+                the object</para>
+            </entry>
+            <entry>
+              <para>key in {string}, return is string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para><code>ENV(key)</code></para>
+            </entry>
+            <entry>
+              <para>Retrieve a system environment property. The only key specific to the current session is ‘sessionid’.  
+                However the preferred mechanism for getting the session id is with the session_id() function.  
+                To prevent untrusted access to system properties, the use of this function must be specifically enabled in the &jboss-beans; file.
+                </para>
+            </entry>
+            <entry>
+              <para>key in {string}, return is string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para><code>SESSION_ID()</code></para>
+            </entry>
+            <entry>
+              <para>Retrieve the string form of the current session id.</para>
+            </entry>
+            <entry>
+              <para>return is string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para><code>USER()</code></para>
+            </entry>
+            <entry>
+              <para>Retrieve the name of the user executing the
+                query</para>
+            </entry>
+            <entry>
+              <para>return is string</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
+              <para><code>CURRENT_DATABASE()</code></para>
+            </entry>
+            <entry>
+              <para>Retrieve the catalog name of the database. Currently VDB's name is also the catalog name.</para>
+            </entry>
+            <entry>
+              <para>return is string</para>
+            </entry>
+          </row>          
+        </tbody>
+      </tgroup>
+    </informaltable>
+  </section>
+  <section id="xml_functions">
+    <title>XML Functions</title>
+    <para>XML functions provide functionality for working with XML data. </para>
+    <section>
+    	<title>JSONTOXML</title>
+    	<para>Returns an xml document from JSON.</para>
+        <para><synopsis>JSONTOXML(rootElementName, json)</synopsis></para>
+        <para>rootElementName is a string, json is in {clob, blob}. Return value is xml.</para>
+        <para>The appropriate UTF encoding (8, 16LE. 16BE, 32LE, 32BE) will be detected for JSON blobs.  If another encoding is used, see the to_chars function.</para>
+        <para>The result is always a well-formed XML document.</para>
+        <para>The mapping to XML uses the following rules:
+        <itemizedlist>
+        	<listitem>
+        		<para>The current element name is initially the rootElementName, and becomes the object value name as the JSON structure is traversed.</para>
+        	</listitem>
+        	<listitem>
+        		<para>All element names must be valid xml 1.1 names.  Invalid names are fully escaped according to the SQLXML specification.</para>
+        	</listitem>
+        	<listitem>
+        		<para>Each object or primitive value will be enclosed in an element with the current name.</para>
+        	</listitem>
+        	<listitem>
+        		<para>Unless an array value is the root, it will not be enclosed in an additional element.</para>
+        	</listitem>
+        </itemizedlist> 
+        </para>
+        <example>
+        	<title>Sample JSON to XML for jsonToXml('person', x)</title>
+        	<para>JSON:</para>
+        	<programlisting language="JSON">{ "firstName" : "John" , "children" : [ "Randy", "Judy" ] }</programlisting>
+        	<para>XML:</para>
+        	<programlisting language="XML"><![CDATA[<?xml version="1.0" ?><person><firstName>John</firstName><children>Randy</children><children>Judy<children></person>]]></programlisting>
+        </example>
+        <example>
+        	<title>Sample JSON to XML for jsonToXml('person', x) with a root array.</title>
+        	<para>JSON:</para>
+        	<programlisting language="JSON">[{ "firstName" : "George" }, { "firstName" : "Jerry" }]</programlisting>
+        	<para>XML (Notice there is an extra "person" wrapping element to keep the XML well-formed):</para>
+        	<programlisting language="XML"><![CDATA[<?xml version="1.0" ?><person><person><firstName>George</firstName></person><person><firstName>Jerry</firstName></person></person>]]></programlisting>
+        </example>
+    </section>
+    <section>
+    	<title>XMLCOMMENT</title>
+    	<para>Returns an xml comment.</para>
+    	<para><synopsis>XMLCOMMENT(comment)</synopsis></para>
+    	<para>Comment is a string.  Return value is xml.</para>
+    </section>
+    <section>
+    	<title>XMLCONCAT</title>
+    	<para>Returns an XML with the concatination of the given xml types.</para>
+    	<para><synopsis>XMLCONCAT(content [, content]*)</synopsis></para>
+    	<para>Content is xml. Return value is xml.</para>
+    	<para>If a value is null, it will be ignored.  If all values are null, null is returned.</para>
+    </section>
+    <section>
+    	<title>XMLELEMENT</title>
+    	<para>Returns an XML element with the given name and content.</para>
+    	<para><synopsis>XMLELEMENT([NAME] name [, &lt;NSP&gt;] [, &lt;ATTR&gt;][, content]*)</synopsis></para>
+          <para><synopsis>ATTR:=XMLATTRIBUTES(exp [AS name] [, exp [AS name]]*)</synopsis></para>
+          <para><synopsis>NSP:=XMLNAMESPACES((uri AS prefix | DEFAULT uri | NO DEFAULT))+</synopsis></para>
+          <para>If the content value is of a type other than xml, it will be escaped when added to the parent element.  Null content values are ignored.  
+          Whitespace in XML or the string values of the content is preserved, but no whitespace is added between content values.</para>
+          <para id="xmlnamespaces">XMLNAMESPACES is used provide namespace information.  NO DEFAULT is equivalent to defining the default namespace to the null uri - xmlns="".  
+          Only one DEFAULT or NO DEFAULT namespace item may be specified.  The namespace prefixes xmlns and xml are reserved.</para>
+          <para>If a attribute name is not supplied, the expression must be a column reference, in which case the attribute name will be the column name. Null attribute values are ignored.</para>
+		<para>Name, prefix are identifiers. uri is a string literal. content can be any type. Return value is xml.  The return value is valid for use in places where a document is expected.</para>            
+           <para><emphasis>Example</emphasis>: with an xml_value of &lt;doc/&gt;, <programlisting>xmlelement('elem', 1, '&lt;2/&gt;', xml_value)</programlisting>
+           		Returns: <code>&lt;elem&gt;1&amp;lt;2/&amp;gt;&lt;doc/&gt;&lt;elem/&gt;</code>
+           </para>
+    </section>
+    <section>
+    	<title>XMLFOREST</title>
+    	<para>Returns an concatination of XML elements for each content item.</para>
+    	<para><synopsis>XMLFOREST(content [AS name] [, &lt;NSP&gt;] [, content [AS name]]*)</synopsis></para>
+        <para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para>
+   		<para>Name is an identifier. Content can be any type. Return value is xml.</para>
+		<para>If a name is not supplied for a content item, the expression must be a column reference, in which case the element name will be a partially escaped version of the column name.</para>
+    </section>
+    <section id="xmlparse">
+    	<title>XMLPARSE</title>
+    	<para>Returns an XML type representation of the string value expression.</para>
+        <para><synopsis>XMLPARSE((DOCUMENT|CONTENT) expr [WELLFORMED])</synopsis></para>
+        <para>expr in {string, clob, blob}. Return value is xml.</para>
+        <para>If DOCIMENT is specfied then the expression must have a single
+        root element and may or may not contain an XML declaration.</para>
+        <para>
+              If WELLFORMED is specified then validation is skipped; this is especially useful for CLOB and BLOB known to already be valid.  
+        </para>
+    </section>
+    <section>
+    	<title>XMLPI</title>
+    	<para>Returns an xml processing instruction.</para>
+        <para><synopsis>XMLPI([NAME] name [, content])</synopsis></para>
+        <para>Name is an identifier. Content is a string. Return value is xml.</para>
+    </section>
+    <section id="xmlquery">
+    	<title>XMLQUERY</title>
+    	<para>Returns the XML result from evaluating the given xquery.</para>
+    	<para><synopsis>XMLQUERY([&lt;NSP&gt;] xquery [&lt;PASSING&gt;] [(NULL|EMPTY) ON EMPTY]]</synopsis></para>
+    	<para><synopsis>PASSING:=PASSING exp [AS name] [, exp [AS name]]*</synopsis></para>
+    	<para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para><para>Namespaces may also be directly declared in the xquery prolog.</para>
+             <para id="passing">The optional PASSING clause is used to provide the context item, which does not have a name, and named global variable values.  
+             If the xquery uses a context item and none is provided, then an exception will be raised.  
+             Only one context item may be specified and should be an XML type.  All non-context non-XML passing values will be converted to an appropriate XML type.</para>
+             <para>The ON EMPTY clause is used to specify the result when the evaluted sequence is empty.  
+             EMPTY ON EMPTY, the default, returns an empty XML result.  NULL ON EMPTY returns a null result.</para>
+             <para>xquery in string. Return value is xml.</para>
+             <para>XMLQUERY is part of the SQL/XML 2006 specification.</para>
+             <para>See also <link linkend="xmltable">XMLTABLE</link></para>
+             <note><para>A technique known as document projection is used to reduce the memory footprint of the context item document.  
+             Only the parts of the document needed by the XQuery path expressions will be loaded into memory.  Since document projection analysis uses all relevant path expressions, even 1 expression that could potentially use many nodes, e.g. //x rather than /a/b/x will cause a larger memory footprint.</para></note>
+             
+    </section>
+    <section id="xmlserialize">
+    	<title>XMLSERIALIZE</title>
+    	<para>Returns a character type representation of the xml expression.</para>
+        <para><synopsis>XMLSERIALIZE([(DOCUMENT|CONTENT)] xml [AS datatype])</synopsis></para>
+        <para>Return value mathces datatype.</para>
+		<para>Only a character type (string, varchar, clob) may be specified as the datatype.  CONTENT is the default.  
+              If DOCUMENT is specified and the xml is not a valid document or fragment, then an exception is raised. 
+              </para>
+    </section>
+    <section>
+    	<title>XSLTRANSFORM</title>
+    	<para>Applies an XSL stylesheet to the given document.</para>
+    	<para><synopsis>XSLTRANSFORM(doc, xsl)</synopsis></para>
+    	<para>Doc, xsl in {string, clob, xml}. Return value is a clob.</para>
+    	<para>If either argument is null, the result is null.</para>
+    </section>
+    <section>
+    	<title>XPATHVALUE</title>
+    	<para>Applies the XPATH expression to the document and returns a
+               string value for the first matching result.</para>
+    	<para><synopsis>XPATHVALUE(doc, xpath)</synopsis></para>
+    	<para>Doc and xpath in {string, clob, xml}. Return value is a string.</para>
+    	<para>An attempt is made to provide a meaningful result for non-text nodes.</para>
+    </section>
+  </section>
+  <section>
+    <title>Security Functions</title>
+    <para>Security functions provide the ability to interact
+    with the security system.</para>
+    <section>
+    	<title>HASROLE</title>
+    	<para>Whether the current caller has the role roleName.</para>
+    	<para><synopsis>hasRole([roleType,] roleName)</synopsis></para>
+        <para>roleName must be a string, the return type is boolean.</para>
+        <para>The two argument form is provided for backwards compatibility. roleType is a string and must be 'data'</para>
+    </section>
+  </section>
+  <section id="nondeterministic_functions">
+  	<title>Nondeterministic Function Handling</title>
+	<para>Teiid categorizes functions by varying degrees of determinism.
+		When a function is evaluated and to what extent the result can be
+		cached are based upon its determinism level.</para>
+  	<orderedlist>
+		<listitem>
+			<para>Deterministic - the function will always return the same result
+				for the given inputs. Deterministic functions are evaluated by the
+				engine as soon as all input values are known, which may occur as soon
+				as the rewrite phase. Some functions, such as the lookup function, are
+				not truly deterministic, but is treated as such for performance. All
+				functions not categorized below are considered deterministic.</para>
+		</listitem>
+		<listitem>
+			<para>User Deterministic - the function will return the same
+				result for the given inputs for the same user. This includes the hasRole
+				and user functions. User deterministic functions are evaluated
+				by the engine as soon as all input values are known, which may occur as soon
+				as the rewrite phase. If a user deterministic function is evaluated
+				during the creation of a prepared processing plan, then the resulting
+				plan will be cached only for the user.</para>
+		</listitem>
+		<listitem>
+			<para>Session Deterministic - the function will return the same
+				result for the given inputs under the same user session. This category includes the env
+				function. Session deterministic functions are evaluated
+				by the engine as soon as all input values are known, which may occur as soon
+				as the rewrite phase. If a session deterministic function is evaluated
+				during the creation of a prepared processing plan, then the resulting
+				plan will be cached only for the user's session.</para>
+		</listitem>
+		<listitem>
+			<para>Command Deterministic - the result of function evaluation is
+				only deterministic within the scope of the user command. This category
+				include the curdate, curtime, now, and commandpayload functions.
+				Command deterministic functions are delayed in evaluation until
+				processing to ensure that even prepared plans utilizing these
+				functions will be executed with relevant values. Command deterministic function
+				evaulation will occur prior to pushdown - however multiple occurances
+				of the same command deterministic time function are not guarenteed to
+				evaluate to the same value. </para>
+		</listitem>
+		<listitem>
+			<para>Nondeterministic - the result of function evaluation is fully
+				nondeterministic. This category includes the rand function and UDFs
+				marked as nondeterministic. Nondeterministic functions are delayed in
+				evaluation until processing with a preference for pushdown. If the
+				function is not pushed down, then it may be evaluated for every row in
+				it's execution context (for example if the function is used in the
+				select clause).</para>
+		</listitem>
+  	</orderedlist>
+  </section>
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/translators.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1291 +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="translators">
-    <title>Translators</title>
-
-    <section>
-        <title>Introduction to the Teiid Connector Architecture</title>
-        <para>
-        The Teiid Connector Architecture (TCA) provides Teiid with a robust mechanism 
-        for integrating with external systems.  The TCA defines a common client interface 
-        between Teiid and an external system that includes metadata as to what SQL 
-        constructs are supported for pushdown and the ability to import metadata from 
-        the external system.
-        </para>
-        
-        <para>
-        A Translator is the heart of the TCA and acts as the bridge logic between Teiid 
-        and an external system, which is most commonly accessed through a JCA resource 
-        adapter.  Refer to the Teiid Developers Guide for details on developing custom 
-        Translators and JCA resource adapters for use with Teiid.
-        </para>
-        
-        <note>
-            <para>
-            The TCA is not the same as the JCA, the JavaEE Connector Architecture, although 
-            the TCA is designed for use with JCA resource adapters.
-            </para>
-        </note>
-        
-        <note>
-            <para>
-            The import capabilities of Teiid Translators is currently only used in 
-            <link linkend="dynamic_vdbs">dynamic VDBs</link> and not by the Teiid Designer.
-            </para>
-        </note>
-        
-    </section>
-
-    <section>
-        <title>Translators</title>
-        <para>
-        A Translator is typically paired with a particular JCA resource adapter.  In 
-        instances where pooling, environment dependent configuration management, advanced 
-        security handling, etc. are not needed, then a JCA resource adapter is not needed.  
-        The configuration of JCA ConnectionFactories for needed resource adapters is not 
-        part of this guide, please see the Teiid Administrator Guide and the kit examples 
-        for configuring resource adapters for use in JBossAS.
-        </para>
-        
-        <para>
-        Translators can have a number of configurable properties.  These are broken down 
-        into execution properties, which determine aspects of how data is retrieved, and 
-        import settings, which determine what metadata is read for import.
-        </para>
-        
-        <para>
-        The execution properties for a translator typically have reasonable defaults.  For 
-        specific translator types, e.g. the Derby translator, base execution properties are 
-        already tuned to match the source.  In most cases the user will not need to adjust 
-        their values.
-        </para>
-
-        <table>
-            <title>Base Execution Properties - shared by all translators</title>
-            <tgroup cols="3">
-                <colspec colwidth="3*" />
-                <colspec colwidth="6*" />
-                <colspec colwidth="2*" />
-                <thead>
-                    <row>
-                        <entry>Name</entry>
-                        <entry>Description</entry>
-                        <entry>Default</entry>
-                    </row>
-                </thead>
-                <tbody>
-                    <row>
-                        <entry>Immutable</entry>
-                        <entry>Set to true to indicate that the source never changes.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>RequiresCriteria</entry>
-                        <entry>Set to true to indicate that source SELECT/UPDATE/DELETE queries require a where clause.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>SupportsOrderBy</entry>
-                        <entry>Set to true to indicate that the ORDER BY clause is supported.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>SupportsOuterJoins</entry>
-                        <entry>Set to true to indicate that OUTER JOINs are supported.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>SupportsFullOuterJoins</entry>
-                        <entry>If outer joins are supported, true indicates that FULL OUTER JOINs are supported.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>SupportsInnerJoins</entry>
-                        <entry>Set to true to indicate that INNER JOINs are supported.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>SupportedJoinCriteria</entry>
-                        <entry>If joins are supported, defines what criteria may be used as the join criteria.  May be one of (ANY, THETA, EQUI, or KEY).</entry>
-                        <entry>ANY</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-        
-        <note>
-            <para>
-            Only a subset of the metadata as to what SQL constructs the source supports 
-            can be set through execution properties.  If more control is needed, please 
-            consult the Teiid Developers Guide.
-            </para>
-        </note>
-        
-        <para>There are no base importer settings.</para>
-
-        <section>
-            <title>File Translator</title>
-            <para>
-            The file translator, known by the type name <emphasis>file</emphasis>, exposes 
-            stored procedures to leverage file system resources exposed by the file resource 
-            adapter. It will commonly be used with the <link linkend="texttable">TEXTTABLE</link> 
-            or <link linkend="xmltable">XMLTABLE</link> table functions to use CSV or XML 
-            formated data.
-            </para>
-
-            <table>
-                <title>Execution Properties</title>
-                <tgroup cols="3">
-                    <colspec colwidth="1*" />
-                    <colspec colwidth="4*" />
-                    <colspec colwidth="1*" />
-                    <thead>
-                        <row>
-                            <entry>Name</entry>
-                            <entry>Description</entry>
-                            <entry>Default</entry>
-                        </row>
-                    </thead>
-                    <tbody>
-                        <row>
-                            <entry>Encoding</entry>
-                            <entry>The encoding that should be used for CLOBs returned by the getTextFiles procedure</entry>
-                            <entry>The system default encoding</entry>
-                        </row>
-                    </tbody>
-                </tgroup>
-            </table>
-            
-            <para>There are file importer settings, but it does provide metadata for dynamic vdbs.</para>
-            
-            <section>
-                <title>Usage</title>
-                <para>
-                Retrieve all files as BLOBs with the given extension at the given path.
-                </para>
-                
-                <programlisting>call getFiles('path/*.ext')</programlisting>
-                
-                <para>
-                If the extension pattern is not specified and the path is a directory, 
-                then all files in the directory will be returned.  If the path or filename 
-                doesn't exist, then no results will be returned.
-                </para>
-                
-                <para>
-                Retrieve all files as CLOBs with the given extension at the given path.
-                </para>
-                <programlisting>call getTextFiles('path/*.ext')</programlisting>
-                
-                <para>
-                Save the CLOB, BLOB, or XML file to given path
-                </para>
-                <programlisting>call saveFile('path', value)</programlisting>
-                
-                <para>
-                See the database metadata for full descriptions of the getFiles, 
-                getTextFiles, and saveFile procedures.
-                </para>
-            </section>
-
-        </section>
-        
-        <section>
-            <title>JDBC Translator</title>
-            <para>
-            The JDBC translator bridges between SQL semantic and data type difference 
-            between Teiid and a target RDBMS.  Teiid has a range of specific translators 
-            that target the most popular open source and proprietary databases.
-            </para>
-
-            <itemizedlist>
-                <title>Type names:</title>
-                <listitem>
-                    <para>
-                    <emphasis>jdbc-ansi</emphasis> - declares support for most SQL 
-                    constructs supported by Teiid, except for row limit/offset and 
-                    EXCEPT/INTERCECT.  Translates source SQL into ANSI compliant syntax.  
-                    This translator should be used when another more specific type is 
-                    not available.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>jdbc-simple</emphasis> - same as jdbc-ansi, except disables 
-                    support for function, UNION, and aggregate pushdown.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>db2</emphasis> - for use with DB2 8 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>derby</emphasis> - for use with Derby 10.1 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>h2</emphasis> - for use with H2 version 1.1 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>hsql</emphasis> - for use with HSQLDB 1.7 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>informix</emphasis> - for use with any version.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>metamatrix</emphasis> - for use with MetaMatrix 5.5.0 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>mysql</emphasis>/<emphasis>mysql5</emphasis> - for use with 
-                    MySQL version 4.x and 5 or later respectively.  
-                    </para>
-                    <para>
-                    The MySQL Translators expect the database or session to be using ANSI 
-                    mode.  If the database is not using ANSI mode, an initialization query 
-                    should be used on the pool to set ANSI mode:  
-                    </para>
-                    <programlisting>set SESSION sql_mode = 'ANSI'</programlisting>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>oracle</emphasis> - for use with Oracle 9i or later.  
-                    Sequences may be used with the Oracle translator. A sequence may be 
-                    modeled as a table with a name in source of DUAL and columns with the 
-                    name in source set to <code>&lt;sequencesequence name&gt;.[nextval|currentval].</code>  
-                    You can use a sequence as the default value for insert columns by 
-                    setting the column to autoincrement and the name in source to 
-                    <code>&lt;element name&gt;:SEQUENCE=&lt;sequence name&gt;.&lt;sequence value&gt;</code>.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>postgresql</emphasis> - for use with 8.0 or later clients 
-                    and 7.1 or later server.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>sybase</emphasis> - for use with Sybase version 12.5 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>teiid</emphasis> - for use with Teiid 6.0 or later.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>teradata</emphasis> - for use with Teradata V2R5.1 or later.
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-            <table>
-                <title>Execution Properties - shared by all JDBC Translators</title>
-                <tgroup cols="3">
-                    <colspec colwidth="3*" />
-                    <colspec colwidth="6*" />
-                    <colspec colwidth="2*" />
-                    <thead>
-                        <row>
-                            <entry>Name</entry>
-                            <entry>Description</entry>
-                            <entry>Default</entry>
-                        </row>
-                    </thead>
-                    <tbody>
-                    <row>
-                        <entry>DatabaseTimeZone</entry>
-                        <entry>The time zone of the database.  Used when fetchings date, time, or timestamp values.</entry>
-                        <entry>The system default time zone</entry>
-                    </row>
-                    <row>
-                        <entry>DatabaseVersion</entry>
-                        <entry>The specific database version.  Used to further tune pushdown support.</entry>
-                        <entry>The base supported version</entry>
-                    </row>
-                    <row>
-                        <entry>TrimStrings</entry>
-                        <entry>true to trim trailing whitespace from fixed length character strings.  Note that Teiid only has a string, or varchar, type that treats trailing whitespace as meaningful.</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>UseBindVariables</entry>
-                        <entry>true to indicate that PreparedStatements should be used and that literal values in the source query should be replace with bind variables.  If false only LOB values will trigger the use of PreparedStatements.</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>UseCommentsInSourceQuery</entry>
-                        <entry>This will embed a /*comment*/ leading comment with session/request id in source SQL query for informational purposes</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>MaxPreparedInsertBatchSize</entry>
-                        <entry>The max size of a prepared insert batch.</entry>
-                        <entry>2048</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-            
-        <table>
-            <title>Importer Properties - shared by all JDBC Translators</title>
-            <tgroup cols="3">
-            <colspec colwidth="3*" />
-            <colspec colwidth="6*" />
-            <colspec colwidth="2*" />
-                <thead>
-                    <row>
-                        <entry>Name</entry>
-                        <entry>Description</entry>
-                        <entry>Default</entry>
-                    </row>
-                </thead>
-                <tbody>
-                    <row>
-                        <entry>catalog</entry>
-                        <entry>See DatabaseMetaData.getTables<footnote label="1" id="dbmd"><para>Full JavaDoc for <ulink url="http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html">DatabaseMetaData</ulink></para></footnote></entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>schemaPattern</entry>
-                        <entry>See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>tableNamePattern</entry>
-                        <entry>See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>procedurePatternName</entry>
-                        <entry>See DatabaseMetaData.getProcedures<footnoteref linkend="dbmd"/></entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>tableTypes</entry>
-                        <entry>Comma separated list - without spaces - of imported table types.  See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>useFullSchemaName</entry>
-                        <entry>When false, directs the importer to drop the source catalog/schema from the Teiid object name, so that the Teiid fully qualified name will be in the form of &lt;model name&gt;.&lt;table name&gt; - Note: that this may lead to objects with duplicate names when importing from multiple schemas, which results in an exception</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>importKeys</entry>
-                        <entry>true to import primary and foriegn keys</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>importIndexes</entry>
-                        <entry>true to import index/unique key/cardinality information</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>importApproximateIndexes</entry>
-                        <entry>true to import approximate index information.  See DatabaseMetaData.getIndexInfo<footnoteref linkend="dbmd"/></entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>importProcedures</entry>
-                        <entry>true to import procedures and procedure columns - Note that it is not always possible to import procedure result set columns due to database limitations.  It is also not currently possible to import overloaded procedures.</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>widenUnsignedTypes</entry>
-                        <entry>true to convert unsigned types to the next widest type.  For example SQL Server reports tinyint as an unsigned type.  With this option enabled, tinyint would be imported as a short instead of a byte.</entry>
-                        <entry>true</entry>
-                    </row>
-                    <row>
-                        <entry>quoteNameInSource</entry>
-                        <entry>false will override the default and direct Teiid to create source queries using unquoted identifiers.</entry>
-                        <entry>true</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-
-        <warning>
-            <para>
-            The default import settings will crawl all available metadata.  This import 
-            process is time consuming and full metadata import is not needed in most 
-            situations.  Most commonly you'll want to limit import by schemaPattern 
-            and tableTypes.
-            </para>
-        </warning>
-
-        <para>
-        Example importer settings to only import tables and views from my-schema.
-        </para>
-        <programlisting language="XML" role="XML"><![CDATA[...
-<property name="importer.tableTypes" value="TABLE,VIEW"/>
-<property name="importer.schemaPattern" value="my-schema"/>
-...]]></programlisting>
-
-        <section>
-            <title>Usage</title>
-            <para>
-            Usage of a JDBC source is straight-forward.  Using Teiid SQL, the source may be 
-            queried as if the tables and procedures were local to the Teiid system.
-            </para>
-        </section>
-        
-    </section>
-    
-    <section>
-        <title>LDAP Translator</title>
-        <para>
-        The LDAP translator, known by the type name <emphasis>ldap</emphasis>, exposes an 
-        LDAP directory tree relationally with pushdown support for filtering via criteria.  
-        This is typically coupled with the LDAP resource adapter.
-        </para>
-        
-        <table>
-            <title>Execution Properties</title>
-            <tgroup cols="3">
-                <thead>
-                    <row>
-                        <entry>Name</entry>
-                        <entry>Description</entry>
-                        <entry>Default</entry>
-                    </row>
-                </thead>
-                <tbody>
-                    <row>
-                        <entry>SearchDerfaultBaseDN</entry>
-                        <entry>Default Base DN for LDAP Searches</entry>
-                        <entry>null</entry>
-                    </row>
-                    <row>
-                        <entry>SearchDefaultScope</entry>
-                        <entry>Default Scope for LDAP Searches. Can be one of SUBTREE_SCOPE, OBJECT_SCOPE, ONELEVEL_SCOPE.</entry>
-                        <entry>ONELEVEL_SCOPE</entry>
-                    </row>
-                    <row>
-                        <entry>RestrictToObjectClass</entry>
-                        <entry>Restrict Searches to objectClass named in the Name field for a table</entry>
-                        <entry>false</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-    </section>
-
-    <section>
-        <title>Loopback Translator</title>
-        <para>
-        The Loopback translator, known by the type name <emphasis>loopback</emphasis>, 
-        provides a quick testing solution.  It supports all SQL constructs and returns 
-        default results, with configurable behavior.
-        </para>
-        
-        <table>
-            <title>Execution Properties</title>
-            <tgroup cols="3">
-                <colspec colwidth="3*" />
-                <colspec colwidth="6*" />
-                <colspec colwidth="2*" />
-                <thead>
-                    <row>
-                        <entry>Name</entry>
-                        <entry>Description</entry>
-                        <entry>Default</entry>
-                    </row>
-                </thead>
-                <tbody>
-                    <row>
-                        <entry>ThrowError</entry>
-                        <entry>true to always throw an error</entry>
-                        <entry>false</entry>
-                    </row>
-                    <row>
-                        <entry>RowCount</entry>
-                        <entry>Rows returned for non-update queries.</entry>
-                        <entry>1</entry>
-                    </row>
-                    <row>
-                        <entry>WaitTime</entry>
-                        <entry>Wait randomly up to this number of milliseconds with each sourc query.</entry>
-                        <entry>0</entry>
-                    </row>
-                    <row>
-                        <entry>PollIntervalInMilli</entry>
-                        <entry>if positive results will be "asynchronously" returned - that is a DataNotAvailableException will be thrown initially and the engine will wait the poll interval before polling for the results.</entry>
-                        <entry>-1</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-
-        <para>
-        There are no import settings for the Loopback translator; it also does not 
-        provide metadata - it should be used as a testing stub.
-        </para>
-        
-    </section>
-    
-    <section>
-        <title>Salesforce Translator</title>
-        <para>
-        The Salesforce translator, known by the type name <emphasis>salesforce</emphasis> 
-        supports the SELECT, DELETE, INSERT and UPDATE operations against a Salesforce.com 
-        account.  It is designed for use with the Teiid Salesforce resource adapter.
-        </para>
-        
-        <table>
-            <title>Execution Properties</title>
-            <tgroup cols="3">
-                <colspec colwidth="3*" />
-                <colspec colwidth="6*" />
-                <colspec colwidth="2*" />
-                <thead>
-                    <row>
-                        <entry>Name</entry>
-                        <entry>Description</entry>
-                        <entry>Default</entry>
-                    </row>
-                </thead>
-                <tbody>
-                    <row>
-                        <entry>ModelAuditFeilds</entry>
-                        <entry>Audit Model Fields</entry>
-                        <entry>false</entry>
-                    </row>
-                </tbody>
-            </tgroup>
-        </table>
-
-        <para>
-        The Salesforce translator can import metadata, but does not currently 
-        have import settings.
-        </para>
-        
-        <section>
-            <title>Usage</title>
-            <section>
-                <title>SQL Processing</title>
-                    <para>
-                    Salesforce does not provide the same set of
-                    functionality as a relational database. For example, Salesforce does
-                    not support arbitrary joins between tables. However, working in
-                    combination with the Teiid Query Planner, the Salesforce
-                    connector supports nearly all of the SQL syntax supported by the
-                    Teiid.
-                    </para>
-                    <para>
-                    The Salesforce Connector executes SQL commands by “pushing
-                    down” the command to Salesforce whenever possible, based on the
-                    supported capabilities. Teiid will automatically provide
-                    additional database functionality when the Salesforce Connector does
-                    not	explicitly provide support for a given SQL construct. In these
-                    cases, the SQL construct cannot be “pushed down” to the data source,
-                    so it will be evaluated in Teiid, in order to ensure that the
-                    operation is performed.
-                    </para>
-                    <para>
-                    In cases where certain SQL capabilities cannot be pushed down
-                    to Salesforce, Teiid will push down the capabilities that are
-                    supported, and fetch a set of data from Salesforce. Then, Teiid
-                    will evaluate the additional capabilities, creating a subset of the
-                    original data set. Finally, Teiid will pass the result to the
-                    client.
-                    </para>
-    
-                    <programlisting language="SQL"><![CDATA[SELECT sum(Reports) FROM Supervisor where Division = 'customer support';]]></programlisting>
-    
-                    <para>
-                    Neither Salesforce nor the Salesforce Connector support
-                    the sum() scalar function, but they do support CompareCriteriaEquals,
-                    so the query that is passed to Salesforce by the connector will be
-                    transformed to this query.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT Reports FROM Supervisor where Division = 'customer support';]]></programlisting>
-    
-                    <para>
-                    The sum() scalar function will be applied by the Teiid Query Engine to 
-                    the result set returned by the connector.
-                    </para>
-                    
-                    <para>
-                    In some cases multiple calls to the Salesforce application
-                    will be made to support the SQL passed to the connector.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[DELETE From Case WHERE Status = 'Closed';]]></programlisting>
-                    
-                    <para>
-                    The API in Salesforce to delete objects only supports
-                    deleting by ID. In order to accomplish this the Salesforce connector
-                    will first execute a query to get the IDs of the correct objects, and
-                    then delete those objects. So the above DELETE command will result in
-                    the following two commands.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT ID From Case WHERE Status = 'Closed';
-DELETE From Case where ID IN (<result of query>);]]></programlisting>
-
-                    <para>
-                    *The Salesforce API DELETE call is not expressed in SQL, but
-                    the above is an SQL equivalent expression.
-                    </para>
-                    
-                    <para>
-                    It's useful to be aware of unsupported capabilities, in order
-                    to avoid fetching large data sets from Salesforce and making you
-                    queries as performant as possible. 
-                    See all <link linkend="sf_supported">Supported Capabilities</link>.
-                    </para>
-                    
-                </section>
-                
-                <section>
-                    <title>Selecting from Multi-Select Picklists</title>
-                    <para>
-                    A multi-select picklist is a field type in Salesforce that can
-                    contain multiple values in a single field. Query criteria operators
-                    for fields of this type in SOQL are limited to EQ, NE, includes and
-                    excludes. The full Salesforce documentation for selecting from
-                    mullti-select picklists can be found at the following link.
-                    <ulink url="http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content%2Fsforce_api_calls_soql_querying_multiselect_picklists.htm|SkinName=webhelp">Querying Mulit-select Picklists</ulink>
-                    </para>
-        
-                    <para>
-                    Teiid SQL does not support the includes or
-                    excludes operators, but the Salesforce connector provides user
-                    defined function definitions for these operators that provided
-                    equivalent functionality for fields of type multi-select. The
-                    definition for the functions is:
-                    </para>
-                    
-                    <programlisting>boolean includes(Column column, String param)
-boolean excludes(Column column, String param)</programlisting>
-
-                    <para>
-                    For example, take a single multi-select picklist column
-                    called Status that contains all of these values.
-                    </para>
-                    
-                    <itemizedlist mark='opencircle'>
-                        <listitem>
-                            <para>current</para>
-                        </listitem>
-                        <listitem>
-                            <para>working</para>
-                        </listitem>
-                        <listitem>
-                            <para>critical</para>
-                        </listitem>
-                    </itemizedlist>
-                
-                    <para>
-                    For that column, all of the below are valid queries:
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT * FROM Issue WHERE true = includes (Status, 'current, working' );
-SELECT * FROM Issue WHERE true = excludes (Status, 'current, working' );
-SELECT * FROM Issue WHERE true = includes (Status, 'current;working, critical' );]]></programlisting>
-
-                    <para>
-                    EQ and NE criteria will pass to Salesforce as supplied. For
-                    example, these queries will not be modified by the connector.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT * FROM Issue WHERE Status = 'current';
-SELECT * FROM Issue WHERE Status = 'current;critical';
-SELECT * FROM Issue WHERE Status != 'current;working';]]></programlisting>
-
-                </section>
-                <section>
-                    <title>Selecting All Objects</title>
-                    <para>
-                    The Salesforce connector supports the calling the queryAll operation
-                    from the Salesforce API. The queryAll operation is equivalent
-                    to the query operation with the exception that it returns data about
-                    <emphasis role="strong">all current and deleted</emphasis>
-                    objects in the system.
-                    </para>
-                    <para>
-                    The connector determines if it will call the
-                    query or queryAll operation via reference to the
-                    isDeleted property present on each  Salesforce object, 
-                    and modeled as a column on each table generated by
-                    the importer. By default this value is set to
-                    False when the model is generated and thus the connector calls
-                    query. Users are free to change the value in the model to True,
-                    changing the default behavior of the connector to be queryAll.
-                    </para>
-                    <para>
-                    The behavior is different if isDeleted is used as a parameter
-                    in the query. If the isDeleted column is used as a parameter
-                    in the query, and the value is 'true' the connector will call queryAll.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[select * from Contact where isDeleted = true;</programlisting>
-                    
-                    <para>
-                    If the isDeleted column is used as a parameter in the query,
-                    and the value is 'false' the connector perform the default behavior
-                    will call query.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[select * from Contact where isDeleted = false;]]></programlisting>
-                </section>
-                <section>
-                    <title>Selecting Updated Objects</title>
-                    <para>
-                    If the option is selected when importing metadata from
-                    Salesforce, a GetUpdated procedure is generated in the model with
-                    the following structure:
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[GetUpdated (ObjectName IN string,
-	StartDate IN datetime, 
-	EndDate IN datetime,
-	LatestDateCovered OUT datetime)
-returns
-	ID string]]></programlisting>
-	
-                    <para>
-                    See the description of the
-                    <ulink url="http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getupdated.htm">GetUpdated</ulink>
-                    operation in the Salesforce documentation for usage details.
-                    </para>
-                    
-                </section>
-                <section>
-                    <title>Selecting Deleted Objects</title>
-                    <para>
-                    If the option is selected when importing metadata from
-                    Salesforce, a GetDeleted procedure is generated in the model with
-                    the following structure:
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[GetDeleted (ObjectName IN string,
-	StartDate IN datetime, 
-	EndDate IN datetime,
-	EarliestDateAvailable OUT datetime,
-	LatestDateCovered OUT datetime)
-returns
-	ID string,
-	DeletedDate datetime]]></programlisting>
-
-                    <para>
-                    See the description of the
-                    <ulink url="http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getdeleted.htm">GetDeleted</ulink>
-                    operation in the Salesforce documentation for usage details.
-                    </para>
-                    
-                </section>
-                <section>
-                    <title>Relationship Queries</title>
-                    <para>
-                    Salesforce does not support joins like a relational database, 
-                    but it does have support for queries that include parent-to-child
-                    or child-to-parent relationships between objects.  These are termed 
-                    Relationship Queries.  The SalesForce connector supports Relationship 
-                    Queries through Outer Join syntax.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT Account.name, Contact.Name from Contact LEFT OUTER JOIN Account 
-on Contact.Accountid = Account.id]]></programlisting>
-
-                    <para>
-                    This query shows the correct syntax to query a SalesForce model with 
-                    to produce a relationship query from child to parent.  It resolves to the 
-                    following query to SalesForce.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT Contact.Account.Name, Contact.Name FROM Contact]]></programlisting>
-                    
-                    <programlisting language="SQL"><![CDATA[select Contact.Name, Account.Name from Account Left outer Join Contact
-on Contact.Accountid = Account.id]]></programlisting>
-    
-                    <para>
-                    This query shows the correct syntax to query a SalesForce model with 
-                    to produce a relationship query from parent to child.  It resolves to the 
-                    following query to SalesForce.
-                    </para>
-                    
-                    <programlisting language="SQL"><![CDATA[SELECT Account.Name, (SELECT Contact.Name FROM
-Account.Contacts) FROM Account]]></programlisting>
-        
-                    <para>
-                    See the description of the
-                    <ulink url="http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content/sforce_api_calls_soql_relationships.htm">Relationship Queries</ulink>
-                    operation in the SalesForce documentation for limitations.
-                    </para>
-                </section>
-        
-                <section id="sf_supported">
-                    <title>Supported Capabilities</title>
-                    <para>
-                    The following are the the connector capabilities supported by
-                    the Salesforce Connector. These SQL constructs will be pushed down to
-                    Salesforce.
-                    </para>
-                    
-                    <itemizedlist mark='opencircle'>
-                        <listitem>
-                            <para>SELECT command</para>
-                        </listitem>
-                        <listitem>
-                            <para>INSERT Command</para>
-                        </listitem>
-                        <listitem>
-                            <para>UPDATE Command</para>
-                        </listitem>
-                        <listitem>
-                            <para>DELETE Command</para>
-                        </listitem>
-                        <listitem>
-                            <para>CompareCriteriaEquals</para>
-                        </listitem>
-                        <listitem>
-                            <para>InCriteria</para>
-                        </listitem>
-                        <listitem>
-                            <para>LikeCriteria - Supported for String fields only.</para>
-                        </listitem>
-                        <listitem>
-                            <para>RowLimit</para>
-                        </listitem>
-                        <listitem>
-                            <para>AggregatesCountStar</para>
-                        </listitem>
-                        <listitem>
-                            <para>NotCriteria</para>
-                        </listitem>
-                        <listitem>
-                            <para>OrCriteria</para>
-                        </listitem>
-                        <listitem>
-                            <para>CompareCriteriaOrdered</para>
-                        </listitem>
-                        <listitem>
-                            <para>OuterJoins with join criteria KEY</para>
-                        </listitem>
-                    </itemizedlist>
-                </section>
-                
-            </section>
-        </section>
-        
-        <section>
-            <title>Web Services Translator</title>
-            <para>
-            The Web Services translator, known by the type name <emphasis>ws</emphasis>, 
-            exposes stored procedures for calling web services backed by a Teiid WS 
-            resource adapter. It will commonly be used with the 
-            <link linkend="texttable">TEXTTABLE</link> or 
-            <link linkend="xmltable">XMLTABLE</link> table functions to use CSV or XML 
-            formated data.
-            </para>
-            
-            <table>
-                <title>Execution Properties</title>
-                <tgroup cols="3">
-                    <colspec colwidth="3*" />
-                    <colspec colwidth="6*" />
-                    <colspec colwidth="2*" />
-                    <thead>
-                        <row>
-                            <entry>Name</entry>
-                            <entry>Description</entry>
-                            <entry>Default</entry>
-                        </row>
-                    </thead>
-                    <tbody>
-                        <row>
-                            <entry>DefaultBinding</entry>
-                            <entry>The binding that should be used if one is not specified.  Can be one of HTTP, SOAP11, or SOAP12</entry>
-                            <entry>SOAP12</entry>
-                        </row>
-                        <row>
-                            <entry>DefaultServiceMode</entry>
-                            <entry>The default service mode.  For SOAP, MESSAGE mode indicates that the request will contain the entire SOAP envelope and not just the contents of the SOAP body.  Can be one of MESSAGE or PAYLOAD</entry>
-                            <entry>PAYLOAD</entry>
-                        </row>
-                        <row>
-                            <entry>XMLParamName</entry>
-                            <entry>Used with the HTTP binding (typically with the GET method) to indicate that the request document should be part of the query string.</entry>
-                            <entry>null - unused</entry>
-                        </row>
-                    </tbody>
-                </tgroup>
-            </table>
-            
-            <para>
-            There are ws importer settings, but it does provide metadata for dynamic VDBs.
-            </para>
-    
-            <section>
-                <title>Usage</title>
-                <para>
-                The WS translator exposes low level procedures for accessing web services.  
-                See also the ws-weather example in the kit.
-                </para>
-
-                <section>
-                    <title>Invoke Procedure</title>
-                    <para>
-                    Invoke allows for multiple binding, or protocol modes, including 
-                    HTTP, SOAP11, and SOAP12. 
-                    </para>
-                    <programlisting>Procedure invoke(binding in STRING, action in STRING, request in XML, endpoint in STRING) returns XML</programlisting>
-
-                    <para>
-                    The binding may be one of null (to use the default) HTTP, SOAP11, or 
-                    SOAP12.  Action with a SOAP binding indicates the SOAPAction value.  
-                    Action with a HTTP binding indicates the HTTP method (GET, POST, etc.), 
-                    which defaults to POST.
-                    </para>
-                    
-                    <para>
-                    A null value for the binding or endpoint will use the default value.  
-                    The default endpoint is specified in the WS resource adapter 
-                    configuration.  The endpoint URL may be absolute or relative.  If it's 
-                    relative then it will be combined with the default endpoint.
-                    </para>
-                    
-                    <para>
-                    Since multiple parameters are not required to have values, it is often 
-                    more clear to call the invoke procedure with named parameter syntax. 
-                    </para> 
-                    <programlisting>call invoke(binding=>'HTTP', action=>'GET')</programlisting>
-                    <para>The request XML should be a valid XML document or root element.</para>
-                </section>
-
-                <section>
-                    <title>InvokeHTTP Procedure</title>
-                    <para>
-                    <methodname>invokeHttp</methodname> can return the byte contents of an HTTP(S) call. 
-                    </para>
-                    <programlisting>Procedure invokeHttp(action in STRING, request in OBJECT, endpoint in STRING, contentType out STRING) returns BLOB</programlisting>
-        
-                    <para>
-                    Action indicates the HTTP method (GET, POST, etc.), which defaults to POST.
-                    </para>
-                    <para>
-                    A null value for endpoint will use the default value.  The default endpoint 
-                    is specified in the WS resource adapter configuration.  The endpoint URL may 
-                    be absolute or relative.  If it's relative then it will be combined with the 
-                    default endpoint.
-                    </para>
-                    <para>
-                    Since multiple parameters are not required to have values, it is often more 
-                    clear to call the invoke procedure with named parameter syntax.
-                    </para>
-                    <programlisting>call invokeHttp(action=>'GET')</programlisting>
-                    
-                    <para>
-                    The request can be one of SQLXML, STRING, BLOB, or CLOB.  The request will be 
-                    sent as the POST payload in byte form.  For STRING/CLOB values this will 
-                    default to the UTF-8 encoding.  To control the byte encoding, see the 
-                    <link linkend="to_bytes">to_bytes</link> function.
-                    </para>
-                </section>
-            </section>
-        </section>
-    </section>
-    
-    <section id="dynamic_vdbs">
-        <title>Dynamic VDBs</title>
-        <para>
-        Teiid integration is available via a "Dynamic VDB" without the need for Teiid Designer 
-        tooling.  While this mode of operation does not yet allow for the creation of view 
-        layers, the underlying sources can still be queried as if they are a single source.  See 
-        the kit's "teiid-example/dynamicvdb-*" for working examples.
-        </para>
-
-        <para>
-        To build a dynamic VDB, you'll need to create a 
-        <filename><replaceable>SOME-NAME</replaceable>-vdb.xml</filename> file.  The XML file captures 
-        information about the VDB, the sources it integrate, and preferences for importing metadata.
-        </para>
-        
-        <note>
-            <para>
-            VDB name pattern must adhere to "-vdb.xml"  for the Teiid VDB deployer to 
-            recognize this file as a dynamic VDB.
-            </para>
-        </note>
-        
-        <para>
-        my-vdb.xml: (The vdb-deployer.xml schema for this file is available in the schema 
-        folder under the docs with the Teiid distribution.)
-        </para>
-        
-        <programlisting role="XML" language="XML"><![CDATA[<vdb name="${vdb-name}" version="${vdb-version}">
-
-    <property name="UseConnectorMetadata" value="..." />
-
-    <!-- define a model fragment for each data source -->
-    <model name="${model-name}">
-        
-        <property name="..." value="..." />
-        ...
-
-        <source name="${source-name}" translator-name="${translator-name}" 
-
-        connection-jndi-name="${deployed-jndi-name}">
-    </model>
- 
-    <!-- create translator instances that override default properties -->
-
-    <translator name="${translator-name}" type="${translator-type}" />
- 
-        <property name="..." value="..." /> 
-        ...
-
-    </translator> 
-</vdb>]]></programlisting>
-
-        <section>
-            <title>VDB Element</title>
-            <itemizedlist>
-                <title>Attributes</title>
-                <listitem>
-                    <para>
-                    <emphasis>name</emphasis>
-                    </para>
-                    <para>
-                    The name of the VDB.  The VDB name 
-                    referenced through the driver or datasource during the connection time.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>version</emphasis>
-                    </para>
-                    <para>
-                    The version of the VDB (should be an 
-                    positive integer).  This determines the deployed directory location 
-                    (see Name), and provides an explicit versioning mechanism to the VDB 
-                    name.
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-            <itemizedlist>
-                <title>Property Elements</title>
-                <listitem>
-                    <para>
-                    <emphasis>UseConnectorMetadata</emphasis>
-                    </para>
-                    <para>
-                    Setting to use connector 
-                    supplied metadata. Can be "true" or "cached".  "true" will obtain 
-                    metadata once for every launch of Teiid.   "cached" will save a file 
-                    containing the metadata into the 
-                    <filename><replaceable>PROFILE</replaceable>/data/teiid</filename> directory
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-        </section>
-        
-        <section>
-            <title>Model Element</title>
-            <itemizedlist>
-                <title>Attributes</title>
-                <listitem>
-                    <para>
-                    <emphasis>name</emphasis>
-                    </para>
-                    <para>
-                    The name of the model is used as a 
-                    top level schema name for all of the  metadata imported from the 
-                    connector.  The name should be unique among all Models in the VDB and 
-                    should not contain the '.' character.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>version</emphasis>
-                    </para>
-                    <para>
-                    The version of the VDB (should be an 
-                    positive integer).  This determines the deployed directory location 
-                    (see Name), and provides an explicit versioning mechanism to the VDB 
-                    name.
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-            <itemizedlist>
-                <title>Source Element</title>
-                <listitem>
-                    <para>
-                    <emphasis>name</emphasis>
-                    </para>
-                    <para>
-                    The name of the source to use for this 
-                    model. This can be any name you like, but will typically be the same 
-                    as the model name.  Having a name different than the model name is 
-                    only useful in multi-source scenarios.	
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>translator-name</emphasis>
-                    </para>
-                    <para>
-                    The name or type of the Teiid Translator to use.  Possible values include 
-                    the built-in types (ws, file, ldap, oracle, sqlserver, db2, derby, etc.) 
-                    and translators defined in the translators section. 
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>connection-jndi-name</emphasis>
-                    </para>
-                    <para>
-                    The JNDI name of this source's connection factory. There should be a 
-                    corresponding "-ds.xml" file that defines the connection factory in 
-                    the JBoss AS.  Check out the  deploying VDB dependencies section for 
-                    info. You also need to deploy these connection factories before you 
-                    can deploy the VDB.	
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-            <itemizedlist>
-                <title>Property Elements</title>
-                <listitem>
-                    <para>
-                    <emphasis>importer.&lt;propertyname&gt;</emphasis>
-                    </para>
-                    <para>
-                    Property to be used by the connector importer for the model for purposes 
-                    importing metadata.  See possible property name/values in the 
-                    Translator specific section. Note that using these properties you 
-                    can narrow or widen the data elements available for integration.
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-        </section>
-        <section>
-            <title>Translator Element</title>
-            <itemizedlist>
-                <title>Attributes</title>
-                <listitem>
-                    <para>
-                    <emphasis>name</emphasis>
-                    </para>
-                    <para>
-                    The name of the the Translator.  Referenced by the source element.
-                    </para>
-                </listitem>
-                <listitem>
-                    <para>
-                    <emphasis>type</emphasis>
-                    </para>
-                    <para>
-                    The base type of the Translator.  Can be one of the built-in types (ws, 
-                    file, ldap, oracle, sqlserver, db2, derby, etc.).
-                    </para>
-                </listitem>
-            </itemizedlist>
-            
-            <itemizedlist>
-                <title>Property Elements</title>
-                <listitem>
-                    <para>
-                    Set a value that overrides a translator default property.  See 
-                    possible property name/values in the Translator specific section.
-                    </para>
-                </listitem>
-            </itemizedlist>        
-        </section>
-        
-    </section>
-    <section>
-        <title>Multi-Source Models and VDB</title>
-        <para>
-        When you have multiple instances of data that are using identical schema 
-        (horizontal sharding), Teiid can help you aggregate data across all the 
-        instances, using "multi-source" models. In this scenario, instead of 
-        creating/importing a model for every data source, user needs to define one 
-        source model that represents the schema and configure multiple data "sources" 
-        underneath it. During runtime, when a query issued against this model, the query 
-        engine analyzes the information and gathers the required data from all the 
-        sources configured and aggregates the results and provides in a single result set.
-        </para>
-    
-        <para>
-        To mark a model as multi-source, the user needs to supply property called 
-        <property>supports-multi-source-bindings</property>, in the "vdb.xml" file.  
-        Also, the user needs to define multiple sources. Here is code example showing dynamic vdb with single model with 
-        multiple sources defined.
-        </para>
-        
-        <programlisting role="XML" language="XML"><![CDATA[<vdb name="vdbname" version="1">
-    <model visible="true" type="PHYSICAL" name="Customers" path="/Test/Customers.xmi">
-        <property name="supports-multi-source-bindings" value="true"/>
-        <source name="chicago" 
-            translator-name="oracle" connection-jndi-name="chicago-customers"/>
-        <source name="newyork" 
-            translator-name="oracle" connection-jndi-name="newyork-customers"/>
-        <source name="la" 
-            translator-name="oracle" connection-jndi-name="la-customers"/>
-    </model>
-</vdb>]]></programlisting>
-
-        <para>
-        In the above example, the VDB defined has single model called <literal>Customers</literal>, 
-        that has multiple sources (<literal>chicago</literal>, <literal>newyork</literal>, 
-        and <literal>la</literal>) that define different instances of data. Every 
-        time a model is marked as "multi-source", the 
-        runtime engine adds a additional column called "SOURCE_NAME" to every table in 
-        that model. This column maps to the source's name from the XML. In 
-        the above XML code that would be <literal>chicago</literal>, <literal>la</literal>, 
-        <literal>newyork</literal>. This allows queries like the following:
-        </para>
-        
-        <programlisting language="SQL"><![CDATA[select * from table where SOURCE_NAME = 'newyork'
-update table column=value  where SOURCE_NAME='chicago'
-delete from table where column = x and SOURCE_NAME='la'
-insert into table (column, SOURCE_NAME) VALUES ('value', 'newyork')]]></programlisting>
-      
-        <para>
-        Note that when user do not supply the "SOURCE_NAME" in the criteria, the command applies 
-        to all the sources. If SOURCE_NAME supplied, the query is executed only aginst the source specified. 
-        Another useful feature along with this feature is 
-        "partial results" to skip unavailable sources if they are down.
-        </para>
-        
-        <note>
-            <para>
-            Currently the tooling support for managing the multi-source feature is 
-            limited, so if you need to use this feature build the VDB as usual in 
-            the Teiid Designer and then edit the "vdb.xml" file in the VDB archive 
-            using a Text editor to add the additional sources as defined above. 
-            You must deploy a separate data source for each source defined in the xml file.
-            </para>
-        </note>
-
-        <note>
-            <para>
-            If you would like to use "SOURCE_NAME" in your transformations to control which sources are accessed or updated, 
-            you would manually need to add this extra column on your view table in
-            the Designer. This column will not be automatically added on the source table, when you import 
-            the medata from source.
-            </para>
-        </note>        
-    </section>
-
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml (from rev 2774, trunk/documentation/reference/src/main/docbook/en-US/content/translators.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/translators.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1301 @@
+<?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="translators">
+    <title>Translators</title>
+
+    <section>
+        <title>Introduction to the Teiid Connector Architecture</title>
+        <para>
+        The Teiid Connector Architecture (TCA) provides Teiid with a robust mechanism 
+        for integrating with external systems.  The TCA defines a common client interface 
+        between Teiid and an external system that includes metadata as to what SQL 
+        constructs are supported for pushdown and the ability to import metadata from 
+        the external system.
+        </para>
+        
+        <para>
+        A Translator is the heart of the TCA and acts as the bridge logic between Teiid 
+        and an external system, which is most commonly accessed through a JCA resource 
+        adapter.  Refer to the Teiid Developers Guide for details on developing custom 
+        Translators and JCA resource adapters for use with Teiid.
+        </para>
+        
+        <note>
+            <para>
+            The TCA is not the same as the JCA, the JavaEE Connector Architecture, although 
+            the TCA is designed for use with JCA resource adapters.
+            </para>
+        </note>
+        
+        <note>
+            <para>
+            The import capabilities of Teiid Translators is currently only used in 
+            <link linkend="dynamic_vdbs">dynamic VDBs</link> and not by the Teiid Designer.
+            </para>
+        </note>
+        
+    </section>
+
+    <section>
+        <title>Translators</title>
+        <para>
+        A Translator is typically paired with a particular JCA resource adapter.  In 
+        instances where pooling, environment dependent configuration management, advanced 
+        security handling, etc. are not needed, then a JCA resource adapter is not needed.  
+        The configuration of JCA ConnectionFactories for needed resource adapters is not 
+        part of this guide, please see the Teiid Administrator Guide and the kit examples 
+        for configuring resource adapters for use in JBossAS.
+        </para>
+        
+        <para>
+        Translators can have a number of configurable properties.  These are broken down 
+        into execution properties, which determine aspects of how data is retrieved, and 
+        import settings, which determine what metadata is read for import.
+        </para>
+        
+        <para>
+        The execution properties for a translator typically have reasonable defaults.  For 
+        specific translator types, e.g. the Derby translator, base execution properties are 
+        already tuned to match the source.  In most cases the user will not need to adjust 
+        their values.
+        </para>
+
+        <table>
+            <title>Base Execution Properties - shared by all translators</title>
+            <tgroup cols="3">
+                <colspec colwidth="3*" />
+                <colspec colwidth="6*" />
+                <colspec colwidth="2*" />
+                <thead>
+                    <row>
+                        <entry>Name</entry>
+                        <entry>Description</entry>
+                        <entry>Default</entry>
+                    </row>
+                </thead>
+                <tbody>
+                    <row>
+                        <entry>Immutable</entry>
+                        <entry>Set to true to indicate that the source never changes.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>RequiresCriteria</entry>
+                        <entry>Set to true to indicate that source SELECT/UPDATE/DELETE queries require a where clause.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>SupportsOrderBy</entry>
+                        <entry>Set to true to indicate that the ORDER BY clause is supported.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>SupportsOuterJoins</entry>
+                        <entry>Set to true to indicate that OUTER JOINs are supported.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>SupportsFullOuterJoins</entry>
+                        <entry>If outer joins are supported, true indicates that FULL OUTER JOINs are supported.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>SupportsInnerJoins</entry>
+                        <entry>Set to true to indicate that INNER JOINs are supported.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>SupportedJoinCriteria</entry>
+                        <entry>If joins are supported, defines what criteria may be used as the join criteria.  May be one of (ANY, THETA, EQUI, or KEY).</entry>
+                        <entry>ANY</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+        
+        <note>
+            <para>
+            Only a subset of the metadata as to what SQL constructs the source supports 
+            can be set through execution properties.  If more control is needed, please 
+            consult the Teiid Developers Guide.
+            </para>
+        </note>
+        
+        <para>There are no base importer settings.</para>
+
+        <section>
+            <title>File Translator</title>
+            <para>
+            The file translator, known by the type name <emphasis>file</emphasis>, exposes 
+            stored procedures to leverage file system resources exposed by the file resource 
+            adapter. It will commonly be used with the <link linkend="texttable">TEXTTABLE</link> 
+            or <link linkend="xmltable">XMLTABLE</link> table functions to use CSV or XML 
+            formated data.
+            </para>
+
+            <table>
+                <title>Execution Properties</title>
+                <tgroup cols="3">
+                    <colspec colwidth="1*" />
+                    <colspec colwidth="4*" />
+                    <colspec colwidth="1*" />
+                    <thead>
+                        <row>
+                            <entry>Name</entry>
+                            <entry>Description</entry>
+                            <entry>Default</entry>
+                        </row>
+                    </thead>
+                    <tbody>
+                        <row>
+                            <entry>Encoding</entry>
+                            <entry>The encoding that should be used for CLOBs returned by the getTextFiles procedure</entry>
+                            <entry>The system default encoding</entry>
+                        </row>
+                    </tbody>
+                </tgroup>
+            </table>
+            
+            <para>There are file importer settings, but it does provide metadata for dynamic vdbs.</para>
+            
+            <section>
+                <title>Usage</title>
+                <para>
+                Retrieve all files as BLOBs with the given extension at the given path.
+                </para>
+                
+                <programlisting>call getFiles('path/*.ext')</programlisting>
+                
+                <para>
+                If the extension pattern is not specified and the path is a directory, 
+                then all files in the directory will be returned.  If the path or filename 
+                doesn't exist, then no results will be returned.
+                </para>
+                
+                <para>
+                Retrieve all files as CLOBs with the given extension at the given path.
+                </para>
+                <programlisting>call getTextFiles('path/*.ext')</programlisting>
+                
+                <para>
+                Save the CLOB, BLOB, or XML file to given path
+                </para>
+                <programlisting>call saveFile('path', value)</programlisting>
+                
+                <para>
+                See the database metadata for full descriptions of the getFiles, 
+                getTextFiles, and saveFile procedures.
+                </para>
+            </section>
+
+        </section>
+        
+        <section>
+            <title>JDBC Translator</title>
+            <para>
+            The JDBC translator bridges between SQL semantic and data type difference 
+            between Teiid and a target RDBMS.  Teiid has a range of specific translators 
+            that target the most popular open source and proprietary databases.
+            </para>
+
+            <itemizedlist>
+                <title>Type names:</title>
+                <listitem>
+                    <para>
+                    <emphasis>jdbc-ansi</emphasis> - declares support for most SQL 
+                    constructs supported by Teiid, except for row limit/offset and 
+                    EXCEPT/INTERCECT.  Translates source SQL into ANSI compliant syntax.  
+                    This translator should be used when another more specific type is 
+                    not available.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>jdbc-simple</emphasis> - same as jdbc-ansi, except disables 
+                    support for function, UNION, and aggregate pushdown.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>db2</emphasis> - for use with DB2 8 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>derby</emphasis> - for use with Derby 10.1 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>h2</emphasis> - for use with H2 version 1.1 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>hsql</emphasis> - for use with HSQLDB 1.7 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>informix</emphasis> - for use with any version.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>metamatrix</emphasis> - for use with MetaMatrix 5.5.0 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>modeshape</emphasis> - for use with Modeshape 2.2.1 or later. The PATH, NAME, LOCALNODENAME, DEPTH, and SCORE functions should be accessed as pseudo-columns, e.g. "nt:base"."jcr:path". 
+                    Teiid UFDs (prefixed by JCR_) are available for CONTIANS, ISCHILDNODE, ISDESCENDENT, ISSAMENODE, REFERENCE - see the JCRFunctions.xmi.  
+                    If a selector name is needed in a JCR function, you should use the pseudo-column "jcr:path", e.g. JCR_ISCHILDNODE(foo.jcr_path, 'x/y') would become ISCHILDNODE(foo, 'x/y') in the ModeShape query.
+                    An additional pseudo-column "mode:properties" should be imported by setting the ModeShape JDBC connection property teiidsupport=true.  
+                    The column "mode:properties" should be used by the JCR_REFERENCE and other 
+                    functions that expect a .* selector name, e.g. JCR_REFERENCE(nt_base.jcr_properties) would become REFERENCE("nt:base".*) in the ModeShape query.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>mysql</emphasis>/<emphasis>mysql5</emphasis> - for use with 
+                    MySQL version 4.x and 5 or later respectively.  
+                    </para>
+                    <para>
+                    The MySQL Translators expect the database or session to be using ANSI 
+                    mode.  If the database is not using ANSI mode, an initialization query 
+                    should be used on the pool to set ANSI mode:  
+                    </para>
+                    <programlisting>set SESSION sql_mode = 'ANSI'</programlisting>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>oracle</emphasis> - for use with Oracle 9i or later.  
+                    Sequences may be used with the Oracle translator. A sequence may be 
+                    modeled as a table with a name in source of DUAL and columns with the 
+                    name in source set to <code>&lt;sequencesequence name&gt;.[nextval|currentval].</code>  
+                    You can use a sequence as the default value for insert columns by 
+                    setting the column to autoincrement and the name in source to 
+                    <code>&lt;element name&gt;:SEQUENCE=&lt;sequence name&gt;.&lt;sequence value&gt;</code>.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>postgresql</emphasis> - for use with 8.0 or later clients 
+                    and 7.1 or later server.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>sybase</emphasis> - for use with Sybase version 12.5 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>teiid</emphasis> - for use with Teiid 6.0 or later.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>teradata</emphasis> - for use with Teradata V2R5.1 or later.
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+            <table>
+                <title>Execution Properties - shared by all JDBC Translators</title>
+                <tgroup cols="3">
+                    <colspec colwidth="3*" />
+                    <colspec colwidth="6*" />
+                    <colspec colwidth="2*" />
+                    <thead>
+                        <row>
+                            <entry>Name</entry>
+                            <entry>Description</entry>
+                            <entry>Default</entry>
+                        </row>
+                    </thead>
+                    <tbody>
+                    <row>
+                        <entry>DatabaseTimeZone</entry>
+                        <entry>The time zone of the database.  Used when fetchings date, time, or timestamp values.</entry>
+                        <entry>The system default time zone</entry>
+                    </row>
+                    <row>
+                        <entry>DatabaseVersion</entry>
+                        <entry>The specific database version.  Used to further tune pushdown support.</entry>
+                        <entry>The base supported version</entry>
+                    </row>
+                    <row>
+                        <entry>TrimStrings</entry>
+                        <entry>true to trim trailing whitespace from fixed length character strings.  Note that Teiid only has a string, or varchar, type that treats trailing whitespace as meaningful.</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>UseBindVariables</entry>
+                        <entry>true to indicate that PreparedStatements should be used and that literal values in the source query should be replace with bind variables.  If false only LOB values will trigger the use of PreparedStatements.</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>UseCommentsInSourceQuery</entry>
+                        <entry>This will embed a /*comment*/ leading comment with session/request id in source SQL query for informational purposes</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>MaxPreparedInsertBatchSize</entry>
+                        <entry>The max size of a prepared insert batch.</entry>
+                        <entry>2048</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+            
+        <table>
+            <title>Importer Properties - shared by all JDBC Translators</title>
+            <tgroup cols="3">
+            <colspec colwidth="3*" />
+            <colspec colwidth="6*" />
+            <colspec colwidth="2*" />
+                <thead>
+                    <row>
+                        <entry>Name</entry>
+                        <entry>Description</entry>
+                        <entry>Default</entry>
+                    </row>
+                </thead>
+                <tbody>
+                    <row>
+                        <entry>catalog</entry>
+                        <entry>See DatabaseMetaData.getTables<footnote label="1" id="dbmd"><para>Full JavaDoc for <ulink url="http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html">DatabaseMetaData</ulink></para></footnote></entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>schemaPattern</entry>
+                        <entry>See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>tableNamePattern</entry>
+                        <entry>See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>procedurePatternName</entry>
+                        <entry>See DatabaseMetaData.getProcedures<footnoteref linkend="dbmd"/></entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>tableTypes</entry>
+                        <entry>Comma separated list - without spaces - of imported table types.  See DatabaseMetaData.getTables<footnoteref linkend="dbmd"/></entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>useFullSchemaName</entry>
+                        <entry>When false, directs the importer to drop the source catalog/schema from the Teiid object name, so that the Teiid fully qualified name will be in the form of &lt;model name&gt;.&lt;table name&gt; - Note: that this may lead to objects with duplicate names when importing from multiple schemas, which results in an exception</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>importKeys</entry>
+                        <entry>true to import primary and foriegn keys</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>importIndexes</entry>
+                        <entry>true to import index/unique key/cardinality information</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>importApproximateIndexes</entry>
+                        <entry>true to import approximate index information.  See DatabaseMetaData.getIndexInfo<footnoteref linkend="dbmd"/></entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>importProcedures</entry>
+                        <entry>true to import procedures and procedure columns - Note that it is not always possible to import procedure result set columns due to database limitations.  It is also not currently possible to import overloaded procedures.</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>widenUnsignedTypes</entry>
+                        <entry>true to convert unsigned types to the next widest type.  For example SQL Server reports tinyint as an unsigned type.  With this option enabled, tinyint would be imported as a short instead of a byte.</entry>
+                        <entry>true</entry>
+                    </row>
+                    <row>
+                        <entry>quoteNameInSource</entry>
+                        <entry>false will override the default and direct Teiid to create source queries using unquoted identifiers.</entry>
+                        <entry>true</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+
+        <warning>
+            <para>
+            The default import settings will crawl all available metadata.  This import 
+            process is time consuming and full metadata import is not needed in most 
+            situations.  Most commonly you'll want to limit import by schemaPattern 
+            and tableTypes.
+            </para>
+        </warning>
+
+        <para>
+        Example importer settings to only import tables and views from my-schema.
+        </para>
+        <programlisting language="XML" role="XML"><![CDATA[...
+<property name="importer.tableTypes" value="TABLE,VIEW"/>
+<property name="importer.schemaPattern" value="my-schema"/>
+...]]></programlisting>
+
+        <section>
+            <title>Usage</title>
+            <para>
+            Usage of a JDBC source is straight-forward.  Using Teiid SQL, the source may be 
+            queried as if the tables and procedures were local to the Teiid system.
+            </para>
+        </section>
+        
+    </section>
+    
+    <section>
+        <title>LDAP Translator</title>
+        <para>
+        The LDAP translator, known by the type name <emphasis>ldap</emphasis>, exposes an 
+        LDAP directory tree relationally with pushdown support for filtering via criteria.  
+        This is typically coupled with the LDAP resource adapter.
+        </para>
+        
+        <table>
+            <title>Execution Properties</title>
+            <tgroup cols="3">
+                <thead>
+                    <row>
+                        <entry>Name</entry>
+                        <entry>Description</entry>
+                        <entry>Default</entry>
+                    </row>
+                </thead>
+                <tbody>
+                    <row>
+                        <entry>SearchDerfaultBaseDN</entry>
+                        <entry>Default Base DN for LDAP Searches</entry>
+                        <entry>null</entry>
+                    </row>
+                    <row>
+                        <entry>SearchDefaultScope</entry>
+                        <entry>Default Scope for LDAP Searches. Can be one of SUBTREE_SCOPE, OBJECT_SCOPE, ONELEVEL_SCOPE.</entry>
+                        <entry>ONELEVEL_SCOPE</entry>
+                    </row>
+                    <row>
+                        <entry>RestrictToObjectClass</entry>
+                        <entry>Restrict Searches to objectClass named in the Name field for a table</entry>
+                        <entry>false</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+    </section>
+
+    <section>
+        <title>Loopback Translator</title>
+        <para>
+        The Loopback translator, known by the type name <emphasis>loopback</emphasis>, 
+        provides a quick testing solution.  It supports all SQL constructs and returns 
+        default results, with configurable behavior.
+        </para>
+        
+        <table>
+            <title>Execution Properties</title>
+            <tgroup cols="3">
+                <colspec colwidth="3*" />
+                <colspec colwidth="6*" />
+                <colspec colwidth="2*" />
+                <thead>
+                    <row>
+                        <entry>Name</entry>
+                        <entry>Description</entry>
+                        <entry>Default</entry>
+                    </row>
+                </thead>
+                <tbody>
+                    <row>
+                        <entry>ThrowError</entry>
+                        <entry>true to always throw an error</entry>
+                        <entry>false</entry>
+                    </row>
+                    <row>
+                        <entry>RowCount</entry>
+                        <entry>Rows returned for non-update queries.</entry>
+                        <entry>1</entry>
+                    </row>
+                    <row>
+                        <entry>WaitTime</entry>
+                        <entry>Wait randomly up to this number of milliseconds with each sourc query.</entry>
+                        <entry>0</entry>
+                    </row>
+                    <row>
+                        <entry>PollIntervalInMilli</entry>
+                        <entry>if positive results will be "asynchronously" returned - that is a DataNotAvailableException will be thrown initially and the engine will wait the poll interval before polling for the results.</entry>
+                        <entry>-1</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+
+        <para>
+        There are no import settings for the Loopback translator; it also does not 
+        provide metadata - it should be used as a testing stub.
+        </para>
+        
+    </section>
+    
+    <section>
+        <title>Salesforce Translator</title>
+        <para>
+        The Salesforce translator, known by the type name <emphasis>salesforce</emphasis> 
+        supports the SELECT, DELETE, INSERT and UPDATE operations against a Salesforce.com 
+        account.  It is designed for use with the Teiid Salesforce resource adapter.
+        </para>
+        
+        <table>
+            <title>Execution Properties</title>
+            <tgroup cols="3">
+                <colspec colwidth="3*" />
+                <colspec colwidth="6*" />
+                <colspec colwidth="2*" />
+                <thead>
+                    <row>
+                        <entry>Name</entry>
+                        <entry>Description</entry>
+                        <entry>Default</entry>
+                    </row>
+                </thead>
+                <tbody>
+                    <row>
+                        <entry>ModelAuditFeilds</entry>
+                        <entry>Audit Model Fields</entry>
+                        <entry>false</entry>
+                    </row>
+                </tbody>
+            </tgroup>
+        </table>
+
+        <para>
+        The Salesforce translator can import metadata, but does not currently 
+        have import settings.
+        </para>
+        
+        <section>
+            <title>Usage</title>
+            <section>
+                <title>SQL Processing</title>
+                    <para>
+                    Salesforce does not provide the same set of
+                    functionality as a relational database. For example, Salesforce does
+                    not support arbitrary joins between tables. However, working in
+                    combination with the Teiid Query Planner, the Salesforce
+                    connector supports nearly all of the SQL syntax supported by the
+                    Teiid.
+                    </para>
+                    <para>
+                    The Salesforce Connector executes SQL commands by “pushing
+                    down” the command to Salesforce whenever possible, based on the
+                    supported capabilities. Teiid will automatically provide
+                    additional database functionality when the Salesforce Connector does
+                    not	explicitly provide support for a given SQL construct. In these
+                    cases, the SQL construct cannot be “pushed down” to the data source,
+                    so it will be evaluated in Teiid, in order to ensure that the
+                    operation is performed.
+                    </para>
+                    <para>
+                    In cases where certain SQL capabilities cannot be pushed down
+                    to Salesforce, Teiid will push down the capabilities that are
+                    supported, and fetch a set of data from Salesforce. Then, Teiid
+                    will evaluate the additional capabilities, creating a subset of the
+                    original data set. Finally, Teiid will pass the result to the
+                    client.
+                    </para>
+    
+                    <programlisting language="SQL"><![CDATA[SELECT sum(Reports) FROM Supervisor where Division = 'customer support';]]></programlisting>
+    
+                    <para>
+                    Neither Salesforce nor the Salesforce Connector support
+                    the sum() scalar function, but they do support CompareCriteriaEquals,
+                    so the query that is passed to Salesforce by the connector will be
+                    transformed to this query.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT Reports FROM Supervisor where Division = 'customer support';]]></programlisting>
+    
+                    <para>
+                    The sum() scalar function will be applied by the Teiid Query Engine to 
+                    the result set returned by the connector.
+                    </para>
+                    
+                    <para>
+                    In some cases multiple calls to the Salesforce application
+                    will be made to support the SQL passed to the connector.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[DELETE From Case WHERE Status = 'Closed';]]></programlisting>
+                    
+                    <para>
+                    The API in Salesforce to delete objects only supports
+                    deleting by ID. In order to accomplish this the Salesforce connector
+                    will first execute a query to get the IDs of the correct objects, and
+                    then delete those objects. So the above DELETE command will result in
+                    the following two commands.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT ID From Case WHERE Status = 'Closed';
+DELETE From Case where ID IN (<result of query>);]]></programlisting>
+
+                    <para>
+                    *The Salesforce API DELETE call is not expressed in SQL, but
+                    the above is an SQL equivalent expression.
+                    </para>
+                    
+                    <para>
+                    It's useful to be aware of unsupported capabilities, in order
+                    to avoid fetching large data sets from Salesforce and making you
+                    queries as performant as possible. 
+                    See all <link linkend="sf_supported">Supported Capabilities</link>.
+                    </para>
+                    
+                </section>
+                
+                <section>
+                    <title>Selecting from Multi-Select Picklists</title>
+                    <para>
+                    A multi-select picklist is a field type in Salesforce that can
+                    contain multiple values in a single field. Query criteria operators
+                    for fields of this type in SOQL are limited to EQ, NE, includes and
+                    excludes. The full Salesforce documentation for selecting from
+                    mullti-select picklists can be found at the following link.
+                    <ulink url="http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content%2Fsforce_api_calls_soql_querying_multiselect_picklists.htm|SkinName=webhelp">Querying Mulit-select Picklists</ulink>
+                    </para>
+        
+                    <para>
+                    Teiid SQL does not support the includes or
+                    excludes operators, but the Salesforce connector provides user
+                    defined function definitions for these operators that provided
+                    equivalent functionality for fields of type multi-select. The
+                    definition for the functions is:
+                    </para>
+                    
+                    <programlisting>boolean includes(Column column, String param)
+boolean excludes(Column column, String param)</programlisting>
+
+                    <para>
+                    For example, take a single multi-select picklist column
+                    called Status that contains all of these values.
+                    </para>
+                    
+                    <itemizedlist mark='opencircle'>
+                        <listitem>
+                            <para>current</para>
+                        </listitem>
+                        <listitem>
+                            <para>working</para>
+                        </listitem>
+                        <listitem>
+                            <para>critical</para>
+                        </listitem>
+                    </itemizedlist>
+                
+                    <para>
+                    For that column, all of the below are valid queries:
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT * FROM Issue WHERE true = includes (Status, 'current, working' );
+SELECT * FROM Issue WHERE true = excludes (Status, 'current, working' );
+SELECT * FROM Issue WHERE true = includes (Status, 'current;working, critical' );]]></programlisting>
+
+                    <para>
+                    EQ and NE criteria will pass to Salesforce as supplied. For
+                    example, these queries will not be modified by the connector.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT * FROM Issue WHERE Status = 'current';
+SELECT * FROM Issue WHERE Status = 'current;critical';
+SELECT * FROM Issue WHERE Status != 'current;working';]]></programlisting>
+
+                </section>
+                <section>
+                    <title>Selecting All Objects</title>
+                    <para>
+                    The Salesforce connector supports the calling the queryAll operation
+                    from the Salesforce API. The queryAll operation is equivalent
+                    to the query operation with the exception that it returns data about
+                    <emphasis role="strong">all current and deleted</emphasis>
+                    objects in the system.
+                    </para>
+                    <para>
+                    The connector determines if it will call the
+                    query or queryAll operation via reference to the
+                    isDeleted property present on each  Salesforce object, 
+                    and modeled as a column on each table generated by
+                    the importer. By default this value is set to
+                    False when the model is generated and thus the connector calls
+                    query. Users are free to change the value in the model to True,
+                    changing the default behavior of the connector to be queryAll.
+                    </para>
+                    <para>
+                    The behavior is different if isDeleted is used as a parameter
+                    in the query. If the isDeleted column is used as a parameter
+                    in the query, and the value is 'true' the connector will call queryAll.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[select * from Contact where isDeleted = true;</programlisting>
+                    
+                    <para>
+                    If the isDeleted column is used as a parameter in the query,
+                    and the value is 'false' the connector perform the default behavior
+                    will call query.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[select * from Contact where isDeleted = false;]]></programlisting>
+                </section>
+                <section>
+                    <title>Selecting Updated Objects</title>
+                    <para>
+                    If the option is selected when importing metadata from
+                    Salesforce, a GetUpdated procedure is generated in the model with
+                    the following structure:
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[GetUpdated (ObjectName IN string,
+	StartDate IN datetime, 
+	EndDate IN datetime,
+	LatestDateCovered OUT datetime)
+returns
+	ID string]]></programlisting>
+	
+                    <para>
+                    See the description of the
+                    <ulink url="http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getupdated.htm">GetUpdated</ulink>
+                    operation in the Salesforce documentation for usage details.
+                    </para>
+                    
+                </section>
+                <section>
+                    <title>Selecting Deleted Objects</title>
+                    <para>
+                    If the option is selected when importing metadata from
+                    Salesforce, a GetDeleted procedure is generated in the model with
+                    the following structure:
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[GetDeleted (ObjectName IN string,
+	StartDate IN datetime, 
+	EndDate IN datetime,
+	EarliestDateAvailable OUT datetime,
+	LatestDateCovered OUT datetime)
+returns
+	ID string,
+	DeletedDate datetime]]></programlisting>
+
+                    <para>
+                    See the description of the
+                    <ulink url="http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_getdeleted.htm">GetDeleted</ulink>
+                    operation in the Salesforce documentation for usage details.
+                    </para>
+                    
+                </section>
+                <section>
+                    <title>Relationship Queries</title>
+                    <para>
+                    Salesforce does not support joins like a relational database, 
+                    but it does have support for queries that include parent-to-child
+                    or child-to-parent relationships between objects.  These are termed 
+                    Relationship Queries.  The SalesForce connector supports Relationship 
+                    Queries through Outer Join syntax.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT Account.name, Contact.Name from Contact LEFT OUTER JOIN Account 
+on Contact.Accountid = Account.id]]></programlisting>
+
+                    <para>
+                    This query shows the correct syntax to query a SalesForce model with 
+                    to produce a relationship query from child to parent.  It resolves to the 
+                    following query to SalesForce.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT Contact.Account.Name, Contact.Name FROM Contact]]></programlisting>
+                    
+                    <programlisting language="SQL"><![CDATA[select Contact.Name, Account.Name from Account Left outer Join Contact
+on Contact.Accountid = Account.id]]></programlisting>
+    
+                    <para>
+                    This query shows the correct syntax to query a SalesForce model with 
+                    to produce a relationship query from parent to child.  It resolves to the 
+                    following query to SalesForce.
+                    </para>
+                    
+                    <programlisting language="SQL"><![CDATA[SELECT Account.Name, (SELECT Contact.Name FROM
+Account.Contacts) FROM Account]]></programlisting>
+        
+                    <para>
+                    See the description of the
+                    <ulink url="http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic=Content/sforce_api_calls_soql_relationships.htm">Relationship Queries</ulink>
+                    operation in the SalesForce documentation for limitations.
+                    </para>
+                </section>
+        
+                <section id="sf_supported">
+                    <title>Supported Capabilities</title>
+                    <para>
+                    The following are the the connector capabilities supported by
+                    the Salesforce Connector. These SQL constructs will be pushed down to
+                    Salesforce.
+                    </para>
+                    
+                    <itemizedlist mark='opencircle'>
+                        <listitem>
+                            <para>SELECT command</para>
+                        </listitem>
+                        <listitem>
+                            <para>INSERT Command</para>
+                        </listitem>
+                        <listitem>
+                            <para>UPDATE Command</para>
+                        </listitem>
+                        <listitem>
+                            <para>DELETE Command</para>
+                        </listitem>
+                        <listitem>
+                            <para>CompareCriteriaEquals</para>
+                        </listitem>
+                        <listitem>
+                            <para>InCriteria</para>
+                        </listitem>
+                        <listitem>
+                            <para>LikeCriteria - Supported for String fields only.</para>
+                        </listitem>
+                        <listitem>
+                            <para>RowLimit</para>
+                        </listitem>
+                        <listitem>
+                            <para>AggregatesCountStar</para>
+                        </listitem>
+                        <listitem>
+                            <para>NotCriteria</para>
+                        </listitem>
+                        <listitem>
+                            <para>OrCriteria</para>
+                        </listitem>
+                        <listitem>
+                            <para>CompareCriteriaOrdered</para>
+                        </listitem>
+                        <listitem>
+                            <para>OuterJoins with join criteria KEY</para>
+                        </listitem>
+                    </itemizedlist>
+                </section>
+                
+            </section>
+        </section>
+        
+        <section>
+            <title>Web Services Translator</title>
+            <para>
+            The Web Services translator, known by the type name <emphasis>ws</emphasis>, 
+            exposes stored procedures for calling web services backed by a Teiid WS 
+            resource adapter. It will commonly be used with the 
+            <link linkend="texttable">TEXTTABLE</link> or 
+            <link linkend="xmltable">XMLTABLE</link> table functions to use CSV or XML 
+            formated data.
+            </para>
+            
+            <table>
+                <title>Execution Properties</title>
+                <tgroup cols="3">
+                    <colspec colwidth="3*" />
+                    <colspec colwidth="6*" />
+                    <colspec colwidth="2*" />
+                    <thead>
+                        <row>
+                            <entry>Name</entry>
+                            <entry>Description</entry>
+                            <entry>Default</entry>
+                        </row>
+                    </thead>
+                    <tbody>
+                        <row>
+                            <entry>DefaultBinding</entry>
+                            <entry>The binding that should be used if one is not specified.  Can be one of HTTP, SOAP11, or SOAP12</entry>
+                            <entry>SOAP12</entry>
+                        </row>
+                        <row>
+                            <entry>DefaultServiceMode</entry>
+                            <entry>The default service mode.  For SOAP, MESSAGE mode indicates that the request will contain the entire SOAP envelope and not just the contents of the SOAP body.  Can be one of MESSAGE or PAYLOAD</entry>
+                            <entry>PAYLOAD</entry>
+                        </row>
+                        <row>
+                            <entry>XMLParamName</entry>
+                            <entry>Used with the HTTP binding (typically with the GET method) to indicate that the request document should be part of the query string.</entry>
+                            <entry>null - unused</entry>
+                        </row>
+                    </tbody>
+                </tgroup>
+            </table>
+            
+            <para>
+            There are ws importer settings, but it does provide metadata for dynamic VDBs.
+            </para>
+    
+            <section>
+                <title>Usage</title>
+                <para>
+                The WS translator exposes low level procedures for accessing web services.  
+                See also the ws-weather example in the kit.
+                </para>
+
+                <section>
+                    <title>Invoke Procedure</title>
+                    <para>
+                    Invoke allows for multiple binding, or protocol modes, including 
+                    HTTP, SOAP11, and SOAP12. 
+                    </para>
+                    <programlisting>Procedure invoke(binding in STRING, action in STRING, request in XML, endpoint in STRING) returns XML</programlisting>
+
+                    <para>
+                    The binding may be one of null (to use the default) HTTP, SOAP11, or 
+                    SOAP12.  Action with a SOAP binding indicates the SOAPAction value.  
+                    Action with a HTTP binding indicates the HTTP method (GET, POST, etc.), 
+                    which defaults to POST.
+                    </para>
+                    
+                    <para>
+                    A null value for the binding or endpoint will use the default value.  
+                    The default endpoint is specified in the WS resource adapter 
+                    configuration.  The endpoint URL may be absolute or relative.  If it's 
+                    relative then it will be combined with the default endpoint.
+                    </para>
+                    
+                    <para>
+                    Since multiple parameters are not required to have values, it is often 
+                    more clear to call the invoke procedure with named parameter syntax. 
+                    </para> 
+                    <programlisting>call invoke(binding=>'HTTP', action=>'GET')</programlisting>
+                    <para>The request XML should be a valid XML document or root element.</para>
+                </section>
+
+                <section>
+                    <title>InvokeHTTP Procedure</title>
+                    <para>
+                    <methodname>invokeHttp</methodname> can return the byte contents of an HTTP(S) call. 
+                    </para>
+                    <programlisting>Procedure invokeHttp(action in STRING, request in OBJECT, endpoint in STRING, contentType out STRING) returns BLOB</programlisting>
+        
+                    <para>
+                    Action indicates the HTTP method (GET, POST, etc.), which defaults to POST.
+                    </para>
+                    <para>
+                    A null value for endpoint will use the default value.  The default endpoint 
+                    is specified in the WS resource adapter configuration.  The endpoint URL may 
+                    be absolute or relative.  If it's relative then it will be combined with the 
+                    default endpoint.
+                    </para>
+                    <para>
+                    Since multiple parameters are not required to have values, it is often more 
+                    clear to call the invoke procedure with named parameter syntax.
+                    </para>
+                    <programlisting>call invokeHttp(action=>'GET')</programlisting>
+                    
+                    <para>
+                    The request can be one of SQLXML, STRING, BLOB, or CLOB.  The request will be 
+                    sent as the POST payload in byte form.  For STRING/CLOB values this will 
+                    default to the UTF-8 encoding.  To control the byte encoding, see the 
+                    <link linkend="to_bytes">to_bytes</link> function.
+                    </para>
+                </section>
+            </section>
+        </section>
+    </section>
+    
+    <section id="dynamic_vdbs">
+        <title>Dynamic VDBs</title>
+        <para>
+        Teiid integration is available via a "Dynamic VDB" without the need for Teiid Designer 
+        tooling.  While this mode of operation does not yet allow for the creation of view 
+        layers, the underlying sources can still be queried as if they are a single source.  See 
+        the kit's "teiid-example/dynamicvdb-*" for working examples.
+        </para>
+
+        <para>
+        To build a dynamic VDB, you'll need to create a 
+        <filename><replaceable>SOME-NAME</replaceable>-vdb.xml</filename> file.  The XML file captures 
+        information about the VDB, the sources it integrate, and preferences for importing metadata.
+        </para>
+        
+        <note>
+            <para>
+            VDB name pattern must adhere to "-vdb.xml"  for the Teiid VDB deployer to 
+            recognize this file as a dynamic VDB.
+            </para>
+        </note>
+        
+        <para>
+        my-vdb.xml: (The vdb-deployer.xml schema for this file is available in the schema 
+        folder under the docs with the Teiid distribution.)
+        </para>
+        
+        <programlisting role="XML" language="XML"><![CDATA[<vdb name="${vdb-name}" version="${vdb-version}">
+
+    <property name="UseConnectorMetadata" value="..." />
+
+    <!-- define a model fragment for each data source -->
+    <model name="${model-name}">
+        
+        <property name="..." value="..." />
+        ...
+
+        <source name="${source-name}" translator-name="${translator-name}" 
+
+        connection-jndi-name="${deployed-jndi-name}">
+    </model>
+ 
+    <!-- create translator instances that override default properties -->
+
+    <translator name="${translator-name}" type="${translator-type}" />
+ 
+        <property name="..." value="..." /> 
+        ...
+
+    </translator> 
+</vdb>]]></programlisting>
+
+        <section>
+            <title>VDB Element</title>
+            <itemizedlist>
+                <title>Attributes</title>
+                <listitem>
+                    <para>
+                    <emphasis>name</emphasis>
+                    </para>
+                    <para>
+                    The name of the VDB.  The VDB name 
+                    referenced through the driver or datasource during the connection time.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>version</emphasis>
+                    </para>
+                    <para>
+                    The version of the VDB (should be an 
+                    positive integer).  This determines the deployed directory location 
+                    (see Name), and provides an explicit versioning mechanism to the VDB 
+                    name.
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+            <itemizedlist>
+                <title>Property Elements</title>
+                <listitem>
+                    <para>
+                    <emphasis>UseConnectorMetadata</emphasis>
+                    </para>
+                    <para>
+                    Setting to use connector 
+                    supplied metadata. Can be "true" or "cached".  "true" will obtain 
+                    metadata once for every launch of Teiid.   "cached" will save a file 
+                    containing the metadata into the 
+                    <filename><replaceable>PROFILE</replaceable>/data/teiid</filename> directory
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+        </section>
+        
+        <section>
+            <title>Model Element</title>
+            <itemizedlist>
+                <title>Attributes</title>
+                <listitem>
+                    <para>
+                    <emphasis>name</emphasis>
+                    </para>
+                    <para>
+                    The name of the model is used as a 
+                    top level schema name for all of the  metadata imported from the 
+                    connector.  The name should be unique among all Models in the VDB and 
+                    should not contain the '.' character.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>version</emphasis>
+                    </para>
+                    <para>
+                    The version of the VDB (should be an 
+                    positive integer).  This determines the deployed directory location 
+                    (see Name), and provides an explicit versioning mechanism to the VDB 
+                    name.
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+            <itemizedlist>
+                <title>Source Element</title>
+                <listitem>
+                    <para>
+                    <emphasis>name</emphasis>
+                    </para>
+                    <para>
+                    The name of the source to use for this 
+                    model. This can be any name you like, but will typically be the same 
+                    as the model name.  Having a name different than the model name is 
+                    only useful in multi-source scenarios.	
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>translator-name</emphasis>
+                    </para>
+                    <para>
+                    The name or type of the Teiid Translator to use.  Possible values include 
+                    the built-in types (ws, file, ldap, oracle, sqlserver, db2, derby, etc.) 
+                    and translators defined in the translators section. 
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>connection-jndi-name</emphasis>
+                    </para>
+                    <para>
+                    The JNDI name of this source's connection factory. There should be a 
+                    corresponding "-ds.xml" file that defines the connection factory in 
+                    the JBoss AS.  Check out the  deploying VDB dependencies section for 
+                    info. You also need to deploy these connection factories before you 
+                    can deploy the VDB.	
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+            <itemizedlist>
+                <title>Property Elements</title>
+                <listitem>
+                    <para>
+                    <emphasis>importer.&lt;propertyname&gt;</emphasis>
+                    </para>
+                    <para>
+                    Property to be used by the connector importer for the model for purposes 
+                    importing metadata.  See possible property name/values in the 
+                    Translator specific section. Note that using these properties you 
+                    can narrow or widen the data elements available for integration.
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+        </section>
+        <section>
+            <title>Translator Element</title>
+            <itemizedlist>
+                <title>Attributes</title>
+                <listitem>
+                    <para>
+                    <emphasis>name</emphasis>
+                    </para>
+                    <para>
+                    The name of the the Translator.  Referenced by the source element.
+                    </para>
+                </listitem>
+                <listitem>
+                    <para>
+                    <emphasis>type</emphasis>
+                    </para>
+                    <para>
+                    The base type of the Translator.  Can be one of the built-in types (ws, 
+                    file, ldap, oracle, sqlserver, db2, derby, etc.).
+                    </para>
+                </listitem>
+            </itemizedlist>
+            
+            <itemizedlist>
+                <title>Property Elements</title>
+                <listitem>
+                    <para>
+                    Set a value that overrides a translator default property.  See 
+                    possible property name/values in the Translator specific section.
+                    </para>
+                </listitem>
+            </itemizedlist>        
+        </section>
+        
+    </section>
+    <section>
+        <title>Multi-Source Models and VDB</title>
+        <para>
+        When you have multiple instances of data that are using identical schema 
+        (horizontal sharding), Teiid can help you aggregate data across all the 
+        instances, using "multi-source" models. In this scenario, instead of 
+        creating/importing a model for every data source, user needs to define one 
+        source model that represents the schema and configure multiple data "sources" 
+        underneath it. During runtime, when a query issued against this model, the query 
+        engine analyzes the information and gathers the required data from all the 
+        sources configured and aggregates the results and provides in a single result set.
+        </para>
+    
+        <para>
+        To mark a model as multi-source, the user needs to supply property called 
+        <property>supports-multi-source-bindings</property>, in the "vdb.xml" file.  
+        Also, the user needs to define multiple sources. Here is code example showing dynamic vdb with single model with 
+        multiple sources defined.
+        </para>
+        
+        <programlisting role="XML" language="XML"><![CDATA[<vdb name="vdbname" version="1">
+    <model visible="true" type="PHYSICAL" name="Customers" path="/Test/Customers.xmi">
+        <property name="supports-multi-source-bindings" value="true"/>
+        <source name="chicago" 
+            translator-name="oracle" connection-jndi-name="chicago-customers"/>
+        <source name="newyork" 
+            translator-name="oracle" connection-jndi-name="newyork-customers"/>
+        <source name="la" 
+            translator-name="oracle" connection-jndi-name="la-customers"/>
+    </model>
+</vdb>]]></programlisting>
+
+        <para>
+        In the above example, the VDB defined has single model called <literal>Customers</literal>, 
+        that has multiple sources (<literal>chicago</literal>, <literal>newyork</literal>, 
+        and <literal>la</literal>) that define different instances of data. Every 
+        time a model is marked as "multi-source", the 
+        runtime engine adds a additional column called "SOURCE_NAME" to every table in 
+        that model. This column maps to the source's name from the XML. In 
+        the above XML code that would be <literal>chicago</literal>, <literal>la</literal>, 
+        <literal>newyork</literal>. This allows queries like the following:
+        </para>
+        
+        <programlisting language="SQL"><![CDATA[select * from table where SOURCE_NAME = 'newyork'
+update table column=value  where SOURCE_NAME='chicago'
+delete from table where column = x and SOURCE_NAME='la'
+insert into table (column, SOURCE_NAME) VALUES ('value', 'newyork')]]></programlisting>
+      
+        <para>
+        Note that when user do not supply the "SOURCE_NAME" in the criteria, the command applies 
+        to all the sources. If SOURCE_NAME supplied, the query is executed only aginst the source specified. 
+        Another useful feature along with this feature is 
+        "partial results" to skip unavailable sources if they are down.
+        </para>
+        
+        <note>
+            <para>
+            Currently the tooling support for managing the multi-source feature is 
+            limited, so if you need to use this feature build the VDB as usual in 
+            the Teiid Designer and then edit the "vdb.xml" file in the VDB archive 
+            using a Text editor to add the additional sources as defined above. 
+            You must deploy a separate data source for each source defined in the xml file.
+            </para>
+        </note>
+
+        <note>
+            <para>
+            If you would like to use "SOURCE_NAME" in your transformations to control which sources are accessed or updated, 
+            you would manually need to add this extra column on your view table in
+            the Designer. This column will not be automatically added on the source table, when you import 
+            the medata from source.
+            </para>
+        </note>        
+    </section>
+
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,57 +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" [
-<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
-%CustomDTD;
-]>
-<chapter id="updatable_views">
-	<title>Updatable Views</title>
-	
-	<para>Any view may be marked as updatable.  In many circumstances the view definition may allow the view to be inherently 
-	updatable without the need to manually define handing of INSERT/UPDATE/DELETE operations.</para>
-	
-	<para>An inherently updatable view cannot be defined with a query that has:</para>
-	
-	<itemizedlist>
-		<listitem>
-			<para>A set operation (INTERSECT, EXCEPT, UNION, UNION ALL)</para>
-		</listitem>
-		<listitem>
-			<para>SELECT DISTINCT</para>
-		</listitem>
-		<listitem>
-			<para>Aggregation (aggregate functions, GROUP BY, HAVING)</para>
-		</listitem>
-		<listitem>
-			<para>A LIMIT clause</para>
-		</listitem>
-	</itemizedlist>
-	
-	<para>Any view column that is not mapped directly to a column is not updatable and cannot be targeted by an UPDATE set
-	 clause or be an INSERT column.</para>
-	 
-	<para>If a view is defined by a join query or has a WITH clause it may still be inherently updatable.  However in these situations there
-	 are further restrictions and the resulting query plan may execute multiple statements.  
-	 For a non-simple query to be updatable, it is required:</para>
-	
-	<itemizedlist>
-		<listitem>
-			<para>An INSERT/UPDATE can only modify a single <xref linkend="key_preserved_table"/>.</para>
-		</listitem>
-		<listitem>
-			<para>To allow DELETE operations there must be only a single <xref linkend="key_preserved_table"/>.</para>
-		</listitem>
-	</itemizedlist>
-	
-	<para>If the default handling is not available or you wish to have an alternative implementation of an INSERT/UPDATE/DELETE, 
-	then you may use <xref linkend="update_procedures"/> to define procedures to handle the respective operations.</para>
-	  
-	<section id="key_preserved_table">
-		<title>Key-preserved Table</title>
-		
-		<para>A key-preserved table has a primary or unique key that would remain unique if it were projected into the result of the query.  
-		Note that it is not actually required for a view to reference the key columns in the SELECT clause.  
-		The query engine can detect a key preserved table by analyzing the join structure.  
-		The engine will ensure that a join of a key-preserved table must be against one of its foreign keys.</para>		
-	</section>
-	
-</chapter>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml (from rev 2761, trunk/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/documentation/reference/src/main/docbook/en-US/content/updatable_views.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,60 @@
+<?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" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter id="updatable_views">
+	<title>Updatable Views</title>
+	
+	<para>Any view may be marked as updatable.  In many circumstances the view definition may allow the view to be inherently 
+	updatable without the need to manually define handing of INSERT/UPDATE/DELETE operations.</para>
+	
+	<para>An inherently updatable view cannot be defined with a query that has:</para>
+	
+	<itemizedlist>
+		<listitem>
+			<para>A set operation (INTERSECT, EXCEPT, UNION).</para>
+		</listitem>
+		<listitem>
+			<para>SELECT DISTINCT</para>
+		</listitem>
+		<listitem>
+			<para>Aggregation (aggregate functions, GROUP BY, HAVING)</para>
+		</listitem>
+		<listitem>
+			<para>A LIMIT clause</para>
+		</listitem>
+	</itemizedlist>
+	
+	<para>A UNION ALL can define an inherently updatable view only if each of the UNION branches is itself inherently updatable.  
+	A view defined by a UNION ALL though does not support inherent INSERTs.</para>
+	
+	<para>Any view column that is not mapped directly to a column is not updatable and cannot be targeted by an UPDATE set
+	 clause or be an INSERT column.</para>
+	 
+	<para>If a view is defined by a join query or has a WITH clause it may still be inherently updatable.  However in these situations there
+	 are further restrictions and the resulting query plan may execute multiple statements.  
+	 For a non-simple query to be updatable, it is required:</para>
+	
+	<itemizedlist>
+		<listitem>
+			<para>An INSERT/UPDATE can only modify a single <xref linkend="key_preserved_table"/>.</para>
+		</listitem>
+		<listitem>
+			<para>To allow DELETE operations there must be only a single <xref linkend="key_preserved_table"/>.</para>
+		</listitem>
+	</itemizedlist>
+	
+	<para>If the default handling is not available or you wish to have an alternative implementation of an INSERT/UPDATE/DELETE, 
+	then you may use <xref linkend="update_procedures"/> to define procedures to handle the respective operations.</para>
+	  
+	<section id="key_preserved_table">
+		<title>Key-preserved Table</title>
+		
+		<para>A key-preserved table has a primary or unique key that would remain unique if it were projected into the result of the query.  
+		Note that it is not actually required for a view to reference the key columns in the SELECT clause.  
+		The query engine can detect a key preserved table by analyzing the join structure.  
+		The engine will ensure that a join of a key-preserved table must be against one of its foreign keys.</para>		
+	</section>
+	
+</chapter>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml
===================================================================
--- trunk/engine/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/engine/pom.xml (from rev 2777, trunk/engine/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,315 +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.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.impl.DataPolicyMetadata;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.CoreConstants;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
-import org.teiid.logging.AuditMessage;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.logging.MessageLevel;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Symbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.validator.AbstractValidationVisitor;
-
-
-public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
-    
-	public enum Context {
-		QUERY,
-		INSERT,
-		UPDATE,
-		DELETE,
-		STORED_PROCEDURE;
-    }
-    
-    private HashMap<String, DataPolicy> allowedPolicies;
-    private String userName;
-
-    public AuthorizationValidationVisitor(HashMap<String, DataPolicy> policies, String user) {
-        this.allowedPolicies = policies;
-        this.userName = user;
-    }
-
-    // ############### Visitor methods for language objects ##################
-    
-    public void visit(Delete obj) {
-    	validateEntitlements(obj);
-    }
-
-    public void visit(Insert obj) {
-    	validateEntitlements(obj);
-    }
-
-    public void visit(Query obj) {
-    	validateEntitlements(obj);
-    }
-
-    public void visit(Update obj) {
-    	validateEntitlements(obj);
-    }
-
-    public void visit(StoredProcedure obj) {
-    	validateEntitlements(obj);
-    }
-    
-    public void visit(Function obj) {
-    	if (FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
-    		try {
-				ResolverUtil.ResolvedLookup lookup = ResolverUtil.resolveLookup(obj, this.getMetadata());
-    			List<Symbol> symbols = new LinkedList<Symbol>();
-				symbols.add(lookup.getGroup());
-				symbols.add(lookup.getKeyElement());
-				symbols.add(lookup.getReturnElement());
-	    		validateEntitlements(symbols, DataPolicy.PermissionType.READ, Context.QUERY);
-			} catch (TeiidComponentException e) {
-				handleException(e, obj);
-			} catch (TeiidProcessingException e) {
-				handleException(e, obj);
-			}
-    	}
-    }
-
-    // ######################### Validation methods #########################
-
-    /**
-     * Validate insert entitlements
-     */
-    protected void validateEntitlements(Insert obj) {
-        validateEntitlements(
-            obj.getVariables(),
-            DataPolicy.PermissionType.CREATE,
-            Context.INSERT);
-    }
-
-    /**
-     * Validate update entitlements
-     */
-    protected void validateEntitlements(Update obj) {
-        // Check that all elements used in criteria have read permission
-        if (obj.getCriteria() != null) {
-            validateEntitlements(
-                ElementCollectorVisitor.getElements(obj.getCriteria(), true),
-                DataPolicy.PermissionType.READ,
-                Context.UPDATE);
-        }
-
-        // The variables from the changes must be checked for UPDATE entitlement
-        // validateEntitlements on all the variables used in the update.
-        validateEntitlements(obj.getChangeList().getClauseMap().keySet(), DataPolicy.PermissionType.UPDATE, Context.UPDATE);
-    }
-
-    /**
-     * Validate delete entitlements
-     */
-    protected void validateEntitlements(Delete obj) {
-        // Check that all elements used in criteria have read permission
-        if (obj.getCriteria() != null) {
-            validateEntitlements(
-                ElementCollectorVisitor.getElements(obj.getCriteria(), true),
-                DataPolicy.PermissionType.READ,
-                Context.DELETE);
-        }
-
-        // Check that all elements of group being deleted have delete permission
-        validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.DELETE, Context.DELETE);
-    }
-
-    /**
-     * Validate query entitlements
-     */
-    protected void validateEntitlements(Query obj) {
-        // If query contains SELECT INTO, validate INTO portion
-        Into intoObj = obj.getInto();
-        if ( intoObj != null ) {
-            GroupSymbol intoGroup = intoObj.getGroup();
-            List<ElementSymbol> intoElements = null;
-            try {
-                intoElements = ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata());
-            } catch (QueryMetadataException err) {
-                handleException(err, intoGroup);
-            } catch (TeiidComponentException err) {
-                handleException(err, intoGroup);
-            }
-            validateEntitlements(intoElements,
-                                 DataPolicy.PermissionType.CREATE,
-                                 Context.INSERT);
-        }
-
-        // Validate this query's entitlements
-        Collection entitledObjects = GroupCollectorVisitor.getGroups(obj, true);
-        if (!isXMLCommand(obj)) {
-            entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
-        }
-
-        if(entitledObjects.size() == 0) {
-            return;
-        }
-        
-        validateEntitlements(entitledObjects, DataPolicy.PermissionType.READ, Context.QUERY);
-    }
-
-    /**
-     * Validate query entitlements
-     */
-    protected void validateEntitlements(StoredProcedure obj) {
-        validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.READ, Context.STORED_PROCEDURE);
-    }
-
-    private String getActionLabel(DataPolicy.PermissionType actionCode) {
-        switch(actionCode) {
-            case READ:    return "Read"; //$NON-NLS-1$
-            case CREATE:  return "Create"; //$NON-NLS-1$
-            case UPDATE:  return "Update"; //$NON-NLS-1$
-            case DELETE:  return "Delete"; //$NON-NLS-1$
-            default:    return "UNKNOWN"; //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Check that the user is entitled to access all data elements in the command.
-     *
-     * @param symbols The collection of <code>Symbol</code>s affected by these actions.
-     * @param actionCode The actions to validate for
-     * @param auditContext The {@link AuthorizationService} to use when resource auditing is done.
-     */
-    protected void validateEntitlements(Collection<? extends Symbol> symbols, DataPolicy.PermissionType actionCode, Context auditContext) {
-        Map<String, Symbol> nameToSymbolMap = new HashMap<String, Symbol>();
-        for (Symbol symbol : symbols) {
-            try {
-                String fullName = null;
-                Object metadataID = null;
-                if(symbol instanceof ElementSymbol) {                    
-                    metadataID = ((ElementSymbol)symbol).getMetadataID();
-                    if (metadataID instanceof MultiSourceElement || metadataID instanceof TempMetadataID) {
-                        continue;
-                    }
-                } else if(symbol instanceof GroupSymbol) {
-                    GroupSymbol group = (GroupSymbol)symbol;
-                    metadataID = group.getMetadataID();
-                    if (metadataID instanceof TempMetadataID && !group.isProcedure()) {
-                        continue;
-                    }
-                }
-                fullName = getMetadata().getFullName(metadataID);
-                Object modelId = getMetadata().getModelID(metadataID);
-                String modelName = getMetadata().getFullName(modelId);
-                if (CoreConstants.SYSTEM_MODEL.equals(modelName) || CoreConstants.ODBC_MODEL.equals(modelName)) {
-                	continue;
-                }
-                nameToSymbolMap.put(fullName, symbol);
-            } catch(QueryMetadataException e) {
-                handleException(e);
-            } catch(TeiidComponentException e) {
-                handleException(e);
-            }
-        }
-
-        if (!nameToSymbolMap.isEmpty()) {
-            Collection<String> inaccessibleResources = getInaccessibleResources(actionCode, nameToSymbolMap.keySet(), auditContext);
-            if(inaccessibleResources.size() > 0) {                              
-            	List<Symbol> inaccessibleSymbols = new ArrayList<Symbol>(inaccessibleResources.size());
-            	for (String name : inaccessibleResources) {
-                    inaccessibleSymbols.add(nameToSymbolMap.get(name));
-                }
-                
-                // CASE 2362 - do not include the names of the elements for which the user
-                // is not authorized in the exception message
-                
-                handleValidationError(
-                    QueryPlugin.Util.getString("ERR.018.005.0095", userName, getActionLabel(actionCode)), //$NON-NLS-1$                    
-                    inaccessibleSymbols);
-            }
-        }
-
-    }
-
-    /**
-     * Out of resources specified, return the subset for which the specified not have authorization to access.
-     */
-    public Set<String> getInaccessibleResources(DataPolicy.PermissionType action, Set<String> resources, Context context) {
-        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
-	        // Audit - request
-	    	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-request", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
-	    	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
-        }
-        
-        HashSet<String> results = new HashSet<String>(resources);
-        
-		for(DataPolicy p:this.allowedPolicies.values()) {
-			DataPolicyMetadata policy = (DataPolicyMetadata)p;
-			
-			if (results.isEmpty()) {
-				break;
-			}
-			
-			Iterator<String> i = results.iterator();
-			while (i.hasNext()) {				
-				if (policy.allows(i.next(), action)) {
-					i.remove();
-				}
-			}
-		}
-
-		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
-	        if (results.isEmpty()) {
-	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-granted all", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
-	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
-	        } else {
-	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-denied", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
-	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
-	        }
-		}
-        return results;
-    }    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java (from rev 2765, trunk/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,365 @@
+/*
+ * 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.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.impl.DataPolicyMetadata;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.CoreConstants;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
+import org.teiid.logging.AuditMessage;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Symbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.validator.AbstractValidationVisitor;
+
+
+public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
+    
+	public enum Context {
+		CREATE,
+		DROP,
+		QUERY,
+		INSERT,
+		UPDATE,
+		DELETE,
+		STORED_PROCEDURE;
+    }
+    
+    private HashMap<String, DataPolicy> allowedPolicies;
+    private String userName;
+    private boolean allowCreateTemporaryTablesDefault = true;
+
+    public AuthorizationValidationVisitor(HashMap<String, DataPolicy> policies, String user) {
+        this.allowedPolicies = policies;
+        this.userName = user;
+    }
+    
+    public void setAllowCreateTemporaryTablesDefault(
+			boolean allowCreateTemporaryTablesDefault) {
+		this.allowCreateTemporaryTablesDefault = allowCreateTemporaryTablesDefault;
+	}
+
+    // ############### Visitor methods for language objects ##################
+    
+    @Override
+    public void visit(Create obj) {
+    	Set<String> resources = Collections.singleton(obj.getTable().getName());
+    	Collection<GroupSymbol> symbols = Arrays.asList(obj.getTable());
+    	validateTemp(resources, symbols, Context.CREATE);
+    }
+
+	private void validateTemp(Set<String> resources,
+			Collection<GroupSymbol> symbols, Context context) {
+		logRequest(resources, context);
+        
+    	boolean allowed = false;
+    	for(DataPolicy p:this.allowedPolicies.values()) {
+			DataPolicyMetadata policy = (DataPolicyMetadata)p;
+			
+			if (policy.isAllowCreateTemporaryTables() == null) {
+				if (allowCreateTemporaryTablesDefault) {
+					allowed = true;
+					break;
+				}
+			} else if (policy.isAllowCreateTemporaryTables()) {
+				allowed = true;
+				break;
+			}
+		}
+    	
+    	logResult(resources, context, allowed);
+    	if (!allowed) {
+		    handleValidationError(
+			        QueryPlugin.Util.getString("ERR.018.005.0095", userName, "CREATE_TEMPORARY_TABLES"), //$NON-NLS-1$                   
+			        symbols);
+    	}
+	}
+
+	private void logRequest(Set<String> resources, Context context) {
+		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
+	        // Audit - request
+	    	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-request", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	    	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
+        }
+	}
+    
+    @Override
+    public void visit(Drop obj) {
+    	Set<String> resources = Collections.singleton(obj.getTable().getName());
+    	Collection<GroupSymbol> symbols = Arrays.asList(obj.getTable());
+    	validateTemp(resources, symbols, Context.CREATE);
+    }
+    
+    public void visit(Delete obj) {
+    	validateEntitlements(obj);
+    }
+
+    public void visit(Insert obj) {
+    	validateEntitlements(obj);
+    }
+
+    public void visit(Query obj) {
+    	validateEntitlements(obj);
+    }
+
+    public void visit(Update obj) {
+    	validateEntitlements(obj);
+    }
+
+    public void visit(StoredProcedure obj) {
+    	validateEntitlements(obj);
+    }
+    
+    public void visit(Function obj) {
+    	if (FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
+    		try {
+				ResolverUtil.ResolvedLookup lookup = ResolverUtil.resolveLookup(obj, this.getMetadata());
+    			List<Symbol> symbols = new LinkedList<Symbol>();
+				symbols.add(lookup.getGroup());
+				symbols.add(lookup.getKeyElement());
+				symbols.add(lookup.getReturnElement());
+	    		validateEntitlements(symbols, DataPolicy.PermissionType.READ, Context.QUERY);
+			} catch (TeiidComponentException e) {
+				handleException(e, obj);
+			} catch (TeiidProcessingException e) {
+				handleException(e, obj);
+			}
+    	}
+    }
+
+    // ######################### Validation methods #########################
+
+    /**
+     * Validate insert entitlements
+     */
+    protected void validateEntitlements(Insert obj) {
+        validateEntitlements(
+            obj.getVariables(),
+            DataPolicy.PermissionType.CREATE,
+            Context.INSERT);
+    }
+
+    /**
+     * Validate update entitlements
+     */
+    protected void validateEntitlements(Update obj) {
+        // Check that all elements used in criteria have read permission
+        if (obj.getCriteria() != null) {
+            validateEntitlements(
+                ElementCollectorVisitor.getElements(obj.getCriteria(), true),
+                DataPolicy.PermissionType.READ,
+                Context.UPDATE);
+        }
+
+        // The variables from the changes must be checked for UPDATE entitlement
+        // validateEntitlements on all the variables used in the update.
+        validateEntitlements(obj.getChangeList().getClauseMap().keySet(), DataPolicy.PermissionType.UPDATE, Context.UPDATE);
+    }
+
+    /**
+     * Validate delete entitlements
+     */
+    protected void validateEntitlements(Delete obj) {
+        // Check that all elements used in criteria have read permission
+        if (obj.getCriteria() != null) {
+            validateEntitlements(
+                ElementCollectorVisitor.getElements(obj.getCriteria(), true),
+                DataPolicy.PermissionType.READ,
+                Context.DELETE);
+        }
+
+        // Check that all elements of group being deleted have delete permission
+        validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.DELETE, Context.DELETE);
+    }
+
+    /**
+     * Validate query entitlements
+     */
+    protected void validateEntitlements(Query obj) {
+        // If query contains SELECT INTO, validate INTO portion
+        Into intoObj = obj.getInto();
+        if ( intoObj != null ) {
+            GroupSymbol intoGroup = intoObj.getGroup();
+            List<ElementSymbol> intoElements = null;
+            try {
+                intoElements = ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata());
+            } catch (QueryMetadataException err) {
+                handleException(err, intoGroup);
+            } catch (TeiidComponentException err) {
+                handleException(err, intoGroup);
+            }
+            validateEntitlements(intoElements,
+                                 DataPolicy.PermissionType.CREATE,
+                                 Context.INSERT);
+        }
+
+        // Validate this query's entitlements
+        Collection entitledObjects = GroupCollectorVisitor.getGroups(obj, true);
+        if (!isXMLCommand(obj)) {
+            entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
+        }
+
+        if(entitledObjects.size() == 0) {
+            return;
+        }
+        
+        validateEntitlements(entitledObjects, DataPolicy.PermissionType.READ, Context.QUERY);
+    }
+
+    /**
+     * Validate query entitlements
+     */
+    protected void validateEntitlements(StoredProcedure obj) {
+        validateEntitlements(Arrays.asList(obj.getGroup()), DataPolicy.PermissionType.READ, Context.STORED_PROCEDURE);
+    }
+
+    /**
+     * Check that the user is entitled to access all data elements in the command.
+     *
+     * @param symbols The collection of <code>Symbol</code>s affected by these actions.
+     * @param actionCode The actions to validate for
+     * @param auditContext The {@link AuthorizationService} to use when resource auditing is done.
+     */
+    protected void validateEntitlements(Collection<? extends Symbol> symbols, DataPolicy.PermissionType actionCode, Context auditContext) {
+        Map<String, Symbol> nameToSymbolMap = new HashMap<String, Symbol>();
+        for (Symbol symbol : symbols) {
+            try {
+                String fullName = null;
+                Object metadataID = null;
+                if(symbol instanceof ElementSymbol) {                    
+                    metadataID = ((ElementSymbol)symbol).getMetadataID();
+                    if (metadataID instanceof MultiSourceElement || metadataID instanceof TempMetadataID) {
+                        continue;
+                    }
+                } else if(symbol instanceof GroupSymbol) {
+                    GroupSymbol group = (GroupSymbol)symbol;
+                    metadataID = group.getMetadataID();
+                    if (metadataID instanceof TempMetadataID && !group.isProcedure()) {
+                        continue;
+                    }
+                }
+                fullName = getMetadata().getFullName(metadataID);
+                Object modelId = getMetadata().getModelID(metadataID);
+                String modelName = getMetadata().getFullName(modelId);
+                if (CoreConstants.SYSTEM_MODEL.equals(modelName) || CoreConstants.ODBC_MODEL.equals(modelName)) {
+                	continue;
+                }
+                nameToSymbolMap.put(fullName, symbol);
+            } catch(QueryMetadataException e) {
+                handleException(e);
+            } catch(TeiidComponentException e) {
+                handleException(e);
+            }
+        }
+
+        if (!nameToSymbolMap.isEmpty()) {
+			Collection<String> inaccessibleResources = getInaccessibleResources(actionCode, nameToSymbolMap.keySet(), auditContext);
+			if(inaccessibleResources.size() > 0) {                              
+				List<Symbol> inaccessibleSymbols = new ArrayList<Symbol>(inaccessibleResources.size());
+				for (String name : inaccessibleResources) {
+			        inaccessibleSymbols.add(nameToSymbolMap.get(name));
+			    }
+			    
+			    // CASE 2362 - do not include the names of the elements for which the user
+			    // is not authorized in the exception message
+			    
+			    handleValidationError(
+			        QueryPlugin.Util.getString("ERR.018.005.0095", userName, actionCode), //$NON-NLS-1$                    
+			        inaccessibleSymbols);
+			}
+        }
+	}
+
+    /**
+     * Out of resources specified, return the subset for which the specified not have authorization to access.
+     */
+    public Set<String> getInaccessibleResources(DataPolicy.PermissionType action, Set<String> resources, Context context) {
+        logRequest(resources, context);
+        
+        HashSet<String> results = new HashSet<String>(resources);
+        
+		for(DataPolicy p:this.allowedPolicies.values()) {
+			DataPolicyMetadata policy = (DataPolicyMetadata)p;
+			
+			if (results.isEmpty()) {
+				break;
+			}
+			
+			Iterator<String> i = results.iterator();
+			while (i.hasNext()) {				
+				if (policy.allows(i.next(), action)) {
+					i.remove();
+				}
+			}
+		}
+
+		logResult(resources, context, results.isEmpty());
+        return results;
+    }
+
+	private void logResult(Set<String> resources, Context context,
+			boolean granted) {
+		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
+	        if (granted) {
+	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-granted all", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
+	        } else {
+	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-denied", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
+	        }
+		}
+	}    
+}

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

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

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

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java (from rev 2765, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,855 @@
+/*
+ * 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){
+			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.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,403 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-
-import javax.activation.DataSource;
-import javax.xml.transform.Source;
-
-import org.teiid.client.SourceWarning;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.common.buffer.FileStore;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.BlobImpl;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.InputStreamFactory;
-import org.teiid.core.types.SQLXMLImpl;
-import org.teiid.core.types.StandardXMLTranslator;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.dqp.internal.datamgr.ConnectorWork;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.AtomicResultsMessage;
-import org.teiid.query.processor.xml.XMLUtil;
-import org.teiid.query.processor.xml.XMLUtil.FileStoreInputStreamFactory;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.translator.DataNotAvailableException;
-import org.teiid.translator.TranslatorException;
-
-
-/**
- * This tuple source impl can only be used once; once it is closed, it 
- * cannot be reopened and reused.
- * 
- * TODO: the handling of DataNotAvailable is awkward.
- * In the multi-threaded case we'd like to not even
- * notify the parent plan and just schedule the next poll. 
- */
-public class DataTierTupleSource implements TupleSource {
-	
-    // Construction state
-    private final AtomicRequestMessage aqr;
-    private final RequestWorkItem workItem;
-    private final ConnectorWork cwi;
-    private final DataTierManagerImpl dtm;
-    
-    private boolean[] convertToRuntimeType;
-    private boolean[] convertToDesiredRuntimeType;
-    private Class<?>[] schema;
-    
-    // Data state
-    private int index;
-    private int rowsProcessed;
-    private AtomicResultsMessage arm;
-    private boolean closed;
-    private volatile boolean canceled;
-    private boolean executed;
-    private volatile boolean done;
-    private boolean explicitClose;
-    
-    private volatile ResultsFuture<AtomicResultsMessage> futureResult;
-    private volatile boolean running;
-    
-    public DataTierTupleSource(AtomicRequestMessage aqr, RequestWorkItem workItem, ConnectorWork cwi, DataTierManagerImpl dtm) {
-        this.aqr = aqr;
-        this.workItem = workItem;
-        this.cwi = cwi;
-        this.dtm = dtm;
-		List<SingleElementSymbol> symbols = this.aqr.getCommand().getProjectedSymbols();
-		this.schema = new Class[symbols.size()];
-        this.convertToDesiredRuntimeType = new boolean[symbols.size()];
-		this.convertToRuntimeType = new boolean[symbols.size()];
-		for (int i = 0; i < symbols.size(); i++) {
-			SingleElementSymbol symbol = symbols.get(i);
-			this.schema[i] = symbol.getType();
-			this.convertToDesiredRuntimeType[i] = true;
-			this.convertToRuntimeType[i] = true;
-		}
-        
-    	Assertion.isNull(workItem.getConnectorRequest(aqr.getAtomicRequestID()));
-        workItem.addConnectorRequest(aqr.getAtomicRequestID(), this);
-        if (!aqr.isTransactional()) {
-        	addWork();
-        }
-    }
-
-	private void addWork() {
-		futureResult = dtm.addWork(new Callable<AtomicResultsMessage>() {
-			@Override
-			public AtomicResultsMessage call() throws Exception {
-				return getResults();
-			}
-		}, 100);
-		futureResult.addCompletionListener(new ResultsFuture.CompletionListener<AtomicResultsMessage>() {
-			public void onCompletion(ResultsFuture<AtomicResultsMessage> future) {
-				workItem.moreWork();
-			}
-		});
-	}
-
-	private List correctTypes(List row) throws TransformationException {
-		//TODO: add a proper intermediate schema
-		for (int i = 0; i < row.size(); i++) {
-			Object value = row.get(i);
-			if (value == null) {
-				continue;
-			}
-			if (convertToRuntimeType[i]) {
-				boolean lob = !arm.supportsCloseWithLobs() && DataTypeManager.isLOB(value.getClass());
-				Object result = convertToRuntimeType(value, this.schema[i]);
-				if (value == result && !DataTypeManager.DefaultDataClasses.OBJECT.equals(this.schema[i])) {
-					convertToRuntimeType[i] = false;
-				} else {
-					if (lob && DataTypeManager.isLOB(result.getClass()) && DataTypeManager.isLOB(this.schema[i])) {
-						explicitClose = true;
-					}				
-					row.set(i, result);
-					value = result;
-				}
-			}
-			if (convertToDesiredRuntimeType[i]) {
-				if (value != null) {
-					Object result = DataTypeManager.transformValue(value, value.getClass(), this.schema[i]);
-					if (value == result) {
-						convertToDesiredRuntimeType[i] = false;
-						continue;
-					}
-					row.set(i, result);
-				}
-			} else {
-				row.set(i, DataTypeManager.getCanonicalValue(value));
-			}
-		}
-		return row;
-	}
-
-	private Object convertToRuntimeType(Object value, Class<?> desiredType) throws TransformationException {
-		if (value instanceof DataSource && (!(value instanceof Source) || desiredType != DataTypeManager.DefaultDataClasses.XML)) {
-			if (value instanceof InputStreamFactory) {
-				return new BlobType(new BlobImpl((InputStreamFactory)value));
-			}
-			FileStore fs = dtm.getBufferManager().createFileStore("bytes"); //$NON-NLS-1$
-			//TODO: guess at the encoding from the content type
-			FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
-			
-			try {
-				ObjectConverterUtil.write(fsisf.getOuputStream(), ((DataSource)value).getInputStream(), -1);
-			} catch (IOException e) {
-				throw new TransformationException(e, e.getMessage());
-			}
-			return new BlobType(new BlobImpl(fsisf));
-		}
-		if (value instanceof Source) {
-			if (value instanceof InputStreamFactory) {
-				return new XMLType(new SQLXMLImpl((InputStreamFactory)value));
-			}
-			StandardXMLTranslator sxt = new StandardXMLTranslator((Source)value);
-			SQLXMLImpl sqlxml;
-			try {
-				sqlxml = XMLUtil.saveToBufferManager(dtm.getBufferManager(), sxt);
-			} catch (TeiidComponentException e) {
-				throw new TeiidRuntimeException(e);
-			} catch (TeiidProcessingException e) {
-				throw new TeiidRuntimeException(e);
-			}
-			return new XMLType(sqlxml);
-		}
-		return DataTypeManager.convertToRuntimeType(value);
-	}
-
-    public List<?> nextTuple() throws TeiidComponentException, TeiidProcessingException {
-    	while (true) {
-    		if (arm == null) {
-    			AtomicResultsMessage results = null;
-    			try {
-	    			if (futureResult != null || !aqr.isTransactional()) {
-	    				results = asynchGet();
-	    			} else {
-	    				results = getResults();
-	    			}
-    			} catch (TranslatorException e) {
-    				exceptionOccurred(e, true);
-    			} catch (DataNotAvailableException e) {
-    				dtm.scheduleWork(new Runnable() {
-    					@Override
-    					public void run() {
-							workItem.moreWork();
-    					}
-    				}, 10, e.getRetryDelay());
-    				throw BlockedException.INSTANCE;
-    			} 
-    			receiveResults(results);
-    		}
-	    	if (index < arm.getResults().length) {
-	            return correctTypes(this.arm.getResults()[index++]);
-	        }
-	    	arm = null;
-	    	if (isDone()) {
-	    		return null;
-	    	}
-    	}
-    }
-
-	private AtomicResultsMessage asynchGet()
-			throws BlockedException, TeiidProcessingException,
-			TeiidComponentException, TranslatorException {
-		if (futureResult == null) {
-			addWork();
-		}
-		if (!futureResult.isDone()) {
-			throw BlockedException.INSTANCE;
-		}
-		ResultsFuture<AtomicResultsMessage> currentResults = futureResult;
-		futureResult = null;
-		AtomicResultsMessage results = null;
-		try {
-			results = currentResults.get();
-			if (results.getFinalRow() < 0) {
-				addWork();
-			}
-		} catch (InterruptedException e) {
-			throw new TeiidRuntimeException(e);
-		} catch (ExecutionException e) {
-			if (e.getCause() instanceof TeiidProcessingException) {
-				throw (TeiidProcessingException)e.getCause();
-			}
-			if (e.getCause() instanceof TeiidComponentException) {
-				throw (TeiidComponentException)e.getCause();
-			}
-			if (e.getCause() instanceof TranslatorException) {
-				throw (TranslatorException)e.getCause();
-			}
-			if (e.getCause() instanceof RuntimeException) {
-				throw (RuntimeException)e.getCause();
-			}
-			//shouldn't happen
-			throw new RuntimeException(e);
-		}
-		return results;
-	}
-
-	private AtomicResultsMessage getResults()
-			throws BlockedException, TeiidComponentException,
-			TranslatorException {
-		AtomicResultsMessage results = null;
-		try {
-			running = true;
-			if (!executed) {
-				results = cwi.execute();
-				executed = true;
-			} else {
-				results = cwi.more();
-			}
-		} finally {
-			running = false;
-		}
-		return results;
-	}
-    
-    public boolean isQueued() {
-    	ResultsFuture<AtomicResultsMessage> future = futureResult;
-    	return !running && future != null && !future.isDone();
-    }
-
-	public boolean isDone() {
-		return done;
-	}
-    
-    public boolean isRunning() {
-		return running;
-	}
-    
-    public void fullyCloseSource() {
-    	if (!closed) {
-    		if (cwi != null) {
-		    	workItem.closeAtomicRequest(this.aqr.getAtomicRequestID());
-		    	if (!aqr.isTransactional()) {
-		    		if (futureResult != null && !futureResult.isDone()) {
-		    			futureResult.addCompletionListener(new ResultsFuture.CompletionListener<AtomicResultsMessage>() {
-		    				@Override
-		    				public void onCompletion(
-		    						ResultsFuture<AtomicResultsMessage> future) {
-		    					cwi.close(); // there is a small chance that this will be done in the processing thread
-		    				}
-						});
-		    		} else {
-		    			dtm.addWork(new Callable<Void>() {
-		    				@Override
-		    				public Void call() throws Exception {
-		    					cwi.close();
-		    					return null;
-		    				}
-		    			}, 0);
-		    		}
-		    	} else {
-		    		this.cwi.close();
-		    	}
-    		}
-			closed = true;
-    	}
-    }
-    
-    public boolean isCanceled() {
-		return canceled;
-	}
-    
-    public void cancelRequest() {
-    	this.canceled = true;
-    	if (this.cwi != null) {
-    		this.cwi.cancel();
-    	}
-    }
-
-    /**
-     * @see TupleSource#closeSource()
-     */
-    public void closeSource() {
-    	if (!explicitClose) {
-        	fullyCloseSource();
-    	}
-    }
-
-    void exceptionOccurred(TranslatorException exception, boolean removeState) throws TeiidComponentException, TeiidProcessingException {
-    	if (removeState) {
-			fullyCloseSource();
-		}
-    	if(workItem.requestMsg.supportsPartialResults()) {
-			AtomicResultsMessage emptyResults = new AtomicResultsMessage(new List[0], null);
-			emptyResults.setWarnings(Arrays.asList((Exception)exception));
-			emptyResults.setFinalRow(this.rowsProcessed);
-			receiveResults(emptyResults);
-		} else {
-    		if (exception.getCause() instanceof TeiidComponentException) {
-    			throw (TeiidComponentException)exception.getCause();
-    		}
-    		if (exception.getCause() instanceof TeiidProcessingException) {
-    			throw (TeiidProcessingException)exception.getCause();
-    		}
-    		throw new TeiidProcessingException(exception);
-		}	
-	}
-
-	void receiveResults(AtomicResultsMessage response) {
-		this.arm = response;
-		explicitClose |= !arm.supportsImplicitClose();
-        rowsProcessed += response.getResults().length;
-        index = 0;
-		if (response.getWarnings() != null) {
-			for (Exception warning : response.getWarnings()) {
-				SourceWarning sourceFailure = new SourceWarning(this.aqr.getModelName(), aqr.getConnectorName(), warning, true);
-		        workItem.addSourceFailureDetails(sourceFailure);
-			}
-		}
-		if (response.getFinalRow() >= 0) {
-    		done = true;
-    	}
-	}
-	
-	public AtomicRequestMessage getAtomicRequestMessage() {
-		return aqr;
-	}
-
-	public String getConnectorName() {
-		return this.aqr.getConnectorName();
-	}
-	
-	public boolean isTransactional() {
-		return this.aqr.isTransactional();
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java (from rev 2774, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,402 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.dqp.internal.process;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+
+import javax.activation.DataSource;
+import javax.xml.transform.Source;
+
+import org.teiid.client.SourceWarning;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.FileStore;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.BlobImpl;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.core.types.StandardXMLTranslator;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.dqp.internal.datamgr.ConnectorWork;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.AtomicResultsMessage;
+import org.teiid.query.processor.xml.XMLUtil;
+import org.teiid.query.processor.xml.XMLUtil.FileStoreInputStreamFactory;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ * This tuple source impl can only be used once; once it is closed, it 
+ * cannot be reopened and reused.
+ * 
+ * TODO: the handling of DataNotAvailable is awkward.
+ * In the multi-threaded case we'd like to not even
+ * notify the parent plan and just schedule the next poll. 
+ */
+public class DataTierTupleSource implements TupleSource {
+	
+    // Construction state
+    private final AtomicRequestMessage aqr;
+    private final RequestWorkItem workItem;
+    private final ConnectorWork cwi;
+    private final DataTierManagerImpl dtm;
+    
+    private boolean[] convertToRuntimeType;
+    private boolean[] convertToDesiredRuntimeType;
+    private Class<?>[] schema;
+    
+    // Data state
+    private int index;
+    private int rowsProcessed;
+    private AtomicResultsMessage arm;
+    private boolean closed;
+    private volatile boolean canceled;
+    private boolean executed;
+    private volatile boolean done;
+    private boolean explicitClose;
+    
+    private volatile ResultsFuture<AtomicResultsMessage> futureResult;
+    private volatile boolean running;
+    
+    public DataTierTupleSource(AtomicRequestMessage aqr, RequestWorkItem workItem, ConnectorWork cwi, DataTierManagerImpl dtm) {
+        this.aqr = aqr;
+        this.workItem = workItem;
+        this.cwi = cwi;
+        this.dtm = dtm;
+		List<SingleElementSymbol> symbols = this.aqr.getCommand().getProjectedSymbols();
+		this.schema = new Class[symbols.size()];
+        this.convertToDesiredRuntimeType = new boolean[symbols.size()];
+		this.convertToRuntimeType = new boolean[symbols.size()];
+		for (int i = 0; i < symbols.size(); i++) {
+			SingleElementSymbol symbol = symbols.get(i);
+			this.schema[i] = symbol.getType();
+			this.convertToDesiredRuntimeType[i] = true;
+			this.convertToRuntimeType[i] = true;
+		}
+        
+    	Assertion.isNull(workItem.getConnectorRequest(aqr.getAtomicRequestID()));
+        workItem.addConnectorRequest(aqr.getAtomicRequestID(), this);
+        if (!aqr.isTransactional()) {
+        	addWork();
+        }
+    }
+
+	private void addWork() {
+		futureResult = dtm.addWork(new Callable<AtomicResultsMessage>() {
+			@Override
+			public AtomicResultsMessage call() throws Exception {
+				return getResults();
+			}
+		}, 100);
+		futureResult.addCompletionListener(new ResultsFuture.CompletionListener<AtomicResultsMessage>() {
+			public void onCompletion(ResultsFuture<AtomicResultsMessage> future) {
+				workItem.moreWork();
+			}
+		});
+	}
+
+	private List correctTypes(List row) throws TransformationException {
+		//TODO: add a proper intermediate schema
+		for (int i = 0; i < row.size(); i++) {
+			Object value = row.get(i);
+			if (value == null) {
+				continue;
+			}
+			if (convertToRuntimeType[i]) {
+				boolean lob = !arm.supportsCloseWithLobs() && DataTypeManager.isLOB(value.getClass());
+				Object result = convertToRuntimeType(value, this.schema[i]);
+				if (value == result && !DataTypeManager.DefaultDataClasses.OBJECT.equals(this.schema[i])) {
+					convertToRuntimeType[i] = false;
+				} else {
+					if (lob && DataTypeManager.isLOB(result.getClass()) && DataTypeManager.isLOB(this.schema[i])) {
+						explicitClose = true;
+					}				
+					row.set(i, result);
+					value = result;
+				}
+			}
+			if (convertToDesiredRuntimeType[i]) {
+				if (value != null) {
+					Object result = DataTypeManager.transformValue(value, value.getClass(), this.schema[i]);
+					if (value == result) {
+						convertToDesiredRuntimeType[i] = false;
+						continue;
+					}
+					row.set(i, result);
+				}
+			} else {
+				row.set(i, DataTypeManager.getCanonicalValue(value));
+			}
+		}
+		return row;
+	}
+
+	private Object convertToRuntimeType(Object value, Class<?> desiredType) throws TransformationException {
+		if (value instanceof DataSource && (!(value instanceof Source) || desiredType != DataTypeManager.DefaultDataClasses.XML)) {
+			if (value instanceof InputStreamFactory) {
+				return new BlobType(new BlobImpl((InputStreamFactory)value));
+			}
+			FileStore fs = dtm.getBufferManager().createFileStore("bytes"); //$NON-NLS-1$
+			//TODO: guess at the encoding from the content type
+			FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
+			
+			try {
+				ObjectConverterUtil.write(fsisf.getOuputStream(), ((DataSource)value).getInputStream(), -1);
+			} catch (IOException e) {
+				throw new TransformationException(e, e.getMessage());
+			}
+			return new BlobType(new BlobImpl(fsisf));
+		}
+		if (value instanceof Source) {
+			if (value instanceof InputStreamFactory) {
+				return new XMLType(new SQLXMLImpl((InputStreamFactory)value));
+			}
+			StandardXMLTranslator sxt = new StandardXMLTranslator((Source)value);
+			SQLXMLImpl sqlxml;
+			try {
+				sqlxml = XMLUtil.saveToBufferManager(dtm.getBufferManager(), sxt);
+			} catch (TeiidComponentException e) {
+				throw new TeiidRuntimeException(e);
+			} catch (TeiidProcessingException e) {
+				throw new TeiidRuntimeException(e);
+			}
+			return new XMLType(sqlxml);
+		}
+		return DataTypeManager.convertToRuntimeType(value);
+	}
+
+    public List<?> nextTuple() throws TeiidComponentException, TeiidProcessingException {
+    	while (true) {
+    		if (arm == null) {
+    			AtomicResultsMessage results = null;
+    			try {
+	    			if (futureResult != null || !aqr.isTransactional()) {
+	    				results = asynchGet();
+	    			} else {
+	    				results = getResults();
+	    			}
+    			} catch (TranslatorException e) {
+    				results = exceptionOccurred(e, true);
+    			} catch (DataNotAvailableException e) {
+    				dtm.scheduleWork(new Runnable() {
+    					@Override
+    					public void run() {
+							workItem.moreWork();
+    					}
+    				}, 10, e.getRetryDelay());
+    				throw BlockedException.INSTANCE;
+    			} 
+    			receiveResults(results);
+    		}
+	    	if (index < arm.getResults().length) {
+	            return correctTypes(this.arm.getResults()[index++]);
+	        }
+	    	arm = null;
+	    	if (isDone()) {
+	    		return null;
+	    	}
+    	}
+    }
+
+	private AtomicResultsMessage asynchGet()
+			throws BlockedException, TeiidProcessingException,
+			TeiidComponentException, TranslatorException {
+		if (futureResult == null) {
+			addWork();
+		}
+		if (!futureResult.isDone()) {
+			throw BlockedException.INSTANCE;
+		}
+		ResultsFuture<AtomicResultsMessage> currentResults = futureResult;
+		futureResult = null;
+		AtomicResultsMessage results = null;
+		try {
+			results = currentResults.get();
+			if (results.getFinalRow() < 0) {
+				addWork();
+			}
+		} catch (InterruptedException e) {
+			throw new TeiidRuntimeException(e);
+		} catch (ExecutionException e) {
+			if (e.getCause() instanceof TeiidProcessingException) {
+				throw (TeiidProcessingException)e.getCause();
+			}
+			if (e.getCause() instanceof TeiidComponentException) {
+				throw (TeiidComponentException)e.getCause();
+			}
+			if (e.getCause() instanceof TranslatorException) {
+				throw (TranslatorException)e.getCause();
+			}
+			if (e.getCause() instanceof RuntimeException) {
+				throw (RuntimeException)e.getCause();
+			}
+			//shouldn't happen
+			throw new RuntimeException(e);
+		}
+		return results;
+	}
+
+	private AtomicResultsMessage getResults()
+			throws BlockedException, TeiidComponentException,
+			TranslatorException {
+		AtomicResultsMessage results = null;
+		try {
+			running = true;
+			if (!executed) {
+				results = cwi.execute();
+				executed = true;
+			} else {
+				results = cwi.more();
+			}
+		} finally {
+			running = false;
+		}
+		return results;
+	}
+    
+    public boolean isQueued() {
+    	ResultsFuture<AtomicResultsMessage> future = futureResult;
+    	return !running && future != null && !future.isDone();
+    }
+
+	public boolean isDone() {
+		return done;
+	}
+    
+    public boolean isRunning() {
+		return running;
+	}
+    
+    public void fullyCloseSource() {
+    	if (!closed) {
+    		if (cwi != null) {
+		    	workItem.closeAtomicRequest(this.aqr.getAtomicRequestID());
+		    	if (!aqr.isTransactional()) {
+		    		if (futureResult != null && !futureResult.isDone()) {
+		    			futureResult.addCompletionListener(new ResultsFuture.CompletionListener<AtomicResultsMessage>() {
+		    				@Override
+		    				public void onCompletion(
+		    						ResultsFuture<AtomicResultsMessage> future) {
+		    					cwi.close(); // there is a small chance that this will be done in the processing thread
+		    				}
+						});
+		    		} else {
+		    			dtm.addWork(new Callable<Void>() {
+		    				@Override
+		    				public Void call() throws Exception {
+		    					cwi.close();
+		    					return null;
+		    				}
+		    			}, 0);
+		    		}
+		    	} else {
+		    		this.cwi.close();
+		    	}
+    		}
+			closed = true;
+    	}
+    }
+    
+    public boolean isCanceled() {
+		return canceled;
+	}
+    
+    public void cancelRequest() {
+    	this.canceled = true;
+    	if (this.cwi != null) {
+    		this.cwi.cancel();
+    	}
+    }
+
+    /**
+     * @see TupleSource#closeSource()
+     */
+    public void closeSource() {
+    	if (!explicitClose) {
+        	fullyCloseSource();
+    	}
+    }
+
+    AtomicResultsMessage exceptionOccurred(TranslatorException exception, boolean removeState) throws TeiidComponentException, TeiidProcessingException {
+    	if (removeState) {
+			fullyCloseSource();
+		}
+    	if(workItem.requestMsg.supportsPartialResults()) {
+			AtomicResultsMessage emptyResults = new AtomicResultsMessage(new List[0], null);
+			emptyResults.setWarnings(Arrays.asList((Exception)exception));
+			emptyResults.setFinalRow(this.rowsProcessed);
+			return emptyResults;
+		} 
+		if (exception.getCause() instanceof TeiidComponentException) {
+			throw (TeiidComponentException)exception.getCause();
+		}
+		if (exception.getCause() instanceof TeiidProcessingException) {
+			throw (TeiidProcessingException)exception.getCause();
+		}
+		throw new TeiidProcessingException(exception);
+	}
+
+	void receiveResults(AtomicResultsMessage response) {
+		this.arm = response;
+		explicitClose |= !arm.supportsImplicitClose();
+        rowsProcessed += response.getResults().length;
+        index = 0;
+		if (response.getWarnings() != null) {
+			for (Exception warning : response.getWarnings()) {
+				SourceWarning sourceFailure = new SourceWarning(this.aqr.getModelName(), aqr.getConnectorName(), warning, true);
+		        workItem.addSourceFailureDetails(sourceFailure);
+			}
+		}
+		if (response.getFinalRow() >= 0) {
+    		done = true;
+    	}
+	}
+	
+	public AtomicRequestMessage getAtomicRequestMessage() {
+		return aqr;
+	}
+
+	public String getConnectorName() {
+		return this.aqr.getConnectorName();
+	}
+	
+	public boolean isTransactional() {
+		return this.aqr.isTransactional();
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,299 +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.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.BatchedUpdatePlanner;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.relational.AccessNode;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-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.Constant;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.util.VariableContext;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * Specific request for handling prepared statement calls.
- */
-public class PreparedStatementRequest extends Request {
-    private SessionAwareCache<PreparedPlan> prepPlanCache;
-    private PreparedPlan prepPlan;
-    
-    public PreparedStatementRequest(SessionAwareCache<PreparedPlan> prepPlanCache) {
-    	this.prepPlanCache = prepPlanCache;
-    }
-    
-    @Override
-    protected void checkReferences(List<Reference> references)
-    		throws QueryValidatorException {
-        prepPlan.setReferences(references);
-    }
-    
-    /** 
-     * @see org.teiid.dqp.internal.process.Request#resolveCommand(org.teiid.query.sql.lang.Command)
-     */
-    @Override
-    protected void resolveCommand(Command command) throws QueryResolverException,
-                                                  TeiidComponentException {
-    	handleCallableStatement(command);
-    	
-    	super.resolveCommand(command);
-    }
-
-    /**
-     * TODO: this is a hack that maintains pre 5.6 behavior, which ignores output parameters for resolving
-     * @param command
-     * @param references
-     */
-	private void handleCallableStatement(Command command) {
-		if (!this.requestMsg.isCallableStatement() || !(command instanceof StoredProcedure)) {
-    		return;
-    	}
-		StoredProcedure proc = (StoredProcedure)command;
-		if (!proc.isCallableStatement()) {
-			return;
-		}
-		List values = requestMsg.getParameterValues();
-		List<SPParameter> spParams = proc.getParameters();
-		proc.clearParameters();
-		int inParameterCount = values.size();
-		if (this.requestMsg.isBatchedUpdate() && values.size() > 0) {
-			inParameterCount = ((List)values.get(0)).size();
-		}
-		int index = 1;
-		for (Iterator<SPParameter> params = spParams.iterator(); params.hasNext();) {
-			SPParameter param = params.next();
-			if (param.getParameterType() == SPParameter.RETURN_VALUE) {
-				inParameterCount++;
-			} else if (param.getExpression() instanceof Reference && index > inParameterCount) {
-				//assume it's an output parameter
-				this.prepPlan.getReferences().remove(param.getExpression());
-				continue;
-			}
-			param.setIndex(index++);
-			proc.setParameter(param);					
-		}
-	}
-    
-    /** 
-     * @throws TeiidComponentException 
-     * @throws TeiidProcessingException 
-     * @see org.teiid.dqp.internal.process.Request#generatePlan()
-     */
-    protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
-    	String sqlQuery = requestMsg.getCommands()[0];
-    	CacheID id = new CacheID(this.workContext, Request.createParseInfo(this.requestMsg), sqlQuery);
-        prepPlan = prepPlanCache.get(id);
-        if (prepPlan == null) {
-            //if prepared plan does not exist, create one
-            prepPlan = new PreparedPlan();
-            LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
-            super.generatePlan();
-	        if (!this.addedLimit) { //TODO: this is a little problematic
-            	prepPlan.setCommand(this.userCommand);
-		        // Defect 13751: Clone the plan in its current state (i.e. before processing) so that it can be used for later queries
-		        prepPlan.setPlan(processPlan.clone());
-		        prepPlan.setAnalysisRecord(analysisRecord);
-				
-		        Determinism hintDeterminismLevel = null;
-				if (userCommand.getCacheHint() != null && userCommand.getCacheHint().getDeterminism() != null) {
-					hintDeterminismLevel = userCommand.getCacheHint().getDeterminism();
-					LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",this.context.getDeterminismLevel(), " to ", hintDeterminismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
-				}		        
-		        
-		        this.prepPlanCache.put(id, hintDeterminismLevel!= null?hintDeterminismLevel:this.context.getDeterminismLevel(), prepPlan, userCommand.getCacheHint() != null?userCommand.getCacheHint().getTtl():null);
-        	}
-        } else {
-        	ProcessorPlan cachedPlan = prepPlan.getPlan();
-        	this.userCommand = prepPlan.getCommand();
-            validateAccess(userCommand);    
-        	LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query exist in cache: ", sqlQuery }); //$NON-NLS-1$
-            processPlan = cachedPlan.clone();
-            //already in cache. obtain the values from cache
-            analysisRecord = prepPlan.getAnalysisRecord();
-            
-            createCommandContext();
-        }
-        
-        if (requestMsg.isBatchedUpdate()) {
-	        handlePreparedBatchUpdate();
-        } else {
-	        List<Reference> params = prepPlan.getReferences();
-	        List<?> values = requestMsg.getParameterValues();
-	
-	    	PreparedStatementRequest.resolveParameterValues(params, values, this.context, this.metadata);
-        }
-    }
-
-    /**
-     * There are two cases
-     *   if 
-     *     The source supports preparedBatchUpdate -> just let the command and values pass to the source
-     *   else 
-     *     create a batchedupdatecommand that represents the batch operation 
-     * @param command
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     * @throws QueryResolverException
-     * @throws QueryPlannerException 
-     * @throws QueryValidatorException 
-     */
-	private void handlePreparedBatchUpdate() throws QueryMetadataException,
-			TeiidComponentException, QueryResolverException, QueryPlannerException, QueryValidatorException {
-		List<List<?>> paramValues = (List<List<?>>) requestMsg.getParameterValues();
-		if (paramValues.isEmpty()) {
-			throw new QueryValidatorException("No batch values sent for prepared batch update"); //$NON-NLS-1$
-		}
-		boolean supportPreparedBatchUpdate = false;
-		Command command = null;
-		if (this.processPlan instanceof RelationalPlan) {
-			RelationalPlan rPlan = (RelationalPlan)this.processPlan;
-			if (rPlan.getRootNode() instanceof AccessNode) {
-				AccessNode aNode = (AccessNode)rPlan.getRootNode();
-				String modelName = aNode.getModelName();
-				command = aNode.getCommand();
-		        SourceCapabilities caps = capabilitiesFinder.findCapabilities(modelName);
-		        supportPreparedBatchUpdate = caps.supportsCapability(SourceCapabilities.Capability.BULK_UPDATE);
-			}
-		}
-		List<Command> commands = new LinkedList<Command>();
-		List<VariableContext> contexts = new LinkedList<VariableContext>();
-		List<List<Object>> multiValues = new ArrayList<List<Object>>(this.prepPlan.getReferences().size());
-		for (List<?> values : paramValues) {
-	    	PreparedStatementRequest.resolveParameterValues(this.prepPlan.getReferences(), values, this.context, this.metadata);
-			contexts.add(this.context.getVariableContext());
-			if(supportPreparedBatchUpdate){
-				if (multiValues.isEmpty()) {
-					for (int i = 0; i < values.size(); i++) {
-						multiValues.add(new ArrayList<Object>(paramValues.size()));
-					}					
-				}
-				for (int i = 0; i < values.size(); i++) {
-					List<Object> multiValue = multiValues.get(i);
-					multiValue.add(values.get(i));
-				}
-			} else { //just accumulate copies of the command/plan - clones are not necessary
-				if (command == null) {
-					command = this.prepPlan.getCommand();
-					command.setProcessorPlan(this.processPlan);
-				}
-				commands.add(command);
-			}
-		}
-		
-		if (paramValues.size() > 1) {
-			this.context.setVariableContext(new VariableContext());
-		} 
-		
-		if (paramValues.size() == 1) {
-			return; // just use the existing plan, and global reference evaluation
-		}
-		
-		if (supportPreparedBatchUpdate) {
-			for (int i = 0; i < this.prepPlan.getReferences().size(); i++) {
-				Constant c = new Constant(null, this.prepPlan.getReferences().get(i).getType());
-				c.setMultiValued(multiValues.get(i));
-				this.context.getVariableContext().setGlobalValue(this.prepPlan.getReferences().get(i).getContextSymbol(), c);
-			}
-			return;
-		}
-		
-		BatchedUpdateCommand buc = new BatchedUpdateCommand(commands);
-		buc.setVariableContexts(contexts);
-		BatchedUpdatePlanner planner = new BatchedUpdatePlanner();
-		this.processPlan = planner.optimize(buc, idGenerator, metadata, capabilitiesFinder, analysisRecord, context);
-	}
-
-	/** 
-	 * @param params
-	 * @param values
-	 * @throws QueryResolverException
-	 * @throws QueryValidatorException 
-	 */
-	public static void resolveParameterValues(List<Reference> params,
-	                                    List values, CommandContext context, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException, QueryValidatorException {
-		VariableContext result = new VariableContext();
-	    //the size of the values must be the same as that of the parameters
-	    if (params.size() != values.size()) {
-	        String msg = QueryPlugin.Util.getString("QueryUtil.wrong_number_of_values", new Object[] {new Integer(values.size()), new Integer(params.size())}); //$NON-NLS-1$
-	        throw new QueryResolverException(msg);
-	    }
-	
-	    //the type must be the same, or the type of the value can be implicitly converted
-	    //to that of the reference
-	    for (int i = 0; i < params.size(); i++) {
-	        Reference param = params.get(i);
-	        Object value = values.get(i);
-	        
-	        //TODO: why is the list check in here
-        	if(value != null && !(value instanceof List)) {
-                try {
-                    String targetTypeName = DataTypeManager.getDataTypeName(param.getType());
-                    Expression expr = ResolverUtil.convertExpression(new Constant(value), targetTypeName, metadata);
-                    value = Evaluator.evaluate(expr);
-				} catch (ExpressionEvaluationException e) {
-                    String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
-                    throw new QueryResolverException(msg);
-				} catch (QueryResolverException e) {
-					String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
-                    throw new QueryResolverException(msg);
-				}
-	        }
-	        	        
-        	if (param.getConstraint() != null) {
-        		param.getConstraint().validate(value);
-        	}
-	        //bind variable
-	        result.setGlobalValue(param.getContextSymbol(), value);
-	    }
-	    
-	    context.setVariableContext(result);
-	}
-} 

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java (from rev 2762, trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,299 @@
+/*
+ * 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.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.BatchedUpdatePlanner;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+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.Constant;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.util.VariableContext;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Specific request for handling prepared statement calls.
+ */
+public class PreparedStatementRequest extends Request {
+    private SessionAwareCache<PreparedPlan> prepPlanCache;
+    private PreparedPlan prepPlan;
+    
+    public PreparedStatementRequest(SessionAwareCache<PreparedPlan> prepPlanCache) {
+    	this.prepPlanCache = prepPlanCache;
+    }
+    
+    @Override
+    protected void checkReferences(List<Reference> references)
+    		throws QueryValidatorException {
+        prepPlan.setReferences(references);
+    }
+    
+    /** 
+     * @see org.teiid.dqp.internal.process.Request#resolveCommand(org.teiid.query.sql.lang.Command)
+     */
+    @Override
+    protected void resolveCommand(Command command) throws QueryResolverException,
+                                                  TeiidComponentException {
+    	handleCallableStatement(command);
+    	
+    	super.resolveCommand(command);
+    }
+
+    /**
+     * TODO: this is a hack that maintains pre 5.6 behavior, which ignores output parameters for resolving
+     * @param command
+     * @param references
+     */
+	private void handleCallableStatement(Command command) {
+		if (!this.requestMsg.isCallableStatement() || !(command instanceof StoredProcedure)) {
+    		return;
+    	}
+		StoredProcedure proc = (StoredProcedure)command;
+		if (!proc.isCallableStatement()) {
+			return;
+		}
+		List values = requestMsg.getParameterValues();
+		List<SPParameter> spParams = proc.getParameters();
+		proc.clearParameters();
+		int inParameterCount = values.size();
+		if (this.requestMsg.isBatchedUpdate() && values.size() > 0) {
+			inParameterCount = ((List)values.get(0)).size();
+		}
+		int index = 1;
+		for (Iterator<SPParameter> params = spParams.iterator(); params.hasNext();) {
+			SPParameter param = params.next();
+			if (param.getParameterType() == SPParameter.RETURN_VALUE) {
+				inParameterCount++;
+			} else if (param.getExpression() instanceof Reference && index > inParameterCount) {
+				//assume it's an output parameter
+				this.prepPlan.getReferences().remove(param.getExpression());
+				continue;
+			}
+			param.setIndex(index++);
+			proc.setParameter(param);					
+		}
+	}
+    
+    /** 
+     * @throws TeiidComponentException 
+     * @throws TeiidProcessingException 
+     * @see org.teiid.dqp.internal.process.Request#generatePlan()
+     */
+    protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
+    	String sqlQuery = requestMsg.getCommands()[0];
+    	CacheID id = new CacheID(this.workContext, Request.createParseInfo(this.requestMsg), sqlQuery);
+        prepPlan = prepPlanCache.get(id);
+        if (prepPlan == null) {
+            //if prepared plan does not exist, create one
+            prepPlan = new PreparedPlan();
+            LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
+            super.generatePlan();
+	        if (!this.addedLimit) { //TODO: this is a little problematic
+            	prepPlan.setCommand(this.userCommand);
+		        // Defect 13751: Clone the plan in its current state (i.e. before processing) so that it can be used for later queries
+		        prepPlan.setPlan(processPlan.clone());
+		        prepPlan.setAnalysisRecord(analysisRecord);
+				
+		        Determinism determinismLevel = this.context.getDeterminismLevel();
+				if (userCommand.getCacheHint() != null && userCommand.getCacheHint().getDeterminism() != null) {
+					LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Cache hint modified the query determinism from ",this.context.getDeterminismLevel(), " to ", determinismLevel }); //$NON-NLS-1$ //$NON-NLS-2$
+					determinismLevel = userCommand.getCacheHint().getDeterminism();
+				}		        
+		        
+		        this.prepPlanCache.put(id, determinismLevel, prepPlan, userCommand.getCacheHint() != null?userCommand.getCacheHint().getTtl():null);
+        	}
+        } else {
+        	ProcessorPlan cachedPlan = prepPlan.getPlan();
+        	this.userCommand = prepPlan.getCommand();
+            validateAccess(userCommand);    
+        	LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query exist in cache: ", sqlQuery }); //$NON-NLS-1$
+            processPlan = cachedPlan.clone();
+            //already in cache. obtain the values from cache
+            analysisRecord = prepPlan.getAnalysisRecord();
+            
+            createCommandContext();
+        }
+        
+        if (requestMsg.isBatchedUpdate()) {
+	        handlePreparedBatchUpdate();
+        } else {
+	        List<Reference> params = prepPlan.getReferences();
+	        List<?> values = requestMsg.getParameterValues();
+	
+	    	PreparedStatementRequest.resolveParameterValues(params, values, this.context, this.metadata);
+        }
+    }
+
+    /**
+     * There are two cases
+     *   if 
+     *     The source supports preparedBatchUpdate -> just let the command and values pass to the source
+     *   else 
+     *     create a batchedupdatecommand that represents the batch operation 
+     * @param command
+     * @throws QueryMetadataException
+     * @throws TeiidComponentException
+     * @throws QueryResolverException
+     * @throws QueryPlannerException 
+     * @throws QueryValidatorException 
+     */
+	private void handlePreparedBatchUpdate() throws QueryMetadataException,
+			TeiidComponentException, QueryResolverException, QueryPlannerException, QueryValidatorException {
+		List<List<?>> paramValues = (List<List<?>>) requestMsg.getParameterValues();
+		if (paramValues.isEmpty()) {
+			throw new QueryValidatorException("No batch values sent for prepared batch update"); //$NON-NLS-1$
+		}
+		boolean supportPreparedBatchUpdate = false;
+		Command command = null;
+		if (this.processPlan instanceof RelationalPlan) {
+			RelationalPlan rPlan = (RelationalPlan)this.processPlan;
+			if (rPlan.getRootNode() instanceof AccessNode) {
+				AccessNode aNode = (AccessNode)rPlan.getRootNode();
+				String modelName = aNode.getModelName();
+				command = aNode.getCommand();
+		        SourceCapabilities caps = capabilitiesFinder.findCapabilities(modelName);
+		        supportPreparedBatchUpdate = caps.supportsCapability(SourceCapabilities.Capability.BULK_UPDATE);
+			}
+		}
+		List<Command> commands = new LinkedList<Command>();
+		List<VariableContext> contexts = new LinkedList<VariableContext>();
+		List<List<Object>> multiValues = new ArrayList<List<Object>>(this.prepPlan.getReferences().size());
+		for (List<?> values : paramValues) {
+	    	PreparedStatementRequest.resolveParameterValues(this.prepPlan.getReferences(), values, this.context, this.metadata);
+			contexts.add(this.context.getVariableContext());
+			if(supportPreparedBatchUpdate){
+				if (multiValues.isEmpty()) {
+					for (int i = 0; i < values.size(); i++) {
+						multiValues.add(new ArrayList<Object>(paramValues.size()));
+					}					
+				}
+				for (int i = 0; i < values.size(); i++) {
+					List<Object> multiValue = multiValues.get(i);
+					multiValue.add(values.get(i));
+				}
+			} else { //just accumulate copies of the command/plan - clones are not necessary
+				if (command == null) {
+					command = this.prepPlan.getCommand();
+					command.setProcessorPlan(this.processPlan);
+				}
+				commands.add(command);
+			}
+		}
+		
+		if (paramValues.size() > 1) {
+			this.context.setVariableContext(new VariableContext());
+		} 
+		
+		if (paramValues.size() == 1) {
+			return; // just use the existing plan, and global reference evaluation
+		}
+		
+		if (supportPreparedBatchUpdate) {
+			for (int i = 0; i < this.prepPlan.getReferences().size(); i++) {
+				Constant c = new Constant(null, this.prepPlan.getReferences().get(i).getType());
+				c.setMultiValued(multiValues.get(i));
+				this.context.getVariableContext().setGlobalValue(this.prepPlan.getReferences().get(i).getContextSymbol(), c);
+			}
+			return;
+		}
+		
+		BatchedUpdateCommand buc = new BatchedUpdateCommand(commands);
+		buc.setVariableContexts(contexts);
+		BatchedUpdatePlanner planner = new BatchedUpdatePlanner();
+		this.processPlan = planner.optimize(buc, idGenerator, metadata, capabilitiesFinder, analysisRecord, context);
+	}
+
+	/** 
+	 * @param params
+	 * @param values
+	 * @throws QueryResolverException
+	 * @throws QueryValidatorException 
+	 */
+	public static void resolveParameterValues(List<Reference> params,
+	                                    List values, CommandContext context, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException, QueryValidatorException {
+		VariableContext result = new VariableContext();
+	    //the size of the values must be the same as that of the parameters
+	    if (params.size() != values.size()) {
+	        String msg = QueryPlugin.Util.getString("QueryUtil.wrong_number_of_values", new Object[] {new Integer(values.size()), new Integer(params.size())}); //$NON-NLS-1$
+	        throw new QueryResolverException(msg);
+	    }
+	
+	    //the type must be the same, or the type of the value can be implicitly converted
+	    //to that of the reference
+	    for (int i = 0; i < params.size(); i++) {
+	        Reference param = params.get(i);
+	        Object value = values.get(i);
+	        
+	        //TODO: why is the list check in here
+        	if(value != null && !(value instanceof List)) {
+                try {
+                    String targetTypeName = DataTypeManager.getDataTypeName(param.getType());
+                    Expression expr = ResolverUtil.convertExpression(new Constant(value), targetTypeName, metadata);
+                    value = Evaluator.evaluate(expr);
+				} catch (ExpressionEvaluationException e) {
+                    String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
+                    throw new QueryResolverException(msg);
+				} catch (QueryResolverException e) {
+					String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", new Integer(i + 1), value, DataTypeManager.getDataTypeName(param.getType())); //$NON-NLS-1$
+                    throw new QueryResolverException(msg);
+				}
+	        }
+	        	        
+        	if (param.getConstraint() != null) {
+        		param.getConstraint().validate(value);
+        	}
+	        //bind variable
+	        result.setGlobalValue(param.getContextSymbol(), value);
+	    }
+	    
+	    context.setVariableContext(result);
+	}
+} 

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,467 +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.Connection;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.teiid.adminapi.impl.VDBMetaData;
-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.RequestMessage;
-import org.teiid.client.RequestMessage.ResultsMode;
-import org.teiid.client.RequestMessage.ShowPlan;
-import org.teiid.client.xa.XATransactionException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerIDFactory;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.Assertion;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.process.multisource.MultiSourceCapabilitiesFinder;
-import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
-import org.teiid.dqp.internal.process.multisource.MultiSourcePlanToProcessConverter;
-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.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.eval.SecurityFunctionEvaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempCapabilitiesFinder;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.processor.xml.XMLPlan;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.Limit;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
-import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.util.ContextProperties;
-import org.teiid.query.validator.AbstractValidationVisitor;
-import org.teiid.query.validator.ValidationVisitor;
-import org.teiid.query.validator.Validator;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
-
-/**
- * Server side representation of the RequestMessage.  Knows how to process itself.
- */
-public class Request {
-    
-	// init state
-    protected RequestMessage requestMsg;
-    private String vdbName;
-    private int vdbVersion;
-    private BufferManager bufferManager;
-    private ProcessorDataManager processorDataManager;
-    private TransactionService transactionService;
-    private TempTableStore tempTableStore;
-    protected IDGenerator idGenerator = new IDGenerator();
-    DQPWorkContext workContext;
-    RequestID requestId;
-
-    // acquired state
-    protected CapabilitiesFinder capabilitiesFinder;
-    protected QueryMetadataInterface metadata;
-    private Set<String> multiSourceModels;
-
-    // internal results
-    protected boolean addedLimit;
-    protected ProcessorPlan processPlan;
-    // external results
-    protected AnalysisRecord analysisRecord;
-    protected CommandContext context;
-    protected QueryProcessor processor;
-    
-    protected TransactionContext transactionContext;
-    protected ConnectorManagerRepository connectorManagerRepo; 
-    
-    protected Command userCommand;
-    protected boolean returnsUpdateCount;
-    protected boolean useEntitlements;
-	private TempTableStore globalTables;
-	private SessionAwareCache<PreparedPlan> planCache;
-	private boolean resultSetCacheEnabled = true;
-
-    void initialize(RequestMessage requestMsg,
-                              BufferManager bufferManager,
-                              ProcessorDataManager processorDataManager,
-                              TransactionService transactionService,
-                              TempTableStore tempTableStore,
-                              DQPWorkContext workContext,
-                              boolean useEntitlements,
-                              SessionAwareCache<PreparedPlan> planCache) {
-
-        this.requestMsg = requestMsg;
-        this.vdbName = workContext.getVdbName();        
-        this.vdbVersion = workContext.getVdbVersion();
-        this.bufferManager = bufferManager;
-        this.processorDataManager = processorDataManager;
-        this.transactionService = transactionService;
-        this.tempTableStore = tempTableStore;
-        idGenerator.setDefaultFactory(new IntegerIDFactory());
-        this.workContext = workContext;
-        this.requestId = workContext.getRequestID(this.requestMsg.getExecutionId());
-        this.connectorManagerRepo = workContext.getVDB().getAttachment(ConnectorManagerRepository.class);
-        this.useEntitlements = useEntitlements && !workContext.getVDB().getDataPolicies().isEmpty();
-        this.planCache = planCache;
-    }
-    
-	void setMetadata(CapabilitiesFinder capabilitiesFinder, QueryMetadataInterface metadata, Set multiSourceModels) {
-		this.capabilitiesFinder = capabilitiesFinder;
-		this.metadata = metadata;
-		this.multiSourceModels = multiSourceModels;
-	}
-	
-	public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
-		this.resultSetCacheEnabled = resultSetCacheEnabled;
-	}
-    
-	/**
-	 * if the metadata has not been supplied via setMetadata, this method will create the appropriate state
-	 * 
-	 * @throws TeiidComponentException
-	 */
-    protected void initMetadata() throws TeiidComponentException {
-        if (this.metadata != null) {
-        	return;
-        }
-    	// Prepare dependencies for running the optimizer        
-        this.capabilitiesFinder = new CachedFinder(this.connectorManagerRepo, workContext.getVDB());        
-        this.capabilitiesFinder = new TempCapabilitiesFinder(this.capabilitiesFinder);
-
-        VDBMetaData vdbMetadata = workContext.getVDB();
-        metadata = vdbMetadata.getAttachment(QueryMetadataInterface.class);
-        globalTables = vdbMetadata.getAttachment(TempTableStore.class);
-
-        if (metadata == null) {
-            throw new TeiidComponentException(QueryPlugin.Util.getString("DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}", this.vdbName, this.vdbVersion)); //$NON-NLS-1$
-        }
-        
-        this.metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
-    
-        // Check for multi-source models and further wrap the metadata interface
-        Set<String> multiSourceModelList = workContext.getVDB().getMultiSourceModelNames();
-        if(multiSourceModelList != null && multiSourceModelList.size() > 0) {
-        	this.multiSourceModels = multiSourceModelList;
-            this.metadata = new MultiSourceMetadataWrapper(this.metadata, this.multiSourceModels);
-        }
-    }
-    
-    protected void createCommandContext() throws QueryValidatorException {
-    	boolean returnsResultSet = userCommand.returnsResultSet();
-    	this.returnsUpdateCount = !(userCommand instanceof StoredProcedure) && !returnsResultSet;
-    	if ((this.requestMsg.getResultsMode() == ResultsMode.UPDATECOUNT && !returnsUpdateCount) 
-    			|| (this.requestMsg.getResultsMode() == ResultsMode.RESULTSET && !returnsResultSet)) {
-        	throw new QueryValidatorException(QueryPlugin.Util.getString(this.requestMsg.getResultsMode()==ResultsMode.RESULTSET?"Request.no_result_set":"Request.result_set")); //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-
-    	// Create command context, used in rewriting, planning, and processing
-        // Identifies a "group" of requests on a per-connection basis to allow later
-        // cleanup of all resources in the group on connection shutdown
-        String groupName = workContext.getSessionId();
-
-        RequestID reqID = workContext.getRequestID(this.requestMsg.getExecutionId());
-        
-        Properties props = new Properties();
-        props.setProperty(ContextProperties.SESSION_ID, workContext.getSessionId());
-        
-        this.context =
-            new CommandContext(
-                reqID,
-                groupName,
-                workContext.getUserName(),
-                requestMsg.getExecutionPayload(), 
-                workContext.getVdbName(), 
-                workContext.getVdbVersion(),
-                props,
-                this.requestMsg.getShowPlan() != ShowPlan.OFF);
-        this.context.setProcessorBatchSize(bufferManager.getProcessorBatchSize());
-        this.context.setConnectorBatchSize(bufferManager.getConnectorBatchSize());
-        this.context.setGlobalTableStore(this.globalTables);
-        if (multiSourceModels != null) {
-            MultiSourcePlanToProcessConverter modifier = new MultiSourcePlanToProcessConverter(
-					metadata, idGenerator, analysisRecord, capabilitiesFinder,
-					multiSourceModels, workContext, context);
-            context.setPlanToProcessConverter(modifier);
-        }
-
-        context.setSecurityFunctionEvaluator(new SecurityFunctionEvaluator() {
-			@Override
-			public boolean hasRole(String roleType, String roleName) throws TeiidComponentException {
-				if (!useEntitlements) {
-					return true;
-				}
-		        if (!DATA_ROLE.equalsIgnoreCase(roleType)) {
-		            return false;
-		        }
-				return workContext.getAllowedDataPolicies().containsKey(roleName);
-			}
-        });
-        context.setTempTableStore(tempTableStore);
-        context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(this.bufferManager, this.processorDataManager, this.capabilitiesFinder, idGenerator, metadata));
-        context.setMetadata(this.metadata);
-        context.setBufferManager(this.bufferManager);
-        context.setPreparedPlanCache(planCache);
-        context.setResultSetCacheEnabled(this.resultSetCacheEnabled);
-    }
-
-    protected void checkReferences(List<Reference> references) throws QueryValidatorException {
-    	referenceCheck(references);
-    }
-    
-    static void referenceCheck(List<Reference> references) throws QueryValidatorException {
-    	if (references != null && !references.isEmpty()) {
-    		throw new QueryValidatorException(QueryPlugin.Util.getString("Request.Invalid_character_in_query")); //$NON-NLS-1$
-    	}
-    }
-
-    protected void resolveCommand(Command command) throws QueryResolverException, TeiidComponentException {
-        if (this.tempTableStore != null) {
-        	QueryResolver.setChildMetadata(command, tempTableStore.getMetadataStore().getData(), null);
-        }
-    	//ensure that the user command is distinct from the processing command
-        //rewrite and planning may alter options, symbols, etc.
-    	QueryResolver.resolveCommand(command, metadata, analysisRecord);
-    	
-    	this.userCommand = (Command)command.clone();
-    }
-        
-    private void validateQuery(Command command)
-        throws QueryValidatorException, TeiidComponentException {
-                
-        // Create generic sql validation visitor
-        AbstractValidationVisitor visitor = new ValidationVisitor();
-        validateWithVisitor(visitor, metadata, command);
-    }
-    
-    private Command parseCommand() throws QueryParserException {
-        String[] commands = requestMsg.getCommands();
-        ParseInfo parseInfo = createParseInfo(this.requestMsg);
-        if (requestMsg.isPreparedStatement() || requestMsg.isCallableStatement() || !requestMsg.isBatchedUpdate()) {
-        	String commandStr = commands[0];
-            return QueryParser.getQueryParser().parseCommand(commandStr, parseInfo);
-        } 
-        List<Command> parsedCommands = new ArrayList<Command>(commands.length);
-        for (int i = 0; i < commands.length; i++) {
-        	String updateCommand = commands[i];
-            parsedCommands.add(QueryParser.getQueryParser().parseCommand(updateCommand, parseInfo));
-        }
-        return new BatchedUpdateCommand(parsedCommands);
-    }
-
-	public static ParseInfo createParseInfo(RequestMessage requestMsg) {
-		ParseInfo parseInfo = new ParseInfo();
-    	parseInfo.ansiQuotedIdentifiers = requestMsg.isAnsiQuotedIdentifiers();
-		return parseInfo;
-	}
-
-    public static void validateWithVisitor(
-        AbstractValidationVisitor visitor,
-        QueryMetadataInterface metadata,
-        Command command)
-        throws QueryValidatorException, TeiidComponentException {
-
-        // Validate with visitor
-        ValidatorReport report = Validator.validate(command, metadata, visitor);
-        if (report.hasItems()) {
-            ValidatorFailure firstFailure = (ValidatorFailure) report.getItems().iterator().next();
-            throw new QueryValidatorException(firstFailure.getMessage());
-        }
-    }
-
-    private void createProcessor() throws TeiidComponentException {
-        
-        TransactionContext tc = transactionService.getOrCreateTransactionContext(workContext.getSessionId());
-        
-        Assertion.assertTrue(tc.getTransactionType() != TransactionContext.Scope.REQUEST, "Transaction already associated with request."); //$NON-NLS-1$
-
-        // If local or global transaction is not started.
-        if (tc.getTransactionType() == Scope.NONE) {
-            
-            boolean startAutoWrapTxn = false;
-            
-            if(RequestMessage.TXN_WRAP_ON.equals(requestMsg.getTxnAutoWrapMode())){ 
-                startAutoWrapTxn = true;
-            } else if (RequestMessage.TXN_WRAP_DETECT.equals(requestMsg.getTxnAutoWrapMode())){
-            	boolean transactionalRead = requestMsg.getTransactionIsolation() == Connection.TRANSACTION_REPEATABLE_READ
-						|| requestMsg.getTransactionIsolation() == Connection.TRANSACTION_SERIALIZABLE;
-        		startAutoWrapTxn = processPlan.requiresTransaction(transactionalRead);
-            } 
-            
-            if (startAutoWrapTxn) {
-                try {
-                    tc = transactionService.begin(tc);
-                } catch (XATransactionException err) {
-                    throw new TeiidComponentException(err);
-                }
-            }
-        } 
-        
-        this.transactionContext = tc;
-        this.processor = new QueryProcessor(processPlan, context, bufferManager, processorDataManager);
-    }
-
-    /**
-     * state side effects:
-     *      creates the analysis record
-     * 		creates the command context
-     * 		sets the pre-rewrite command on the request
-     * 		adds a limit clause if the row limit is specified
-     * 		sets the processor plan
-     * 
-     * @throws TeiidComponentException
-     * @throws TeiidProcessingException 
-     */
-    protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
-        Command command = parseCommand();
-
-        List<Reference> references = ReferenceCollectorVisitor.getReferences(command);
-        
-        checkReferences(references);
-        
-        this.analysisRecord = new AnalysisRecord(requestMsg.getShowPlan() != ShowPlan.OFF, requestMsg.getShowPlan() == ShowPlan.DEBUG);
-                
-        resolveCommand(command);
-        
-        validateAccess(userCommand);
-        
-        createCommandContext();
-
-        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
-        for (GroupSymbol groupSymbol : groups) {
-			if (groupSymbol.isTempTable()) {
-				this.context.setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
-				break;
-			}
-		}
-
-        validateQuery(command);
-        
-        command = QueryRewriter.rewrite(command, metadata, context);
-        
-        /*
-         * Adds a row limit to a query if Statement.setMaxRows has been called and the command
-         * doesn't already have a limit clause.
-         */
-        if (requestMsg.getRowLimit() > 0 && command instanceof QueryCommand) {
-            QueryCommand query = (QueryCommand)command;
-            if (query.getLimit() == null) {
-                query.setLimit(new Limit(null, new Constant(new Integer(requestMsg.getRowLimit()), DataTypeManager.DefaultDataClasses.INTEGER)));
-                this.addedLimit = true;
-            }
-        }
-        
-        try {
-        	// If using multi-source models, insert a proxy to simplify the supported capabilities.  This is 
-            // done OUTSIDE the cache (wrapped around the cache) intentionally to avoid caching the simplified
-            // capabilities which may be different for the same model in a different VDB used by this same DQP.
-        	CapabilitiesFinder finder = this.capabilitiesFinder;
-            if(this.multiSourceModels != null) {
-                finder = new MultiSourceCapabilitiesFinder(finder, this.multiSourceModels);
-            }
-            
-            boolean debug = analysisRecord.recordDebug();
-    		if(debug) {
-    			analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
-                analysisRecord.println("USER COMMAND:\n" + command);		 //$NON-NLS-1$
-            }
-            // Run the optimizer
-            try {
-                processPlan = QueryOptimizer.optimizePlan(command, metadata, idGenerator, finder, analysisRecord, context);
-            } finally {
-                String debugLog = analysisRecord.getDebugLog();
-                if(debugLog != null && debugLog.length() > 0) {
-                    LogManager.log(requestMsg.getShowPlan()==ShowPlan.DEBUG?MessageLevel.INFO:MessageLevel.TRACE, LogConstants.CTX_QUERY_PLANNER, debugLog);               
-                }
-                if (analysisRecord.recordAnnotations() && analysisRecord.getAnnotations() != null && !analysisRecord.getAnnotations().isEmpty()) {
-                	LogManager.logDetail(LogConstants.CTX_QUERY_PLANNER, analysisRecord.getAnnotations());
-                }
-            }
-            LogManager.logDetail(LogConstants.CTX_DQP, new Object[] { QueryPlugin.Util.getString("BasicInterceptor.ProcessTree_for__4"), requestId, processPlan }); //$NON-NLS-1$
-        } catch (QueryMetadataException e) {
-            throw new QueryPlannerException(e, QueryPlugin.Util.getString("DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.", requestId)); //$NON-NLS-1$
-        }
-    }
-
-    public void processRequest() 
-        throws TeiidComponentException, TeiidProcessingException {
-                    
-    	LogManager.logDetail(LogConstants.CTX_DQP, this.requestId, "executing", this.requestMsg.isPreparedStatement()?"prepared":"", this.requestMsg.getCommandString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    	
-        initMetadata();
-        
-        generatePlan();
-        
-        postProcessXML();
-        
-        createProcessor();
-    }
-
-	private void postProcessXML() {
-        if (requestMsg.getXMLFormat() != null && processPlan instanceof XMLPlan) {
-        	((XMLPlan)processPlan).setXMLFormat(requestMsg.getXMLFormat());
-        }
-        this.context.setValidateXML(requestMsg.getValidationMode());
-	}
-
-	protected void validateAccess(Command command) throws QueryValidatorException, TeiidComponentException {
-		if (useEntitlements) {
-			AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(this.workContext.getAllowedDataPolicies(), this.workContext.getUserName());
-			validateWithVisitor(visitor, this.metadata, command);
-		}
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java (from rev 2765, trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,474 @@
+/*
+ * 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.Connection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import org.teiid.adminapi.impl.VDBMetaData;
+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.RequestMessage;
+import org.teiid.client.RequestMessage.ResultsMode;
+import org.teiid.client.RequestMessage.ShowPlan;
+import org.teiid.client.xa.XATransactionException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.id.IDGenerator;
+import org.teiid.core.id.IntegerIDFactory;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.process.multisource.MultiSourceCapabilitiesFinder;
+import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
+import org.teiid.dqp.internal.process.multisource.MultiSourcePlanToProcessConverter;
+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.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.eval.SecurityFunctionEvaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempCapabilitiesFinder;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.processor.xml.XMLPlan;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.util.ContextProperties;
+import org.teiid.query.validator.AbstractValidationVisitor;
+import org.teiid.query.validator.ValidationVisitor;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorFailure;
+import org.teiid.query.validator.ValidatorReport;
+
+
+/**
+ * Server side representation of the RequestMessage.  Knows how to process itself.
+ */
+public class Request {
+    
+	// init state
+    protected RequestMessage requestMsg;
+    private String vdbName;
+    private int vdbVersion;
+    private BufferManager bufferManager;
+    private ProcessorDataManager processorDataManager;
+    private TransactionService transactionService;
+    private TempTableStore tempTableStore;
+    protected IDGenerator idGenerator = new IDGenerator();
+    DQPWorkContext workContext;
+    RequestID requestId;
+
+    // acquired state
+    protected CapabilitiesFinder capabilitiesFinder;
+    protected QueryMetadataInterface metadata;
+    private Set<String> multiSourceModels;
+
+    // internal results
+    protected boolean addedLimit;
+    protected ProcessorPlan processPlan;
+    // external results
+    protected AnalysisRecord analysisRecord;
+    protected CommandContext context;
+    protected QueryProcessor processor;
+    
+    protected TransactionContext transactionContext;
+    protected ConnectorManagerRepository connectorManagerRepo; 
+    
+    protected Command userCommand;
+    protected boolean returnsUpdateCount;
+    protected boolean useEntitlements;
+	private TempTableStore globalTables;
+	private SessionAwareCache<PreparedPlan> planCache;
+	private boolean resultSetCacheEnabled = true;
+	private boolean allowCreateTemporaryTablesByDefault;
+
+    void initialize(RequestMessage requestMsg,
+                              BufferManager bufferManager,
+                              ProcessorDataManager processorDataManager,
+                              TransactionService transactionService,
+                              TempTableStore tempTableStore,
+                              DQPWorkContext workContext,
+                              boolean useEntitlements,
+                              SessionAwareCache<PreparedPlan> planCache) {
+
+        this.requestMsg = requestMsg;
+        this.vdbName = workContext.getVdbName();        
+        this.vdbVersion = workContext.getVdbVersion();
+        this.bufferManager = bufferManager;
+        this.processorDataManager = processorDataManager;
+        this.transactionService = transactionService;
+        this.tempTableStore = tempTableStore;
+        idGenerator.setDefaultFactory(new IntegerIDFactory());
+        this.workContext = workContext;
+        this.requestId = workContext.getRequestID(this.requestMsg.getExecutionId());
+        this.connectorManagerRepo = workContext.getVDB().getAttachment(ConnectorManagerRepository.class);
+        this.useEntitlements = useEntitlements && !workContext.getVDB().getDataPolicies().isEmpty();
+        this.planCache = planCache;
+    }
+    
+	void setMetadata(CapabilitiesFinder capabilitiesFinder, QueryMetadataInterface metadata, Set multiSourceModels) {
+		this.capabilitiesFinder = capabilitiesFinder;
+		this.metadata = metadata;
+		this.multiSourceModels = multiSourceModels;
+	}
+	
+	public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
+		this.resultSetCacheEnabled = resultSetCacheEnabled;
+	}
+	
+	public void setAllowCreateTemporaryTablesByDefault(
+			boolean allowCreateTemporaryTablesByDefault) {
+		this.allowCreateTemporaryTablesByDefault = allowCreateTemporaryTablesByDefault;
+	}
+    
+	/**
+	 * if the metadata has not been supplied via setMetadata, this method will create the appropriate state
+	 * 
+	 * @throws TeiidComponentException
+	 */
+    protected void initMetadata() throws TeiidComponentException {
+        if (this.metadata != null) {
+        	return;
+        }
+    	// Prepare dependencies for running the optimizer        
+        this.capabilitiesFinder = new CachedFinder(this.connectorManagerRepo, workContext.getVDB());        
+        this.capabilitiesFinder = new TempCapabilitiesFinder(this.capabilitiesFinder);
+
+        VDBMetaData vdbMetadata = workContext.getVDB();
+        metadata = vdbMetadata.getAttachment(QueryMetadataInterface.class);
+        globalTables = vdbMetadata.getAttachment(TempTableStore.class);
+
+        if (metadata == null) {
+            throw new TeiidComponentException(QueryPlugin.Util.getString("DQPCore.Unable_to_load_metadata_for_VDB_name__{0},_version__{1}", this.vdbName, this.vdbVersion)); //$NON-NLS-1$
+        }
+        
+        this.metadata = new TempMetadataAdapter(metadata, new TempMetadataStore());
+    
+        // Check for multi-source models and further wrap the metadata interface
+        Set<String> multiSourceModelList = workContext.getVDB().getMultiSourceModelNames();
+        if(multiSourceModelList != null && multiSourceModelList.size() > 0) {
+        	this.multiSourceModels = multiSourceModelList;
+            this.metadata = new MultiSourceMetadataWrapper(this.metadata, this.multiSourceModels);
+        }
+    }
+    
+    protected void createCommandContext() throws QueryValidatorException {
+    	boolean returnsResultSet = userCommand.returnsResultSet();
+    	this.returnsUpdateCount = !(userCommand instanceof StoredProcedure) && !returnsResultSet;
+    	if ((this.requestMsg.getResultsMode() == ResultsMode.UPDATECOUNT && !returnsUpdateCount) 
+    			|| (this.requestMsg.getResultsMode() == ResultsMode.RESULTSET && !returnsResultSet)) {
+        	throw new QueryValidatorException(QueryPlugin.Util.getString(this.requestMsg.getResultsMode()==ResultsMode.RESULTSET?"Request.no_result_set":"Request.result_set")); //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+
+    	// Create command context, used in rewriting, planning, and processing
+        // Identifies a "group" of requests on a per-connection basis to allow later
+        // cleanup of all resources in the group on connection shutdown
+        String groupName = workContext.getSessionId();
+
+        RequestID reqID = workContext.getRequestID(this.requestMsg.getExecutionId());
+        
+        Properties props = new Properties();
+        props.setProperty(ContextProperties.SESSION_ID, workContext.getSessionId());
+        
+        this.context =
+            new CommandContext(
+                reqID,
+                groupName,
+                workContext.getUserName(),
+                requestMsg.getExecutionPayload(), 
+                workContext.getVdbName(), 
+                workContext.getVdbVersion(),
+                props,
+                this.requestMsg.getShowPlan() != ShowPlan.OFF);
+        this.context.setProcessorBatchSize(bufferManager.getProcessorBatchSize());
+        this.context.setConnectorBatchSize(bufferManager.getConnectorBatchSize());
+        this.context.setGlobalTableStore(this.globalTables);
+        if (multiSourceModels != null) {
+            MultiSourcePlanToProcessConverter modifier = new MultiSourcePlanToProcessConverter(
+					metadata, idGenerator, analysisRecord, capabilitiesFinder,
+					multiSourceModels, workContext, context);
+            context.setPlanToProcessConverter(modifier);
+        }
+
+        context.setSecurityFunctionEvaluator(new SecurityFunctionEvaluator() {
+			@Override
+			public boolean hasRole(String roleType, String roleName) throws TeiidComponentException {
+				if (!useEntitlements) {
+					return true;
+				}
+		        if (!DATA_ROLE.equalsIgnoreCase(roleType)) {
+		            return false;
+		        }
+				return workContext.getAllowedDataPolicies().containsKey(roleName);
+			}
+        });
+        context.setTempTableStore(tempTableStore);
+        context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(this.bufferManager, this.processorDataManager, this.capabilitiesFinder, idGenerator, metadata));
+        context.setMetadata(this.metadata);
+        context.setBufferManager(this.bufferManager);
+        context.setPreparedPlanCache(planCache);
+        context.setResultSetCacheEnabled(this.resultSetCacheEnabled);
+    }
+
+    protected void checkReferences(List<Reference> references) throws QueryValidatorException {
+    	referenceCheck(references);
+    }
+    
+    static void referenceCheck(List<Reference> references) throws QueryValidatorException {
+    	if (references != null && !references.isEmpty()) {
+    		throw new QueryValidatorException(QueryPlugin.Util.getString("Request.Invalid_character_in_query")); //$NON-NLS-1$
+    	}
+    }
+
+    protected void resolveCommand(Command command) throws QueryResolverException, TeiidComponentException {
+        if (this.tempTableStore != null) {
+        	QueryResolver.setChildMetadata(command, tempTableStore.getMetadataStore().getData(), null);
+        }
+    	//ensure that the user command is distinct from the processing command
+        //rewrite and planning may alter options, symbols, etc.
+    	QueryResolver.resolveCommand(command, metadata, analysisRecord);
+    	
+    	this.userCommand = (Command)command.clone();
+    }
+        
+    private void validateQuery(Command command)
+        throws QueryValidatorException, TeiidComponentException {
+                
+        // Create generic sql validation visitor
+        AbstractValidationVisitor visitor = new ValidationVisitor();
+        validateWithVisitor(visitor, metadata, command);
+    }
+    
+    private Command parseCommand() throws QueryParserException {
+        String[] commands = requestMsg.getCommands();
+        ParseInfo parseInfo = createParseInfo(this.requestMsg);
+        if (requestMsg.isPreparedStatement() || requestMsg.isCallableStatement() || !requestMsg.isBatchedUpdate()) {
+        	String commandStr = commands[0];
+            return QueryParser.getQueryParser().parseCommand(commandStr, parseInfo);
+        } 
+        List<Command> parsedCommands = new ArrayList<Command>(commands.length);
+        for (int i = 0; i < commands.length; i++) {
+        	String updateCommand = commands[i];
+            parsedCommands.add(QueryParser.getQueryParser().parseCommand(updateCommand, parseInfo));
+        }
+        return new BatchedUpdateCommand(parsedCommands);
+    }
+
+	public static ParseInfo createParseInfo(RequestMessage requestMsg) {
+		ParseInfo parseInfo = new ParseInfo();
+    	parseInfo.ansiQuotedIdentifiers = requestMsg.isAnsiQuotedIdentifiers();
+		return parseInfo;
+	}
+
+    public static void validateWithVisitor(
+        AbstractValidationVisitor visitor,
+        QueryMetadataInterface metadata,
+        Command command)
+        throws QueryValidatorException, TeiidComponentException {
+
+        // Validate with visitor
+        ValidatorReport report = Validator.validate(command, metadata, visitor);
+        if (report.hasItems()) {
+            ValidatorFailure firstFailure = (ValidatorFailure) report.getItems().iterator().next();
+            throw new QueryValidatorException(firstFailure.getMessage());
+        }
+    }
+
+    private void createProcessor() throws TeiidComponentException {
+        
+        TransactionContext tc = transactionService.getOrCreateTransactionContext(workContext.getSessionId());
+        
+        Assertion.assertTrue(tc.getTransactionType() != TransactionContext.Scope.REQUEST, "Transaction already associated with request."); //$NON-NLS-1$
+
+        // If local or global transaction is not started.
+        if (tc.getTransactionType() == Scope.NONE) {
+            
+            boolean startAutoWrapTxn = false;
+            
+            if(RequestMessage.TXN_WRAP_ON.equals(requestMsg.getTxnAutoWrapMode())){ 
+                startAutoWrapTxn = true;
+            } else if (RequestMessage.TXN_WRAP_DETECT.equals(requestMsg.getTxnAutoWrapMode())){
+            	boolean transactionalRead = requestMsg.getTransactionIsolation() == Connection.TRANSACTION_REPEATABLE_READ
+						|| requestMsg.getTransactionIsolation() == Connection.TRANSACTION_SERIALIZABLE;
+        		startAutoWrapTxn = processPlan.requiresTransaction(transactionalRead);
+            } 
+            
+            if (startAutoWrapTxn) {
+                try {
+                    tc = transactionService.begin(tc);
+                } catch (XATransactionException err) {
+                    throw new TeiidComponentException(err);
+                }
+            }
+        } 
+        
+        this.transactionContext = tc;
+        this.processor = new QueryProcessor(processPlan, context, bufferManager, processorDataManager);
+    }
+
+    /**
+     * state side effects:
+     *      creates the analysis record
+     * 		creates the command context
+     * 		sets the pre-rewrite command on the request
+     * 		adds a limit clause if the row limit is specified
+     * 		sets the processor plan
+     * 
+     * @throws TeiidComponentException
+     * @throws TeiidProcessingException 
+     */
+    protected void generatePlan() throws TeiidComponentException, TeiidProcessingException {
+        Command command = parseCommand();
+
+        List<Reference> references = ReferenceCollectorVisitor.getReferences(command);
+        
+        checkReferences(references);
+        
+        this.analysisRecord = new AnalysisRecord(requestMsg.getShowPlan() != ShowPlan.OFF, requestMsg.getShowPlan() == ShowPlan.DEBUG);
+                
+        resolveCommand(command);
+        
+        validateAccess(userCommand);
+        
+        createCommandContext();
+
+        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
+        for (GroupSymbol groupSymbol : groups) {
+			if (groupSymbol.isTempTable()) {
+				this.context.setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
+				break;
+			}
+		}
+
+        validateQuery(command);
+        
+        command = QueryRewriter.rewrite(command, metadata, context);
+        
+        /*
+         * Adds a row limit to a query if Statement.setMaxRows has been called and the command
+         * doesn't already have a limit clause.
+         */
+        if (requestMsg.getRowLimit() > 0 && command instanceof QueryCommand) {
+            QueryCommand query = (QueryCommand)command;
+            if (query.getLimit() == null) {
+                query.setLimit(new Limit(null, new Constant(new Integer(requestMsg.getRowLimit()), DataTypeManager.DefaultDataClasses.INTEGER)));
+                this.addedLimit = true;
+            }
+        }
+        
+        try {
+        	// If using multi-source models, insert a proxy to simplify the supported capabilities.  This is 
+            // done OUTSIDE the cache (wrapped around the cache) intentionally to avoid caching the simplified
+            // capabilities which may be different for the same model in a different VDB used by this same DQP.
+        	CapabilitiesFinder finder = this.capabilitiesFinder;
+            if(this.multiSourceModels != null) {
+                finder = new MultiSourceCapabilitiesFinder(finder, this.multiSourceModels);
+            }
+            
+            boolean debug = analysisRecord.recordDebug();
+    		if(debug) {
+    			analysisRecord.println("\n============================================================================"); //$NON-NLS-1$
+                analysisRecord.println("USER COMMAND:\n" + command);		 //$NON-NLS-1$
+            }
+            // Run the optimizer
+            try {
+                processPlan = QueryOptimizer.optimizePlan(command, metadata, idGenerator, finder, analysisRecord, context);
+            } finally {
+                String debugLog = analysisRecord.getDebugLog();
+                if(debugLog != null && debugLog.length() > 0) {
+                    LogManager.log(requestMsg.getShowPlan()==ShowPlan.DEBUG?MessageLevel.INFO:MessageLevel.TRACE, LogConstants.CTX_QUERY_PLANNER, debugLog);               
+                }
+                if (analysisRecord.recordAnnotations() && analysisRecord.getAnnotations() != null && !analysisRecord.getAnnotations().isEmpty()) {
+                	LogManager.logDetail(LogConstants.CTX_QUERY_PLANNER, analysisRecord.getAnnotations());
+                }
+            }
+            LogManager.logDetail(LogConstants.CTX_DQP, new Object[] { QueryPlugin.Util.getString("BasicInterceptor.ProcessTree_for__4"), requestId, processPlan }); //$NON-NLS-1$
+        } catch (QueryMetadataException e) {
+            throw new QueryPlannerException(e, QueryPlugin.Util.getString("DQPCore.Unknown_query_metadata_exception_while_registering_query__{0}.", requestId)); //$NON-NLS-1$
+        }
+    }
+
+    public void processRequest() 
+        throws TeiidComponentException, TeiidProcessingException {
+                    
+    	LogManager.logDetail(LogConstants.CTX_DQP, this.requestId, "executing", this.requestMsg.isPreparedStatement()?"prepared":"", this.requestMsg.getCommandString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    	
+        initMetadata();
+        
+        generatePlan();
+        
+        postProcessXML();
+        
+        createProcessor();
+    }
+
+	private void postProcessXML() {
+        if (requestMsg.getXMLFormat() != null && processPlan instanceof XMLPlan) {
+        	((XMLPlan)processPlan).setXMLFormat(requestMsg.getXMLFormat());
+        }
+        this.context.setValidateXML(requestMsg.getValidationMode());
+	}
+
+	protected void validateAccess(Command command) throws QueryValidatorException, TeiidComponentException {
+		if (useEntitlements) {
+			AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(this.workContext.getAllowedDataPolicies(), this.workContext.getUserName());
+			visitor.setAllowCreateTemporaryTablesDefault(this.allowCreateTemporaryTablesByDefault);
+			validateWithVisitor(visitor, this.metadata, command);
+		}
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/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-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,745 +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();
-				}
-				
-				for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
-					connectorRequest.fullyCloseSource();
-			    }
-			}
-
-			this.resultsBuffer = null;
-			
-			for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
-				lobWorkItem.close();
-			}
-		}
-
-		if (this.transactionState == TransactionState.ACTIVE) { 
-			this.transactionState = TransactionState.DONE;
-            if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
-				try {
-	        		this.transactionService.rollback(transactionContext);
-	            } catch (XATransactionException e1) {
-	                LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$           
-	            } 
-			} else {
-				suspend();
-			}
-		}
-		
-		isClosed = true;
-
-		dqpCore.removeRequest(this);
-	    
-		if (this.processingException != null) {
-			sendError();			
-		} else {
-	        dqpCore.logMMCommand(this, Event.END, rowcount);
-		}
-	}
-
-	protected void processNew() throws TeiidProcessingException, TeiidComponentException {
-		SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
-				
-		boolean cachable = false;
-		CacheID cacheId = null;
-		boolean canUseCached = (requestMsg.useResultSetCache() || 
-				QueryParser.getQueryParser().parseCacheHint(requestMsg.getCommandString()) != null);
-		
-		if (rsCache != null) {
-			if (!canUseCached) {
-				LogManager.logDetail(LogConstants.CTX_DQP, requestID, "No cache directive"); //$NON-NLS-1$
-			} else {
-				ParseInfo pi = Request.createParseInfo(requestMsg);
-				cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
-		    	cachable = cacheId.setParameters(requestMsg.getParameterValues());
-				if (cachable) {
-					CachedResults cr = rsCache.get(cacheId);
-					if (cr != null) {
-						this.resultsBuffer = cr.getResults();
-						this.analysisRecord = cr.getAnalysisRecord();
-						request.initMetadata();
-						this.originalCommand = cr.getCommand(requestMsg.getCommandString(), request.metadata, pi);
-						request.validateAccess(this.originalCommand);
-						this.doneProducingBatches();
-						return;
-					} 
-				} else {
-					LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Parameters are not serializable - cache cannot be used for", cacheId); //$NON-NLS-1$
-				}
-			}
-		}
-		request.processRequest();
-		originalCommand = request.userCommand;
-        if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
-        	this.cid = cacheId;
-        }
-		processor = request.processor;
-		resultsBuffer = processor.createTupleBuffer();
-		if (this.cid != null && originalCommand.getCacheHint() != null) {
-			LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Using cache hint", originalCommand.getCacheHint()); //$NON-NLS-1$
-			resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
-		}
-		collector = new BatchCollector(processor, resultsBuffer) {
-			protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
-				boolean added = false;
-				if (cid != null || resultsBuffer.isLobs()) {
-					super.flushBatchDirect(batch, add);
-					added = true;
-				}
-				if (batch.getTerminationFlag()) {
-					doneProducingBatches();
-				}
-				if (doneProducingBatches && cid != null) {
-			    	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.isRestrictiveThan(Determinism.SESSION_DETERMINISTIC)) {
-	    				LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("RequestWorkItem.cache_nondeterministic", originalCommand)); //$NON-NLS-1$
-	    			}
-	                dqpCore.getRsCache().put(cid, determinismLevel, cr, originalCommand.getCacheHint() != null?originalCommand.getCacheHint().getTtl():null);
-			    }
-				add = sendResultsIfNeeded(batch);
-				if (!added) {
-					super.flushBatchDirect(batch, add);
-				}
-			}
-		};
-		resultsBuffer = collector.getTupleBuffer();
-		resultsBuffer.setForwardOnly(isForwardOnly());
-		analysisRecord = request.analysisRecord;
-		analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
-		transactionContext = request.transactionContext;
-		if (this.transactionContext != null && this.transactionContext.getTransactionType() != Scope.NONE) {
-			this.transactionState = TransactionState.ACTIVE;
-		}
-		if (requestMsg.isNoExec()) {
-		    doneProducingBatches();
-            resultsBuffer.close();
-            this.cid = null;
-		}
-	    this.returnsUpdateCount = request.returnsUpdateCount;
-		request = null;
-	}
-
-	/**
-	 * Send results if they have been requested.  This should only be called from the processing thread.
-	 */
-	protected boolean sendResultsIfNeeded(TupleBatch batch) throws TeiidComponentException {
-		ResultsMessage response = null;
-		ResultsReceiver<ResultsMessage> receiver = null;
-		boolean result = true;
-		synchronized (this) {
-			if (this.resultsReceiver == null
-					|| (this.begin > (batch != null?batch.getEndRow():this.resultsBuffer.getRowCount()) && !doneProducingBatches)
-					|| (this.transactionState == TransactionState.ACTIVE)) {
-				return result;
-			}
-		
-			if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-				LogManager.logDetail(LogConstants.CTX_DQP, "[RequestWorkItem.sendResultsIfNeeded] requestID:", requestID, "resultsID:", this.resultsBuffer, "done:", doneProducingBatches );   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			}
-	
-			//TODO: support fetching more than 1 batch
-			boolean fromBuffer = false;
-    		if (batch == null || !(batch.containsRow(this.begin) || (batch.getTerminationFlag() && batch.getEndRow() <= this.begin))) {
-	    		if (savedBatch != null && savedBatch.containsRow(this.begin)) {
-	    			batch = savedBatch;
-	    		} else {
-	    			batch = resultsBuffer.getBatch(begin);
-	    		}
-	    		savedBatch = null;
-	    		fromBuffer = true;
-	    	}
-    		int count = this.end - this.begin + 1;
-    		if (batch.getRowCount() > count) {
-    			int beginRow = Math.min(this.begin, batch.getEndRow() - count + 1);
-    			int endRow = Math.min(beginRow + count - 1, batch.getEndRow());
-    			boolean last = false;
-    			if (endRow == batch.getEndRow()) {
-    				last = batch.getTerminationFlag();
-    			} else if (fromBuffer && isForwardOnly()) {
-        			savedBatch = batch;
-    			}
-                List<List<?>> memoryRows = batch.getTuples();
-                batch = new TupleBatch(beginRow, memoryRows.subList(beginRow - batch.getBeginRow(), endRow - batch.getBeginRow() + 1));
-                batch.setTerminationFlag(last);
-    		} else if (!fromBuffer){
-    			result = !isForwardOnly();
-    		}
-	        int finalRowCount = this.resultsBuffer.isFinal()?this.resultsBuffer.getRowCount():(batch.getTerminationFlag()?batch.getEndRow():-1);
-	        
-	        response = createResultsMessage(batch.getAllTuples(), this.originalCommand.getProjectedSymbols());
-	        response.setFirstRow(batch.getBeginRow());
-	        response.setLastRow(batch.getEndRow());
-	        response.setUpdateResult(this.returnsUpdateCount);
-	        // set final row
-	        response.setFinalRow(finalRowCount);
-	
-	        // send any warnings with the response object
-	        List<Throwable> responseWarnings = new ArrayList<Throwable>();
-	        if (this.processor != null) {
-				List<Exception> currentWarnings = processor.getAndClearWarnings();
-			    if (currentWarnings != null) {
-			    	responseWarnings.addAll(currentWarnings);
-			    }
-	        }
-		    synchronized (warnings) {
-	        	responseWarnings.addAll(this.warnings);
-	        	this.warnings.clear();
-		    }
-	        response.setWarnings(responseWarnings);
-	        
-	        // If it is stored procedure, set parameters
-	        if (originalCommand instanceof StoredProcedure) {
-	        	StoredProcedure proc = (StoredProcedure)originalCommand;
-	        	if (proc.returnParameters()) {
-	        		response.setParameters(getParameterInfo(proc));
-	        	}
-	        }
-	        /*
-	         * mark the results sent at this point.
-	         * communication exceptions will be treated as non-recoverable 
-	         */
-            receiver = this.resultsReceiver;
-            this.resultsReceiver = null;    
-		}
-        receiver.receiveResults(response);
-        return result;
-	}
-    
-    public ResultsMessage createResultsMessage(List[] batch, List columnSymbols) {
-        String[] columnNames = new String[columnSymbols.size()];
-        String[] dataTypes = new String[columnSymbols.size()];
-
-        for(int i=0; i<columnSymbols.size(); i++) {
-            SingleElementSymbol symbol = (SingleElementSymbol) columnSymbols.get(i);
-            columnNames[i] = SingleElementSymbol.getShortName(symbol.getOutputName());
-            dataTypes[i] = DataTypeManager.getDataTypeName(symbol.getType());
-        }
-        ResultsMessage result = new ResultsMessage(requestMsg, batch, columnNames, dataTypes);
-        setAnalysisRecords(result);
-        return result;
-    }
-    
-	private void setAnalysisRecords(ResultsMessage response) {
-		if(analysisRecord != null) {
-        	if (requestMsg.getShowPlan() != ShowPlan.OFF) {
-        		if (processor != null) {
-        			analysisRecord.setQueryPlan(processor.getProcessorPlan().getDescriptionProperties());
-        		}
-        		response.setPlanDescription(analysisRecord.getQueryPlan());
-	            response.setAnnotations(analysisRecord.getAnnotations());
-        	}
-            if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
-            	response.setDebugLog(analysisRecord.getDebugLog());
-            }
-        }
-	}
-
-    private void sendError() {
-    	synchronized (this) {
-    		if (this.resultsReceiver == null) {
-    			LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Unable to send error to client as results were already sent.", requestID); //$NON-NLS-1$
-    			return;
-    		}
-    	}
-		LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
-        ResultsMessage response = new ResultsMessage(requestMsg);
-        response.setException(processingException);
-        setAnalysisRecords(response);
-        resultsReceiver.receiveResults(response);
-    }
-
-    private static List<ParameterInfo> getParameterInfo(StoredProcedure procedure) {
-        List<ParameterInfo> paramInfos = new ArrayList<ParameterInfo>();
-        
-        for (SPParameter param : procedure.getParameters()) {
-            ParameterInfo info = new ParameterInfo(param.getParameterType(), param.getResultSetColumns().size());
-            paramInfos.add(info);
-        }
-        
-        return paramInfos;
-    }
-    
-    public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
-    	LobWorkItem workItem = null;
-    	synchronized (lobStreams) {
-            workItem = this.lobStreams.get(new Integer(streamRequestId));
-            if (workItem == null) {
-            	workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
-            	lobStreams.put(new Integer(streamRequestId), workItem);
-            }
-		}
-    	workItem.setResultsReceiver(chunckReceiver);
-        dqpCore.addWork(workItem);
-    }
-    
-    public void removeLobStream(int streamRequestId) {
-        this.lobStreams.remove(new Integer(streamRequestId));
-    } 
-    
-    public boolean requestCancel() throws TeiidComponentException {
-    	synchronized (this) {
-        	if (this.isCanceled || this.closeRequested) {
-        		return false;
-        	}
-        	this.isCanceled = true;
-		}
-    	if (this.processor != null) {
-    		this.processor.requestCanceled();
-    	}
-    	
-        // Cancel Connector atomic requests 
-        try {
-        	for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
-                connectorRequest.cancelRequest();
-            }
-        } finally {
-        	try {
-	            if (transactionService != null) {
-	                try {
-	                    transactionService.cancelTransactions(requestID.getConnectionID(), true);
-	                } catch (XATransactionException err) {
-	                    throw new TeiidComponentException(err);
-	                }
-	            }
-        	} finally {
-        		this.moreWork();
-        	}
-        }
-        return true;
-    }
-    
-    public boolean requestAtomicRequestCancel(AtomicRequestID ari) throws TeiidComponentException {
-    	// in the case that this does not support partial results; cancel
-        // the original processor request.
-        if(!requestMsg.supportsPartialResults()) {
-        	return requestCancel();
-        }
-        
-        DataTierTupleSource connectorRequest = this.connectorInfo.get(ari);
-        if (connectorRequest != null) {
-	        connectorRequest.cancelRequest();
-        	return true;
-        }
-        
-		LogManager.logDetail(LogConstants.CTX_DQP, "Connector request not found. AtomicRequestID=", ari); //$NON-NLS-1$ 
-        return false;
-    }
-    
-    public void requestClose() throws TeiidComponentException {
-    	synchronized (this) {
-        	if (this.state == ProcessingState.CLOSE || this.closeRequested) {
-        		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
-        			LogManager.logDetail(LogConstants.CTX_DQP, "Request already closing" + requestID); //$NON-NLS-1$
-        		}
-        		return;
-        	}
-		}
-    	this.closeRequested = true;
-    	if (!this.doneProducingBatches) {
-    		this.requestCancel(); //pending work should be canceled for fastest clean up
-    	}
-    	this.moreWork();
-    }
-    
-    public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
-    	this.requestResults(batchFirst, batchLast, receiver);
-    	this.moreWork(); 
-    }
-    
-    public void closeAtomicRequest(AtomicRequestID atomicRequestId) {
-        connectorInfo.remove(atomicRequestId);
-        LogManager.logTrace(LogConstants.CTX_DQP, new Object[] {"closed atomic-request:", atomicRequestId});  //$NON-NLS-1$
-    }
-    
-	public void addConnectorRequest(AtomicRequestID atomicRequestId, DataTierTupleSource connInfo) {
-		connectorInfo.put(atomicRequestId, connInfo);
-	}
-    
-    /**
-	 * <p>This method add information to the warning on the work item for the given
-	 * <code>RequestID</code>. This method is called from <code>DataTierManager</code></p>
-	 */
-    public void addSourceFailureDetails(SourceWarning details) {
-    	synchronized (warnings) {
-			this.warnings.add(details);
-    	}
-	}
-        
-	boolean isCanceled() {
-		return isCanceled;
-	}
-	
-	Command getOriginalCommand() throws TeiidProcessingException {
-		if (this.originalCommand == null) {
-			if (this.processingException != null) {
-				throw new TeiidProcessingException(this.processingException);
-			} 
-			throw new IllegalStateException("Original command is not available"); //$NON-NLS-1$
-		}
-		return this.originalCommand;
-	}
-	
-	void setOriginalCommand(Command originalCommand) {
-		this.originalCommand = originalCommand;
-	}
-
-	TransactionContext getTransactionContext() {
-		return transactionContext;
-	}
-	
-	
-	Collection<DataTierTupleSource> getConnectorRequests() {
-		return new LinkedList<DataTierTupleSource>(this.connectorInfo.values());
-	}
-	
-	DataTierTupleSource getConnectorRequest(AtomicRequestID id) {
-		return this.connectorInfo.get(id);
-	}
-	
-	public List<TeiidException> getWarnings() {
-		return warnings;
-	}
-
-	@Override
-	public String toString() {
-		return this.requestID.toString();
-	}
-
-	public DQPWorkContext getDqpWorkContext() {
-		return dqpWorkContext;
-	}
-	
-	public long getProcessingTimestamp() {
-		return processingTimestamp;
-	}
-	
-	@Override
-	public void release() {
-		try {
-			requestCancel();
-		} catch (TeiidComponentException e) {
-			LogManager.logWarning(LogConstants.CTX_DQP, e, "Failed to cancel " + requestID); //$NON-NLS-1$
-		}
-	}
-
-	private void doneProducingBatches() {
-		this.doneProducingBatches = true;
-		dqpCore.finishProcessing(this);
-	}
-	
-	@Override
-	public int getPriority() {
-		return (closeRequested || isCanceled) ? 0 : 1000;
-	}
-	
-	@Override
-	public long getCreationTime() {
-		return processingTimestamp;
-	}
-
-}
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java (from rev 2762, trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,745 @@
+/*
+ * 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();
+				}
+				
+				for (DataTierTupleSource connectorRequest : this.connectorInfo.values()) {
+					connectorRequest.fullyCloseSource();
+			    }
+			}
+
+			this.resultsBuffer = null;
+			
+			for (LobWorkItem lobWorkItem : this.lobStreams.values()) {
+				lobWorkItem.close();
+			}
+		}
+
+		if (this.transactionState == TransactionState.ACTIVE) { 
+			this.transactionState = TransactionState.DONE;
+            if (transactionContext.getTransactionType() == TransactionContext.Scope.REQUEST) {
+				try {
+	        		this.transactionService.rollback(transactionContext);
+	            } catch (XATransactionException e1) {
+	                LogManager.logWarning(LogConstants.CTX_DQP, e1, QueryPlugin.Util.getString("ProcessWorker.failed_rollback")); //$NON-NLS-1$           
+	            } 
+			} else {
+				suspend();
+			}
+		}
+		
+		isClosed = true;
+
+		dqpCore.removeRequest(this);
+	    
+		if (this.processingException != null) {
+			sendError();			
+		} else {
+	        dqpCore.logMMCommand(this, Event.END, rowcount);
+		}
+	}
+
+	protected void processNew() throws TeiidProcessingException, TeiidComponentException {
+		SessionAwareCache<CachedResults> rsCache = dqpCore.getRsCache();
+				
+		boolean cachable = false;
+		CacheID cacheId = null;
+		boolean canUseCached = (requestMsg.useResultSetCache() || 
+				QueryParser.getQueryParser().parseCacheHint(requestMsg.getCommandString()) != null);
+		
+		if (rsCache != null) {
+			if (!canUseCached) {
+				LogManager.logDetail(LogConstants.CTX_DQP, requestID, "No cache directive"); //$NON-NLS-1$
+			} else {
+				ParseInfo pi = Request.createParseInfo(requestMsg);
+				cacheId = new CacheID(this.dqpWorkContext, pi, requestMsg.getCommandString());
+		    	cachable = cacheId.setParameters(requestMsg.getParameterValues());
+				if (cachable) {
+					CachedResults cr = rsCache.get(cacheId);
+					if (cr != null) {
+						this.resultsBuffer = cr.getResults();
+						this.analysisRecord = cr.getAnalysisRecord();
+						request.initMetadata();
+						this.originalCommand = cr.getCommand(requestMsg.getCommandString(), request.metadata, pi);
+						request.validateAccess(this.originalCommand);
+						this.doneProducingBatches();
+						return;
+					} 
+				} else {
+					LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Parameters are not serializable - cache cannot be used for", cacheId); //$NON-NLS-1$
+				}
+			}
+		}
+		request.processRequest();
+		originalCommand = request.userCommand;
+        if (cachable && (requestMsg.useResultSetCache() || originalCommand.getCacheHint() != null) && rsCache != null && originalCommand.areResultsCachable()) {
+        	this.cid = cacheId;
+        }
+		processor = request.processor;
+		resultsBuffer = processor.createTupleBuffer();
+		if (this.cid != null && originalCommand.getCacheHint() != null) {
+			LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Using cache hint", originalCommand.getCacheHint()); //$NON-NLS-1$
+			resultsBuffer.setPrefersMemory(originalCommand.getCacheHint().getPrefersMemory());
+		}
+		collector = new BatchCollector(processor, resultsBuffer) {
+			protected void flushBatchDirect(TupleBatch batch, boolean add) throws TeiidComponentException,TeiidProcessingException {
+				boolean added = false;
+				if (cid != null || resultsBuffer.isLobs()) {
+					super.flushBatchDirect(batch, add);
+					added = true;
+				}
+				if (batch.getTerminationFlag()) {
+					doneProducingBatches();
+				}
+				if (doneProducingBatches && cid != null) {
+			    	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.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,305 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.dqp.internal.process;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.teiid.cache.Cachable;
-import org.teiid.cache.Cache;
-import org.teiid.cache.CacheConfiguration;
-import org.teiid.cache.CacheFactory;
-import org.teiid.cache.DefaultCache;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.vdb.runtime.VDBKey;
-
-
-/**
- * This class is used to cache session aware objects
- */
-public class SessionAwareCache<T> {
-	public static final int DEFAULT_MAX_SIZE_TOTAL = 512;
-
-	private Cache<CacheID, T> localCache;
-	private Cache<CacheID, T> distributedCache;
-	private Cache tupleBatchCache;
-	
-	private int maxSize = DEFAULT_MAX_SIZE_TOTAL;
-	
-	private AtomicInteger cacheHit = new AtomicInteger();
-	private AtomicInteger totalRequests = new AtomicInteger();
-	
-	private BufferManager bufferManager;
-	
-	public SessionAwareCache(){
-		this(DEFAULT_MAX_SIZE_TOTAL);
-	}
-	
-	SessionAwareCache(int maxSize){
-		this(new DefaultCacheFactory(), Cache.Type.RESULTSET, new CacheConfiguration(Policy.LRU, 60, maxSize));
-	}
-	
-	SessionAwareCache (final CacheFactory cacheFactory, final Cache.Type type, final CacheConfiguration config){
-		this.maxSize = config.getMaxEntries();
-		if(this.maxSize < 0){
-			this.maxSize = DEFAULT_MAX_SIZE_TOTAL;
-		}		
-		this.localCache = new DefaultCache<CacheID, T>("local", maxSize, config.getMaxAgeInSeconds()*1000); //$NON-NLS-1$
-		
-		if (type == Cache.Type.PREPAREDPLAN) {
-			this.distributedCache = localCache;
-		}
-		else {
-			this.distributedCache = cacheFactory.get(type, config);
-			if (type == Cache.Type.RESULTSET) {
-				this.tupleBatchCache = cacheFactory.get(Cache.Type.RESULTSET_BATCHES, config);
-			}
-			else {
-				this.tupleBatchCache = this.distributedCache;
-			}
-		}
-	}	
-	
-	public T get(CacheID id){
-
-		this.totalRequests.getAndIncrement();
-		
-		id.setSessionId(id.originalSessionId);
-		T result = localCache.get(id);
-		
-		if (result == null) {
-			id.setSessionId(null);
-			
-			id.setUserName(id.originalUserName);
-			result = distributedCache.get(id);
-			
-			if (result == null) {
-				id.setUserName(null);
-				result = distributedCache.get(id);
-			}
-			
-			if (result != null && result instanceof Cachable) {
-				Cachable c = (Cachable)result;
-				if (!c.restore(this.tupleBatchCache, this.bufferManager)) {
-					result = null;
-				}
-			}
-		}
-		
-		if (result != null) {
-			LogManager.logTrace(LogConstants.CTX_DQP, "Cache hit for", id); //$NON-NLS-1$
-			cacheHit.getAndIncrement();
-		} else {
-			LogManager.logTrace(LogConstants.CTX_DQP, "Cache miss for", id); //$NON-NLS-1$
-		}
-		return result;
-	}
-	
-	public int getCacheHitCount() {
-		return cacheHit.get();
-	}
-		
-	public int getRequestCount() {
-		return this.totalRequests.get();
-	}
-	
-	public int getTotalCacheEntries() {
-		if (this.localCache == this.distributedCache) {
-			return this.localCache.size();
-		}
-		return localCache.size() + distributedCache.size();
-	}
-	
-	public void put(CacheID id, Determinism determinismLevel, T t, Long ttl){
-		if (determinismLevel.isRestrictiveThanOrEqual(Determinism.SESSION_DETERMINISTIC)) {
-			id.setSessionId(id.originalSessionId);
-			LogManager.logTrace(LogConstants.CTX_DQP, "Adding to session/local cache", id); //$NON-NLS-1$
-			this.localCache.put(id, t, ttl);
-		} 
-		else {
-			
-			boolean insert = true;
-			
-			id.setSessionId(null);
-			
-			if (determinismLevel == Determinism.USER_DETERMINISTIC) {
-				id.setUserName(id.originalUserName);
-			}
-			else {
-				id.setUserName(null);
-			}
-			
-			if (t instanceof Cachable) {
-				Cachable c = (Cachable)t;
-				insert = c.prepare(this.tupleBatchCache, this.bufferManager);
-			}
-			
-			if (insert) {
-				LogManager.logTrace(LogConstants.CTX_DQP, "Adding to global/distributed cache", id); //$NON-NLS-1$
-				this.distributedCache.put(id, t, ttl);
-			}
-		}
-	}
-	
-	/**
-	 * Clear all the cached plans for all the clientConns
-	 * @param clientConn ClientConnection
-	 */
-	public void clearAll(){
-		this.localCache.clear();
-		this.distributedCache.clear();
-		this.totalRequests.set(0);
-		this.cacheHit.set(0);		
-	}	
-	
-	public void clearForVDB(String vdbName, int version) {
-		clearCache(this.localCache, vdbName, version);
-		clearCache(this.distributedCache, vdbName, version);
-	}
-	
-	private void clearCache(Cache<CacheID, T> cache, String vdbName, int version) {
-		Set<CacheID> keys = cache.keys();
-		VDBKey vdbKey = new VDBKey(vdbName, version);
-		for (CacheID key:keys) {
-			if (key.vdbInfo.equals(vdbKey)) {
-				cache.remove(key);
-			}
-		}
-	}
-	
-	public static class CacheID implements Serializable {
-		private static final long serialVersionUID = 8261905111156764744L;
-		private String sql;
-		private VDBKey vdbInfo;
-		private ParseInfo pi;
-		private String sessionId;
-		private String originalSessionId;
-		private List<Serializable> parameters;
-		private String userName;
-		private String originalUserName;
-		
-		public CacheID(DQPWorkContext context, ParseInfo pi, String sql){
-			this(pi, sql, context.getVdbName(), context.getVdbVersion(), context.getSessionId(), context.getUserName());
-		}
-		
-		public CacheID(ParseInfo pi, String sql, String vdbName, int vdbVersion, String sessionId, String userName){
-			this.sql = sql;
-			this.vdbInfo = new VDBKey(vdbName, vdbVersion);
-			this.pi = pi;
-			this.originalSessionId = sessionId;
-			this.originalUserName = userName;
-		}
-
-		
-		public String getSessionId() {
-			return sessionId;
-		}
-		
-		public String getUserName() {
-			return userName;
-		}
-		
-		private void setSessionId(String sessionId) {
-			this.sessionId = sessionId;
-		}
-		
-		/**
-		 * Set the raw (non-Constant) parameter values.
-		 * @param parameters
-		 * @return
-		 */
-		public boolean setParameters(List<?> parameters) {
-			if (parameters !=  null && !parameters.isEmpty()) {
-				this.parameters = new ArrayList<Serializable>();
-				for (Object obj:parameters) {
-					if (obj == null) {
-						this.parameters.add(null);
-						continue;
-					}
-					if (!(obj instanceof Serializable)) {
-						return false;
-					}
-					
-					Class<?> type = DataTypeManager.determineDataTypeClass(obj);
-					if (DataTypeManager.isLOB(type) || type == DataTypeManager.DefaultDataClasses.OBJECT) {
-						return false;
-					}
-					this.parameters.add((Serializable)obj);
-				}
-			}
-			return true;
-		}
-		
-		public String getSql() {
-			return sql;
-		}
-		
-		void setUserName(String name) {
-			this.userName = name;
-		}
-						
-		public boolean equals(Object obj){
-	        if(obj == this) {
-	            return true;
-	        } 
-	        if(! (obj instanceof CacheID)) {
-	            return false;
-	        } 
-        	CacheID that = (CacheID)obj;
-            return EquivalenceUtil.areEqual(this.pi, that.pi) && this.vdbInfo.equals(that.vdbInfo) && this.sql.equals(that.sql) 
-            	&& EquivalenceUtil.areEqual(this.userName, that.userName)            	
-            	&& EquivalenceUtil.areEqual(this.sessionId, that.sessionId)
-            	&& EquivalenceUtil.areEqual(this.parameters, that.parameters);
-		}
-		
-	    public int hashCode() {
-	        return HashCodeUtil.hashCode(0, vdbInfo, sql, pi, this.userName, sessionId, parameters);
-	    }
-	    
-	    @Override
-	    public String toString() {
-	    	return "Cache Entry<" + originalSessionId + "="+ originalUserName + "> params:" + parameters + " sql:" + sql; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	    }
-	    
-	}
-	
-    int getSpaceAllowed() {
-        return maxSize;
-    }
-    
-    public void setBufferManager(BufferManager bufferManager) {
-    	this.bufferManager = bufferManager;
-    }
-}

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/eval/Evaluator.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1025 +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.eval;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-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.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-import net.sf.saxon.trans.XPathException;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.ComponentNotFoundException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-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.Sequencable;
-import org.teiid.core.types.Streamable;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.types.XMLType.Type;
-import org.teiid.core.types.basic.StringToSQLXMLTransform;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionDescriptor;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.source.XMLSystemFunctions;
-import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.AbstractSetCriteria;
-import org.teiid.query.sql.lang.CollectionValueIterator;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.ExpressionCriteria;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.CaseExpression;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ContextReference;
-import org.teiid.query.sql.symbol.DerivedColumn;
-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.QueryString;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.symbol.TextLine;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-import org.teiid.query.sql.symbol.XMLParse;
-import org.teiid.query.sql.symbol.XMLQuery;
-import org.teiid.query.sql.symbol.XMLSerialize;
-import org.teiid.query.sql.symbol.XMLNamespaces.NamespaceItem;
-import org.teiid.query.sql.util.ValueIterator;
-import org.teiid.query.sql.util.ValueIteratorSource;
-import org.teiid.query.util.CommandContext;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result;
-import org.teiid.translator.WSConnection.Util;
-
-public class Evaluator {
-
-    private final class SequenceReader extends Reader {
-		private LinkedList<Reader> readers;
-		private Reader current = null;
-		
-		public SequenceReader(LinkedList<Reader> readers) {
-			this.readers = readers;
-		}
-
-		@Override
-		public void close() throws IOException {
-			for (Reader reader : readers) {
-				try {
-					reader.close();
-				} catch (IOException e) {
-					
-				}
-			}
-		}
-
-		@Override
-		public int read(char[] cbuf, int off, int len)
-				throws IOException {
-			if (current == null && !readers.isEmpty()) {
-				current = readers.removeFirst();
-			}
-			if (current == null) {
-				return -1;
-			}
-			int read = current.read(cbuf, off, len);
-			if (read == -1) {
-				current.close();
-				current = null;
-				read = 0;
-			} 
-			if (read < len) {
-				int nextRead = read(cbuf, off + read, len - read);
-				if (nextRead > 0) {
-					read += nextRead;
-				}
-			}
-			return read;
-		}
-	}
-
-	public static class NameValuePair<T> {
-		public String name;
-		public T value;
-		
-		public NameValuePair(String name, T value) {
-			this.name = name;
-			this.value = value;
-		}
-	}
-
-	private final static char[] REGEX_RESERVED = new char[] {'$', '(', ')', '*', '.', '?', '[', '\\', ']', '^', '{', '|', '}'}; //in sorted order
-    private final static MatchCriteria.PatternTranslator LIKE_TO_REGEX = new MatchCriteria.PatternTranslator(".*", ".", REGEX_RESERVED, '\\');  //$NON-NLS-1$ //$NON-NLS-2$
-
-    private Map elements;
-    
-    protected ProcessorDataManager dataMgr;
-    protected CommandContext context;
-    
-    public static boolean evaluate(Criteria criteria) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-    	return new Evaluator(Collections.emptyMap(), null, null).evaluate(criteria, Collections.emptyList());
-    }
-    
-    public static Object evaluate(Expression expression) throws ExpressionEvaluationException, BlockedException, TeiidComponentException  {
-    	return new Evaluator(Collections.emptyMap(), null, null).evaluate(expression, Collections.emptyList());
-    }
-    
-    public Evaluator(Map elements, ProcessorDataManager dataMgr, CommandContext context) {
-		this.context = context;
-		this.dataMgr = dataMgr;
-		this.elements = elements;
-	}
-    
-    public void initialize(CommandContext context, ProcessorDataManager dataMgr) {
-		this.context = context;
-		this.dataMgr = dataMgr;
-	}
-
-	public boolean evaluate(Criteria criteria, List<?> tuple)
-        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-        return Boolean.TRUE.equals(evaluateTVL(criteria, tuple));
-    }
-
-    public Boolean evaluateTVL(Criteria criteria, List<?> tuple)
-        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-    	
-		if(criteria instanceof CompoundCriteria) {
-			return evaluate((CompoundCriteria)criteria, tuple);
-		} else if(criteria instanceof NotCriteria) {
-			return evaluate((NotCriteria)criteria, tuple);
-		} else if(criteria instanceof CompareCriteria) {
-			return evaluate((CompareCriteria)criteria, tuple);
-		} else if(criteria instanceof MatchCriteria) {
-			return evaluate((MatchCriteria)criteria, tuple);
-		} else if(criteria instanceof AbstractSetCriteria) {
-			return evaluate((AbstractSetCriteria)criteria, tuple);
-		} else if(criteria instanceof IsNullCriteria) {
-			return Boolean.valueOf(evaluate((IsNullCriteria)criteria, tuple));
-        } else if(criteria instanceof SubqueryCompareCriteria) {
-            return evaluate((SubqueryCompareCriteria)criteria, tuple);
-        } else if(criteria instanceof ExistsCriteria) {
-            return Boolean.valueOf(evaluate((ExistsCriteria)criteria, tuple));
-        } else if (criteria instanceof ExpressionCriteria) {
-        	return (Boolean)evaluate(((ExpressionCriteria)criteria).getExpression(), tuple);
-		} else {
-            throw new ExpressionEvaluationException("ERR.015.006.0010", QueryPlugin.Util.getString("ERR.015.006.0010", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-	}
-
-	public Boolean evaluate(CompoundCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-		List subCrits = criteria.getCriteria();
-		Iterator subCritIter = subCrits.iterator();
-
-		boolean and = criteria.getOperator() == CompoundCriteria.AND;
-        Boolean result = and?Boolean.TRUE:Boolean.FALSE;
-		while(subCritIter.hasNext()) {
-			Criteria subCrit = (Criteria) subCritIter.next();
-			Boolean value = evaluateTVL(subCrit, tuple);
-            if (value == null) {
-				result = null;
-			} else if (!value.booleanValue()) {
-				if (and) {
-					return Boolean.FALSE;
-				}
-            } else if (!and) {
-            	return Boolean.TRUE;
-            }
-		}
-		return result;
-	}
-
-	public Boolean evaluate(NotCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-		Criteria subCrit = criteria.getCriteria();
-		Boolean result = evaluateTVL(subCrit, tuple);
-        if (result == null) {
-            return null;
-        }
-        if (result.booleanValue()) {
-            return Boolean.FALSE;
-        }
-        return Boolean.TRUE;
-	}
-
-	public Boolean evaluate(CompareCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-		// Evaluate left expression
-		Object leftValue = null;
-		try {
-			leftValue = evaluate(criteria.getLeftExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[] {"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-
-		// Shortcut if null
-		if(leftValue == null) {
-			return null;
-		}
-
-		// Evaluate right expression
-		Object rightValue = null;
-		try {
-			rightValue = evaluate(criteria.getRightExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-
-		// Shortcut if null
-		if(rightValue == null) {
-			return null;
-		}
-
-		// Compare two non-null values using specified operator
-		switch(criteria.getOperator()) {
-			case CompareCriteria.EQ:
-				return Boolean.valueOf(compareValues(leftValue, rightValue) == 0);
-			case CompareCriteria.NE:
-				return Boolean.valueOf(compareValues(leftValue, rightValue) != 0);
-			case CompareCriteria.LT:
-				return Boolean.valueOf((compareValues(leftValue, rightValue) < 0));
-			case CompareCriteria.LE:
-				return Boolean.valueOf((compareValues(leftValue, rightValue) <= 0));
-			case CompareCriteria.GT:
-				return Boolean.valueOf((compareValues(leftValue, rightValue) > 0));
-			case CompareCriteria.GE:
-				return Boolean.valueOf((compareValues(leftValue, rightValue) >= 0));
-			default:
-                throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-	}
-
-    private final int compareValues(Object leftValue, Object rightValue) {
-    	assert leftValue instanceof Comparable<?>;
-    	assert rightValue instanceof Comparable<?>;
-    	if (leftValue == rightValue) {
-    		return 0;
-    	}
-        return ((Comparable<Object>)leftValue).compareTo(rightValue);
-    }
-
-	public Boolean evaluate(MatchCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-        boolean result = false;
-		// Evaluate left expression
-        Object value = null;
-		try {
-			value = evaluate(criteria.getLeftExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-
-		// Shortcut if null
-		if(value == null) {
-            return null;
-        }
-        
-        CharSequence leftValue = null;
-        
-        if (value instanceof CharSequence) {
-            leftValue = (CharSequence)value;
-        } else {
-            try {
-                leftValue = ((Sequencable)value).getCharSequence();
-            } catch (SQLException err) {
-                throw new ExpressionEvaluationException(err, err.getMessage()); 
-            }
-        }
-
-		// Evaluate right expression
-		String rightValue = null;
-		try {
-			rightValue = (String) evaluate(criteria.getRightExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-
-		// Shortcut if null
-		if(rightValue == null) {
-            return null;
-        }
-        
-        result = match(rightValue, criteria.getEscapeChar(), leftValue);
-        
-        return Boolean.valueOf(result ^ criteria.isNegated());
-	}
-
-	private boolean match(String pattern, char escape, CharSequence search)
-		throws ExpressionEvaluationException {
-
-		StringBuffer rePattern = LIKE_TO_REGEX.translate(pattern, escape);
-		
-		// Insert leading and trailing characters to ensure match of full string
-		rePattern.insert(0, '^');
-		rePattern.append('$');
-
-		try {
-            Pattern patternRegex = Pattern.compile(rePattern.toString(), Pattern.DOTALL);
-            Matcher matcher = patternRegex.matcher(search);
-            return matcher.matches();
-		} catch(PatternSyntaxException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0014", QueryPlugin.Util.getString("ERR.015.006.0014", new Object[]{pattern, e.getMessage()})); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-	}
-
-	private Boolean evaluate(AbstractSetCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-		// Evaluate expression
-		Object leftValue = null;
-		try {
-			leftValue = evaluate(criteria.getExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-
-		// Shortcut if null
-		if(leftValue == null) {
-            return null;
-        }
-        Boolean result = Boolean.FALSE;
-
-        ValueIterator valueIter = null;
-        if (criteria instanceof SetCriteria) {
-        	SetCriteria set = (SetCriteria)criteria;
-        	if (set.isAllConstants()) {
-        		boolean exists = set.getValues().contains(new Constant(leftValue, criteria.getExpression().getType()));
-        		if (!exists) {
-        			if (set.getValues().contains(Constant.NULL_CONSTANT)) {
-        				return null;
-        			}
-        			return criteria.isNegated();
-        		}
-        		return !criteria.isNegated();
-        	}
-        	valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
-        } else if (criteria instanceof DependentSetCriteria){
-        	ContextReference ref = (ContextReference)criteria;
-    		ValueIteratorSource vis = (ValueIteratorSource)getContext(criteria).getVariableContext().getGlobalValue(ref.getContextSymbol());
-    		Set<Object> values;
-    		try {
-    			values = vis.getCachedSet(ref.getValueExpression());
-    		} catch (TeiidProcessingException e) {
-    			throw new ExpressionEvaluationException(e, e.getMessage());
-    		}
-        	if (values != null) {
-        		return values.contains(leftValue);
-        	}
-        	//there are too many values to justify a linear search or holding
-        	//them in memory
-        	return true;
-        } else if (criteria instanceof SubquerySetCriteria) {
-        	try {
-				valueIter = evaluateSubquery((SubquerySetCriteria)criteria, tuple);
-			} catch (TeiidProcessingException e) {
-				throw new ExpressionEvaluationException(e, e.getMessage());
-			}
-        } else {
-        	throw new AssertionError("unknown set criteria type"); //$NON-NLS-1$
-        }
-        while(valueIter.hasNext()) {
-            Object possibleValue = valueIter.next();
-            Object value = null;
-            if(possibleValue instanceof Expression) {
-    			try {
-    				value = evaluate((Expression) possibleValue, tuple);
-    			} catch(ExpressionEvaluationException e) {
-                    throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", possibleValue)); //$NON-NLS-1$ //$NON-NLS-2$
-    			}
-            } else {
-                value = possibleValue;
-            }
-
-			if(value != null) {
-				if(compareValues(leftValue, value) == 0) {
-					return Boolean.valueOf(!criteria.isNegated());
-				} // else try next value
-			} else {
-			    result = null;
-            }
-		}
-        
-        if (result == null) {
-            return null;
-        }
-        
-        return Boolean.valueOf(criteria.isNegated());
-	}
-
-	public boolean evaluate(IsNullCriteria criteria, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-		// Evaluate expression
-		Object value = null;
-		try {
-			value = evaluate(criteria.getExpression(), tuple);
-		} catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-
-		return (value == null ^ criteria.isNegated());
-	}
-
-    private Boolean evaluate(SubqueryCompareCriteria criteria, List<?> tuple)
-        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-
-        // Evaluate expression
-        Object leftValue = null;
-        try {
-            leftValue = evaluate(criteria.getLeftExpression(), tuple);
-        } catch(ExpressionEvaluationException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-
-        // Shortcut if null
-        if(leftValue == null) {
-            return null;
-        }
-
-        // Need to be careful to initialize this variable carefully for the case
-        // where valueIterator has no values, and the block below is not entered.
-        // If there are no rows, and ALL is the predicate quantifier, the result
-        // should be true.  If SOME is the predicate quantifier, or no quantifier
-        // is used, the result should be false.
-        Boolean result = Boolean.FALSE;
-        if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ALL){
-            result = Boolean.TRUE;
-        }
-
-        ValueIterator valueIter;
-		try {
-			valueIter = evaluateSubquery(criteria, tuple);
-		} catch (TeiidProcessingException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		}
-        while(valueIter.hasNext()) {
-            Object value = valueIter.next();
-
-            if(value != null) {
-            	int compare = compareValues(leftValue, value);
-                // Compare two non-null values using specified operator
-                switch(criteria.getOperator()) {
-                    case SubqueryCompareCriteria.EQ:
-                        result = Boolean.valueOf(compare == 0);
-                        break;
-                    case SubqueryCompareCriteria.NE:
-                        result = Boolean.valueOf(compare != 0);
-                        break;
-                    case SubqueryCompareCriteria.LT:
-                        result = Boolean.valueOf(compare < 0);
-                        break;
-                    case SubqueryCompareCriteria.LE:
-                        result = Boolean.valueOf(compare <= 0);
-                        break;
-                    case SubqueryCompareCriteria.GT:
-                        result = Boolean.valueOf(compare > 0);
-                        break;
-                    case SubqueryCompareCriteria.GE:
-                        result = Boolean.valueOf(compare >= 0);
-                        break;
-                    default:
-                        throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
-                }
-
-                switch(criteria.getPredicateQuantifier()) {
-                    case SubqueryCompareCriteria.ALL:
-                        if (Boolean.FALSE.equals(result)){
-                            return Boolean.FALSE;
-                        }
-                        break;
-                    case SubqueryCompareCriteria.SOME:
-                        if (Boolean.TRUE.equals(result)){
-                            return Boolean.TRUE;
-                        }
-                        break;
-                    default:
-                        throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
-                }
-
-            } else { // value is null
-
-                switch(criteria.getPredicateQuantifier()) {
-                    case SubqueryCompareCriteria.ALL:
-                        // null counts as unknown; one unknown means the whole thing is unknown
-                        return null;
-                    case SubqueryCompareCriteria.SOME:
-                        result = null;
-                        break;
-                    default:
-                        throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
-                }
-            }
-
-
-        } //end value iteration
-
-        return result;
-    }
-
-    public boolean evaluate(ExistsCriteria criteria, List<?> tuple)
-        throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
-
-        ValueIterator valueIter;
-		try {
-			valueIter = evaluateSubquery(criteria, tuple);
-		} catch (TeiidProcessingException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		}
-        if(valueIter.hasNext()) {
-            return true;
-        }
-        return false;
-    }
-    
-	public Object evaluate(Expression expression, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-	
-	    try {
-			return internalEvaluate(expression, tuple);
-	    } catch (ExpressionEvaluationException e) {
-	        throw new ExpressionEvaluationException(e, QueryPlugin.Util.getString("ExpressionEvaluator.Eval_failed", new Object[] {expression, e.getMessage()})); //$NON-NLS-1$
-	    }
-	}
-	
-	private Object internalEvaluate(Expression expression, List<?> tuple)
-	   throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-	
-	   if(expression instanceof SingleElementSymbol) {
-		   if (elements != null) {
-		       // Try to evaluate by lookup in the elements map (may work for both ElementSymbol and ExpressionSymbol
-		       Integer index = (Integer) elements.get(expression);
-		       if(index != null) {
-		           return tuple.get(index.intValue());
-		       }
-		   }
-		   
-	       // Otherwise this should be an ExpressionSymbol and we just need to dive in and evaluate the expression itself
-	       if (expression instanceof ExpressionSymbol && !(expression instanceof AggregateSymbol)) {            
-	           ExpressionSymbol exprSyb = (ExpressionSymbol) expression;
-	           Expression expr = exprSyb.getExpression();
-	           return internalEvaluate(expr, tuple);
-	       } 
-	       
-	       return getContext(expression).getFromContext(expression);
-	   } 
-	   if(expression instanceof Constant) {
-	       return ((Constant) expression).getValue();
-	   } else if(expression instanceof Function) {
-	       return evaluate((Function) expression, tuple);
-	   } else if(expression instanceof CaseExpression) {
-	       return evaluate((CaseExpression) expression, tuple);
-	   } else if(expression instanceof SearchedCaseExpression) {
-	       return evaluate((SearchedCaseExpression) expression, tuple);
-	   } else if(expression instanceof Reference) {
-		   Reference ref = (Reference)expression;
-		   if (ref.isPositional() && ref.getExpression() == null) {
-			   return getContext(ref).getVariableContext().getGlobalValue(ref.getContextSymbol());
-		   }
-		   return internalEvaluate(ref.getExpression(), tuple);
-	   } else if(expression instanceof Criteria) {
-	       return evaluate((Criteria) expression, tuple);
-	   } else if(expression instanceof ScalarSubquery) {
-	       return evaluate((ScalarSubquery) expression, tuple);
-	   } else if (expression instanceof Criteria) {
-		   return evaluate((Criteria)expression, tuple);
-	   } else if (expression instanceof TextLine){
-		   return evaluateTextLine(tuple, (TextLine)expression);
-	   } else if (expression instanceof XMLElement){
-		   return evaluateXMLElement(tuple, (XMLElement)expression);
-	   } else if (expression instanceof XMLForest){
-		   return evaluateXMLForest(tuple, (XMLForest)expression);
-	   } else if (expression instanceof XMLSerialize){
-		   return evaluateXMLSerialize(tuple, (XMLSerialize)expression);
-	   } else if (expression instanceof XMLQuery) {
-		   return evaluateXMLQuery(tuple, (XMLQuery)expression);
-	   } else if (expression instanceof QueryString) {
-		   return evaluateQueryString(tuple, (QueryString)expression);
-	   } else if (expression instanceof XMLParse){
-		   return evaluateXMLParse(tuple, (XMLParse)expression);
-	   } else {
-	       throw new TeiidComponentException("ERR.015.006.0016", QueryPlugin.Util.getString("ERR.015.006.0016", expression.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
-	   }
-	}
-
-	private Object evaluateXMLParse(List<?> tuple, final XMLParse xp) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-		Object value = internalEvaluate(xp.getExpression(), tuple);
-		if (value == null) {
-			return null;
-		}
-		XMLType.Type type = Type.DOCUMENT;
-		SQLXMLImpl result = null;
-		try {
-			if (value instanceof String) {
-				String string = (String)value;
-				result = new SQLXMLImpl(string);
-				result.setEncoding(Streamable.ENCODING);
-				if (!xp.isWellFormed()) {
-					Reader r = new StringReader(string);
-					type = validate(xp, r);
-				}
-			} else {
-				InputStreamFactory isf = null;
-				Streamable<?> s = (Streamable<?>)value;
-				isf = getInputStreamFactory(s);
-				result = new SQLXMLImpl(isf);
-				if (!xp.isWellFormed()) {
-					Reader r = result.getCharacterStream();
-					type = validate(xp, r);
-				}
-			}
-		} catch (TransformationException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		} catch (SQLException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		}
-		if (!xp.isDocument()) {
-			type = Type.CONTENT;
-		}
-		XMLType xml = new XMLType(result);
-		xml.setType(type);
-		return xml;
-	}
-
-	//TODO: determine when wrapping is not needed
-	public static InputStreamFactory getInputStreamFactory(Streamable<?> s) {
-		if (s instanceof ClobType) {
-			return new InputStreamFactory.ClobInputStreamFactory((Clob)s.getReference());
-		} else if (s instanceof BlobType){
-			return new InputStreamFactory.BlobInputStreamFactory((Blob)s.getReference());
-		}
-		return new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML)s.getReference());
-	}
-
-	private Type validate(final XMLParse xp, Reader r)
-			throws TransformationException {
-		if (!xp.isDocument()) {
-			LinkedList<Reader> readers = new LinkedList<Reader>();
-			readers.add(new StringReader("<r>")); //$NON-NLS-1$
-			readers.add(r);
-			readers.add(new StringReader("</r>")); //$NON-NLS-1$
-			r = new SequenceReader(readers);
-		}
-		return StringToSQLXMLTransform.isXml(r);
-	}
-
-	//TODO: exception if length is too long?
-	private Object evaluateQueryString(List<?> tuple, QueryString queryString)
-			throws ExpressionEvaluationException, BlockedException,
-			TeiidComponentException {
-		Evaluator.NameValuePair<Object>[] pairs = getNameValuePairs(tuple, queryString.getArgs(), false);
-		String path = (String)internalEvaluate(queryString.getPath(), tuple);
-		if (path == null) {
-			path = ""; //$NON-NLS-1$
-		} 
-		boolean appendedAny = false;
-		StringBuilder result = new StringBuilder();
-		for (Evaluator.NameValuePair<Object> nameValuePair : pairs) {
-			if (nameValuePair.value == null) {
-				continue;
-			}
-			if (appendedAny) {
-				result.append('&');
-			}
-			appendedAny = true;
-			result.append(Util.httpURLEncode(nameValuePair.name)).append('=').append(Util.httpURLEncode((String)nameValuePair.value));
-		}
-		if (!appendedAny) {
-			return path;
-		}
-		result.insert(0, '?');
-		result.insert(0, path);
-		return result.toString();
-	}
-
-	private Object evaluateXMLQuery(List<?> tuple, XMLQuery xmlQuery)
-			throws BlockedException, TeiidComponentException,
-			FunctionExecutionException {
-		boolean emptyOnEmpty = true;
-		if (xmlQuery.getEmptyOnEmpty() != null)  {
-			emptyOnEmpty = xmlQuery.getEmptyOnEmpty();
-		}   
-		Result result = null;
-		try {
-			result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple);
-			return xmlQuery.getXQueryExpression().createXMLType(result.iter, this.context.getBufferManager(), emptyOnEmpty);
-		} catch (TeiidProcessingException e) {
-			throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
-		} catch (XPathException e) {
-			throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
-		} finally {
-			if (result != null) {
-				result.close();
-			}
-		}
-	}
-	
-	private Object evaluateXMLSerialize(List<?> tuple, XMLSerialize xs)
-			throws ExpressionEvaluationException, BlockedException,
-			TeiidComponentException, FunctionExecutionException {
-		XMLType value = (XMLType) internalEvaluate(xs.getExpression(), tuple);
-		if (value == null) {
-			return null;
-		}
-		try {
-			if (xs.isDocument() == null || !xs.isDocument()) {
-				return serialize(xs, value);
-			}
-			if (value.getType() == Type.UNKNOWN) {
-				Type type = StringToSQLXMLTransform.isXml(value.getCharacterStream());
-				value.setType(type);
-			}
-			if (value.getType() == Type.DOCUMENT || value.getType() == Type.ELEMENT) {
-				return serialize(xs, value);
-			}
-		} catch (SQLException e) {
-			throw new FunctionExecutionException(e, e.getMessage());
-		} catch (TransformationException e) {
-			throw new FunctionExecutionException(e, e.getMessage());
-		}
-		throw new FunctionExecutionException(QueryPlugin.Util.getString("Evaluator.xmlserialize")); //$NON-NLS-1$
-	}
-
-	private Object serialize(XMLSerialize xs, XMLType value) throws TransformationException {
-		if (xs.getType() == DataTypeManager.DefaultDataClasses.STRING) {
-			return DataTypeManager.transformValue(value, xs.getType());
-		}
-		InputStreamFactory isf = getInputStreamFactory(value);
-		return new ClobType(new ClobImpl(isf, -1));
-	}
-	
-	private Object evaluateTextLine(List<?> tuple, TextLine function) throws ExpressionEvaluationException, BlockedException, TeiidComponentException, FunctionExecutionException {
-		List<DerivedColumn> args = function.getExpressions();
-		Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
-		
-		try {
-			return TextLine.evaluate(Arrays.asList(nameValuePairs), new TextLine.ValueExtractor<NameValuePair<Object>>() {
-				public Object getValue(NameValuePair<Object> t) {
-					return t.value;
-				}
-			}, function.getDelimiter(), function.getQuote());
-		} catch (TransformationException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		}
-	}
-
-	private Object evaluateXMLForest(List<?> tuple, XMLForest function)
-			throws ExpressionEvaluationException, BlockedException,
-			TeiidComponentException, FunctionExecutionException {
-		List<DerivedColumn> args = function.getArgs();
-		Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true); 
-			
-		try {
-			return XMLSystemFunctions.xmlForest(context, namespaces(function.getNamespaces()), nameValuePairs);
-		} catch (TeiidProcessingException e) {
-			throw new FunctionExecutionException(e, e.getMessage());
-		}
-	}
-
-	private Object evaluateXMLElement(List<?> tuple, XMLElement function)
-			throws ExpressionEvaluationException, BlockedException,
-			TeiidComponentException, FunctionExecutionException {
-		List<Expression> content = function.getContent();
-		   List<Object> values = new ArrayList<Object>(content.size());
-		   for (Expression exp : content) {
-			   values.add(internalEvaluate(exp, tuple));
-		   }
-		   try {
-			   Evaluator.NameValuePair<Object>[] attributes = null;
-			   if (function.getAttributes() != null) {
-				   attributes = getNameValuePairs(tuple, function.getAttributes().getArgs(), true);
-			   }
-			   return XMLSystemFunctions.xmlElement(context, function.getName(), namespaces(function.getNamespaces()), attributes, values);
-		   } catch (TeiidProcessingException e) {
-			   throw new FunctionExecutionException(e, e.getMessage());
-		   }
-	}
-	
-	public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple) 
-	throws BlockedException, TeiidComponentException, TeiidProcessingException {
-		HashMap<String, Object> parameters = new HashMap<String, Object>();
-		Object contextItem = null;
-		for (DerivedColumn passing : cols) {
-			Object value = this.evaluate(passing.getExpression(), tuple);
-			if (passing.getAlias() == null) {
-				contextItem = value;
-			} else {
-				parameters.put(passing.getAlias(), value);
-			}
-		}
-		return xquery.evaluateXQuery(contextItem, parameters);
-	}
-
-	private Evaluator.NameValuePair<Object>[] getNameValuePairs(List<?> tuple, List<DerivedColumn> args, boolean xmlNames)
-			throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-		Evaluator.NameValuePair<Object>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
-		for (int i = 0; i < args.size(); i++) {
-			DerivedColumn symbol = args.get(i);
-			String name = symbol.getAlias();
-			Expression ex = symbol.getExpression();
-			if (name == null && ex instanceof ElementSymbol) {
-				name = ((ElementSymbol)ex).getShortName();
-				if (xmlNames) {
-					name = XMLSystemFunctions.escapeName(name, true);
-				}
-			}
-			nameValuePairs[i] = new Evaluator.NameValuePair<Object>(name, internalEvaluate(ex, tuple));
-		}
-		return nameValuePairs;
-	}
-	
-	private Evaluator.NameValuePair<String>[] namespaces(XMLNamespaces namespaces) {
-		if (namespaces == null) {
-			return null;
-		}
-	    List<NamespaceItem> args = namespaces.getNamespaceItems();
-	    Evaluator.NameValuePair<String>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
-	    for(int i=0; i < args.size(); i++) {
-	    	NamespaceItem item = args.get(i);
-	    	nameValuePairs[i] = new Evaluator.NameValuePair<String>(item.getPrefix(), item.getUri());
-	    } 
-	    return nameValuePairs;
-	}
-	
-	private Object evaluate(CaseExpression expr, List<?> tuple)
-	throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-	    Object exprVal = internalEvaluate(expr.getExpression(), tuple);
-	    for (int i = 0; i < expr.getWhenCount(); i++) {
-	        if (EquivalenceUtil.areEqual(exprVal, internalEvaluate(expr.getWhenExpression(i), tuple))) {
-	            return internalEvaluate(expr.getThenExpression(i), tuple);
-	        }
-	    }
-	    if (expr.getElseExpression() != null) {
-	        return internalEvaluate(expr.getElseExpression(), tuple);
-	    }
-	    return null;
-	}
-	
-	private Object evaluate(SearchedCaseExpression expr, List<?> tuple)
-	throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-	    for (int i = 0; i < expr.getWhenCount(); i++) {
-	        try {
-	            if (evaluate(expr.getWhenCriteria(i), tuple)) {
-	                return internalEvaluate(expr.getThenExpression(i), tuple);
-	            }
-	        } catch (ExpressionEvaluationException e) {
-	            throw new ExpressionEvaluationException(e, "ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", "CASE", expr.getWhenCriteria(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	        }
-	    }
-	    if (expr.getElseExpression() != null) {
-	        return internalEvaluate(expr.getElseExpression(), tuple);
-	    }
-	    return null;
-	}
-	
-	private Object evaluate(Function function, List<?> tuple)
-		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-	
-	    // Get function based on resolved function info
-	    FunctionDescriptor fd = function.getFunctionDescriptor();
-	    
-		// Evaluate args
-		Expression[] args = function.getArgs();
-	    Object[] values = null;
-	    int start = 0;
-	    
-	    if (fd.requiresContext()) {
-			values = new Object[args.length+1];
-	        values[0] = context;
-	        start = 1;
-	    }
-	    else {
-	        values = new Object[args.length];
-	    }
-	    
-	    for(int i=0; i < args.length; i++) {
-	        values[i+start] = internalEvaluate(args[i], tuple);
-	    }            
-	    
-	    // Check for function we can't evaluate
-	    if(fd.getPushdown() == PushDown.MUST_PUSHDOWN) {
-	        throw new TeiidComponentException(QueryPlugin.Util.getString("ExpressionEvaluator.Must_push", fd.getName())); //$NON-NLS-1$
-	    }
-	
-	    // Check for special lookup function
-	    if(fd.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)) {
-	        if(dataMgr == null) {
-	            throw new ComponentNotFoundException("ERR.015.006.0055", QueryPlugin.Util.getString("ERR.015.006.0055")); //$NON-NLS-1$ //$NON-NLS-2$
-	        }
-	
-	        String codeTableName = (String) values[0];
-	        String returnElementName = (String) values[1];
-	        String keyElementName = (String) values[2];
-	        
-	        try {
-				return dataMgr.lookupCodeValue(context, codeTableName, returnElementName, keyElementName, values[3]);
-			} catch (TeiidProcessingException e) {
-				throw new ExpressionEvaluationException(e, e.getMessage());
-			}
-	    }
-	    
-		// Execute function
-		Object result = fd.invokeFunction(values);
-		return result;        
-	}
-	
-	private Object evaluate(ScalarSubquery scalarSubquery, List<?> tuple)
-	    throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-		
-	    Object result = null;
-        ValueIterator valueIter;
-		try {
-			valueIter = evaluateSubquery(scalarSubquery, tuple);
-		} catch (TeiidProcessingException e) {
-			throw new ExpressionEvaluationException(e, e.getMessage());
-		}
-	    if(valueIter.hasNext()) {
-	        result = valueIter.next();
-	        if(valueIter.hasNext()) {
-	            // The subquery should be scalar, but has produced
-	            // more than one result value - this is an exception case
-	            throw new ExpressionEvaluationException("ERR.015.006.0058", QueryPlugin.Util.getString("ERR.015.006.0058", scalarSubquery.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
-	        }
-	    }
-	    return result;
-	}
-	
-	protected ValueIterator evaluateSubquery(SubqueryContainer container, List<?> tuple) 
-	throws TeiidProcessingException, BlockedException, TeiidComponentException {
-		throw new UnsupportedOperationException("Subquery evaluation not possible with a base Evaluator"); //$NON-NLS-1$
-	}
-
-	private CommandContext getContext(LanguageObject expression) throws TeiidComponentException {
-		if (context == null) {
-			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-		return context;
-	}   
-	    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java (from rev 2775, trunk/engine/src/main/java/org/teiid/query/eval/Evaluator.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/eval/Evaluator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1030 @@
+/*
+ * 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.eval;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+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.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import net.sf.saxon.trans.XPathException;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.core.ComponentNotFoundException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+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.Sequencable;
+import org.teiid.core.types.Streamable;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.types.XMLType.Type;
+import org.teiid.core.types.basic.StringToSQLXMLTransform;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionDescriptor;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.CollectionValueIterator;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.ExpressionCriteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.CaseExpression;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ContextReference;
+import org.teiid.query.sql.symbol.DerivedColumn;
+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.QueryString;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+import org.teiid.query.sql.symbol.XMLParse;
+import org.teiid.query.sql.symbol.XMLQuery;
+import org.teiid.query.sql.symbol.XMLSerialize;
+import org.teiid.query.sql.symbol.XMLNamespaces.NamespaceItem;
+import org.teiid.query.sql.util.ValueIterator;
+import org.teiid.query.sql.util.ValueIteratorSource;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result;
+import org.teiid.translator.WSConnection.Util;
+
+public class Evaluator {
+
+    private final class SequenceReader extends Reader {
+		private LinkedList<Reader> readers;
+		private Reader current = null;
+		
+		public SequenceReader(LinkedList<Reader> readers) {
+			this.readers = readers;
+		}
+
+		@Override
+		public void close() throws IOException {
+			for (Reader reader : readers) {
+				try {
+					reader.close();
+				} catch (IOException e) {
+					
+				}
+			}
+		}
+
+		@Override
+		public int read(char[] cbuf, int off, int len)
+				throws IOException {
+			if (current == null && !readers.isEmpty()) {
+				current = readers.removeFirst();
+			}
+			if (current == null) {
+				return -1;
+			}
+			int read = current.read(cbuf, off, len);
+			if (read == -1) {
+				current.close();
+				current = null;
+				read = 0;
+			} 
+			if (read < len) {
+				int nextRead = read(cbuf, off + read, len - read);
+				if (nextRead > 0) {
+					read += nextRead;
+				}
+			}
+			return read;
+		}
+	}
+
+	public static class NameValuePair<T> {
+		public String name;
+		public T value;
+		
+		public NameValuePair(String name, T value) {
+			this.name = name;
+			this.value = value;
+		}
+	}
+
+	private final static char[] REGEX_RESERVED = new char[] {'$', '(', ')', '*', '.', '?', '[', '\\', ']', '^', '{', '|', '}'}; //in sorted order
+    private final static MatchCriteria.PatternTranslator LIKE_TO_REGEX = new MatchCriteria.PatternTranslator(".*", ".", REGEX_RESERVED, '\\');  //$NON-NLS-1$ //$NON-NLS-2$
+
+    private Map elements;
+    
+    protected ProcessorDataManager dataMgr;
+    protected CommandContext context;
+    
+    public static boolean evaluate(Criteria criteria) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+    	return new Evaluator(Collections.emptyMap(), null, null).evaluate(criteria, Collections.emptyList());
+    }
+    
+    public static Object evaluate(Expression expression) throws ExpressionEvaluationException, BlockedException, TeiidComponentException  {
+    	return new Evaluator(Collections.emptyMap(), null, null).evaluate(expression, Collections.emptyList());
+    }
+    
+    public Evaluator(Map elements, ProcessorDataManager dataMgr, CommandContext context) {
+		this.context = context;
+		this.dataMgr = dataMgr;
+		this.elements = elements;
+	}
+    
+    public void initialize(CommandContext context, ProcessorDataManager dataMgr) {
+		this.context = context;
+		this.dataMgr = dataMgr;
+	}
+
+	public boolean evaluate(Criteria criteria, List<?> tuple)
+        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+        return Boolean.TRUE.equals(evaluateTVL(criteria, tuple));
+    }
+
+    public Boolean evaluateTVL(Criteria criteria, List<?> tuple)
+        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+    	
+		if(criteria instanceof CompoundCriteria) {
+			return evaluate((CompoundCriteria)criteria, tuple);
+		} else if(criteria instanceof NotCriteria) {
+			return evaluate((NotCriteria)criteria, tuple);
+		} else if(criteria instanceof CompareCriteria) {
+			return evaluate((CompareCriteria)criteria, tuple);
+		} else if(criteria instanceof MatchCriteria) {
+			return evaluate((MatchCriteria)criteria, tuple);
+		} else if(criteria instanceof AbstractSetCriteria) {
+			return evaluate((AbstractSetCriteria)criteria, tuple);
+		} else if(criteria instanceof IsNullCriteria) {
+			return Boolean.valueOf(evaluate((IsNullCriteria)criteria, tuple));
+        } else if(criteria instanceof SubqueryCompareCriteria) {
+            return evaluate((SubqueryCompareCriteria)criteria, tuple);
+        } else if(criteria instanceof ExistsCriteria) {
+            return Boolean.valueOf(evaluate((ExistsCriteria)criteria, tuple));
+        } else if (criteria instanceof ExpressionCriteria) {
+        	return (Boolean)evaluate(((ExpressionCriteria)criteria).getExpression(), tuple);
+		} else {
+            throw new ExpressionEvaluationException("ERR.015.006.0010", QueryPlugin.Util.getString("ERR.015.006.0010", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+
+	public Boolean evaluate(CompoundCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+		List subCrits = criteria.getCriteria();
+		Iterator subCritIter = subCrits.iterator();
+
+		boolean and = criteria.getOperator() == CompoundCriteria.AND;
+        Boolean result = and?Boolean.TRUE:Boolean.FALSE;
+		while(subCritIter.hasNext()) {
+			Criteria subCrit = (Criteria) subCritIter.next();
+			Boolean value = evaluateTVL(subCrit, tuple);
+            if (value == null) {
+				result = null;
+			} else if (!value.booleanValue()) {
+				if (and) {
+					return Boolean.FALSE;
+				}
+            } else if (!and) {
+            	return Boolean.TRUE;
+            }
+		}
+		return result;
+	}
+
+	public Boolean evaluate(NotCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+		Criteria subCrit = criteria.getCriteria();
+		Boolean result = evaluateTVL(subCrit, tuple);
+        if (result == null) {
+            return null;
+        }
+        if (result.booleanValue()) {
+            return Boolean.FALSE;
+        }
+        return Boolean.TRUE;
+	}
+
+	public Boolean evaluate(CompareCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+		// Evaluate left expression
+		Object leftValue = null;
+		try {
+			leftValue = evaluate(criteria.getLeftExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[] {"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+
+		// Shortcut if null
+		if(leftValue == null) {
+			return null;
+		}
+
+		// Evaluate right expression
+		Object rightValue = null;
+		try {
+			rightValue = evaluate(criteria.getRightExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+
+		// Shortcut if null
+		if(rightValue == null) {
+			return null;
+		}
+
+		// Compare two non-null values using specified operator
+		return compare(criteria, leftValue, rightValue);
+	}
+
+	public static Boolean compare(CompareCriteria criteria, Object leftValue,
+			Object rightValue) throws ExpressionEvaluationException {
+		switch(criteria.getOperator()) {
+			case CompareCriteria.EQ:
+				return Boolean.valueOf(compareValues(leftValue, rightValue) == 0);
+			case CompareCriteria.NE:
+				return Boolean.valueOf(compareValues(leftValue, rightValue) != 0);
+			case CompareCriteria.LT:
+				return Boolean.valueOf((compareValues(leftValue, rightValue) < 0));
+			case CompareCriteria.LE:
+				return Boolean.valueOf((compareValues(leftValue, rightValue) <= 0));
+			case CompareCriteria.GT:
+				return Boolean.valueOf((compareValues(leftValue, rightValue) > 0));
+			case CompareCriteria.GE:
+				return Boolean.valueOf((compareValues(leftValue, rightValue) >= 0));
+			default:
+                throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+
+    private static final int compareValues(Object leftValue, Object rightValue) {
+    	assert leftValue instanceof Comparable<?>;
+    	assert rightValue instanceof Comparable<?>;
+    	if (leftValue == rightValue) {
+    		return 0;
+    	}
+        return ((Comparable<Object>)leftValue).compareTo(rightValue);
+    }
+
+	public Boolean evaluate(MatchCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+        boolean result = false;
+		// Evaluate left expression
+        Object value = null;
+		try {
+			value = evaluate(criteria.getLeftExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"left", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+
+		// Shortcut if null
+		if(value == null) {
+            return null;
+        }
+        
+        CharSequence leftValue = null;
+        
+        if (value instanceof CharSequence) {
+            leftValue = (CharSequence)value;
+        } else {
+            try {
+                leftValue = ((Sequencable)value).getCharSequence();
+            } catch (SQLException err) {
+                throw new ExpressionEvaluationException(err, err.getMessage()); 
+            }
+        }
+
+		// Evaluate right expression
+		String rightValue = null;
+		try {
+			rightValue = (String) evaluate(criteria.getRightExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0011", QueryPlugin.Util.getString("ERR.015.006.0011", new Object[]{"right", criteria})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+
+		// Shortcut if null
+		if(rightValue == null) {
+            return null;
+        }
+        
+        result = match(rightValue, criteria.getEscapeChar(), leftValue);
+        
+        return Boolean.valueOf(result ^ criteria.isNegated());
+	}
+
+	private boolean match(String pattern, char escape, CharSequence search)
+		throws ExpressionEvaluationException {
+
+		StringBuffer rePattern = LIKE_TO_REGEX.translate(pattern, escape);
+		
+		// Insert leading and trailing characters to ensure match of full string
+		rePattern.insert(0, '^');
+		rePattern.append('$');
+
+		try {
+            Pattern patternRegex = Pattern.compile(rePattern.toString(), Pattern.DOTALL);
+            Matcher matcher = patternRegex.matcher(search);
+            return matcher.matches();
+		} catch(PatternSyntaxException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0014", QueryPlugin.Util.getString("ERR.015.006.0014", new Object[]{pattern, e.getMessage()})); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+
+	private Boolean evaluate(AbstractSetCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+		// Evaluate expression
+		Object leftValue = null;
+		try {
+			leftValue = evaluate(criteria.getExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+
+		// Shortcut if null
+		if(leftValue == null) {
+            return null;
+        }
+        Boolean result = Boolean.FALSE;
+
+        ValueIterator valueIter = null;
+        if (criteria instanceof SetCriteria) {
+        	SetCriteria set = (SetCriteria)criteria;
+        	if (set.isAllConstants()) {
+        		boolean exists = set.getValues().contains(new Constant(leftValue, criteria.getExpression().getType()));
+        		if (!exists) {
+        			if (set.getValues().contains(Constant.NULL_CONSTANT)) {
+        				return null;
+        			}
+        			return criteria.isNegated();
+        		}
+        		return !criteria.isNegated();
+        	}
+        	valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
+        } else if (criteria instanceof DependentSetCriteria){
+        	ContextReference ref = (ContextReference)criteria;
+    		ValueIteratorSource vis = (ValueIteratorSource)getContext(criteria).getVariableContext().getGlobalValue(ref.getContextSymbol());
+    		Set<Object> values;
+    		try {
+    			values = vis.getCachedSet(ref.getValueExpression());
+    		} catch (TeiidProcessingException e) {
+    			throw new ExpressionEvaluationException(e, e.getMessage());
+    		}
+        	if (values != null) {
+        		return values.contains(leftValue);
+        	}
+        	//there are too many values to justify a linear search or holding
+        	//them in memory
+        	return true;
+        } else if (criteria instanceof SubquerySetCriteria) {
+        	try {
+				valueIter = evaluateSubquery((SubquerySetCriteria)criteria, tuple);
+			} catch (TeiidProcessingException e) {
+				throw new ExpressionEvaluationException(e, e.getMessage());
+			}
+        } else {
+        	throw new AssertionError("unknown set criteria type"); //$NON-NLS-1$
+        }
+        while(valueIter.hasNext()) {
+            Object possibleValue = valueIter.next();
+            Object value = null;
+            if(possibleValue instanceof Expression) {
+    			try {
+    				value = evaluate((Expression) possibleValue, tuple);
+    			} catch(ExpressionEvaluationException e) {
+                    throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", possibleValue)); //$NON-NLS-1$ //$NON-NLS-2$
+    			}
+            } else {
+                value = possibleValue;
+            }
+
+			if(value != null) {
+				if(compareValues(leftValue, value) == 0) {
+					return Boolean.valueOf(!criteria.isNegated());
+				} // else try next value
+			} else {
+			    result = null;
+            }
+		}
+        
+        if (result == null) {
+            return null;
+        }
+        
+        return Boolean.valueOf(criteria.isNegated());
+	}
+
+	public boolean evaluate(IsNullCriteria criteria, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+		// Evaluate expression
+		Object value = null;
+		try {
+			value = evaluate(criteria.getExpression(), tuple);
+		} catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+
+		return (value == null ^ criteria.isNegated());
+	}
+
+    private Boolean evaluate(SubqueryCompareCriteria criteria, List<?> tuple)
+        throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+
+        // Evaluate expression
+        Object leftValue = null;
+        try {
+            leftValue = evaluate(criteria.getLeftExpression(), tuple);
+        } catch(ExpressionEvaluationException e) {
+            throw new ExpressionEvaluationException(e, "ERR.015.006.0015", QueryPlugin.Util.getString("ERR.015.006.0015", criteria)); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+
+        // Shortcut if null
+        if(leftValue == null) {
+            return null;
+        }
+
+        // Need to be careful to initialize this variable carefully for the case
+        // where valueIterator has no values, and the block below is not entered.
+        // If there are no rows, and ALL is the predicate quantifier, the result
+        // should be true.  If SOME is the predicate quantifier, or no quantifier
+        // is used, the result should be false.
+        Boolean result = Boolean.FALSE;
+        if (criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ALL){
+            result = Boolean.TRUE;
+        }
+
+        ValueIterator valueIter;
+		try {
+			valueIter = evaluateSubquery(criteria, tuple);
+		} catch (TeiidProcessingException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		}
+        while(valueIter.hasNext()) {
+            Object value = valueIter.next();
+
+            if(value != null) {
+            	int compare = compareValues(leftValue, value);
+                // Compare two non-null values using specified operator
+                switch(criteria.getOperator()) {
+                    case SubqueryCompareCriteria.EQ:
+                        result = Boolean.valueOf(compare == 0);
+                        break;
+                    case SubqueryCompareCriteria.NE:
+                        result = Boolean.valueOf(compare != 0);
+                        break;
+                    case SubqueryCompareCriteria.LT:
+                        result = Boolean.valueOf(compare < 0);
+                        break;
+                    case SubqueryCompareCriteria.LE:
+                        result = Boolean.valueOf(compare <= 0);
+                        break;
+                    case SubqueryCompareCriteria.GT:
+                        result = Boolean.valueOf(compare > 0);
+                        break;
+                    case SubqueryCompareCriteria.GE:
+                        result = Boolean.valueOf(compare >= 0);
+                        break;
+                    default:
+                        throw new ExpressionEvaluationException("ERR.015.006.0012", QueryPlugin.Util.getString("ERR.015.006.0012", criteria.getOperator())); //$NON-NLS-1$ //$NON-NLS-2$
+                }
+
+                switch(criteria.getPredicateQuantifier()) {
+                    case SubqueryCompareCriteria.ALL:
+                        if (Boolean.FALSE.equals(result)){
+                            return Boolean.FALSE;
+                        }
+                        break;
+                    case SubqueryCompareCriteria.SOME:
+                        if (Boolean.TRUE.equals(result)){
+                            return Boolean.TRUE;
+                        }
+                        break;
+                    default:
+                        throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
+                }
+
+            } else { // value is null
+
+                switch(criteria.getPredicateQuantifier()) {
+                    case SubqueryCompareCriteria.ALL:
+                        // null counts as unknown; one unknown means the whole thing is unknown
+                        return null;
+                    case SubqueryCompareCriteria.SOME:
+                        result = null;
+                        break;
+                    default:
+                        throw new ExpressionEvaluationException("ERR.015.006.0057", QueryPlugin.Util.getString("ERR.015.006.0057", criteria.getPredicateQuantifier())); //$NON-NLS-1$ //$NON-NLS-2$
+                }
+            }
+
+
+        } //end value iteration
+
+        return result;
+    }
+
+    public boolean evaluate(ExistsCriteria criteria, List<?> tuple)
+        throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
+
+        ValueIterator valueIter;
+		try {
+			valueIter = evaluateSubquery(criteria, tuple);
+		} catch (TeiidProcessingException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		}
+        if(valueIter.hasNext()) {
+            return true;
+        }
+        return false;
+    }
+    
+	public Object evaluate(Expression expression, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+	
+	    try {
+			return internalEvaluate(expression, tuple);
+	    } catch (ExpressionEvaluationException e) {
+	        throw new ExpressionEvaluationException(e, QueryPlugin.Util.getString("ExpressionEvaluator.Eval_failed", new Object[] {expression, e.getMessage()})); //$NON-NLS-1$
+	    }
+	}
+	
+	private Object internalEvaluate(Expression expression, List<?> tuple)
+	   throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+	
+	   if(expression instanceof SingleElementSymbol) {
+		   if (elements != null) {
+		       // Try to evaluate by lookup in the elements map (may work for both ElementSymbol and ExpressionSymbol
+		       Integer index = (Integer) elements.get(expression);
+		       if(index != null) {
+		           return tuple.get(index.intValue());
+		       }
+		   }
+		   
+	       // Otherwise this should be an ExpressionSymbol and we just need to dive in and evaluate the expression itself
+	       if (expression instanceof ExpressionSymbol && !(expression instanceof AggregateSymbol)) {            
+	           ExpressionSymbol exprSyb = (ExpressionSymbol) expression;
+	           Expression expr = exprSyb.getExpression();
+	           return internalEvaluate(expr, tuple);
+	       } 
+	       
+	       return getContext(expression).getFromContext(expression);
+	   } 
+	   if(expression instanceof Constant) {
+	       return ((Constant) expression).getValue();
+	   } else if(expression instanceof Function) {
+	       return evaluate((Function) expression, tuple);
+	   } else if(expression instanceof CaseExpression) {
+	       return evaluate((CaseExpression) expression, tuple);
+	   } else if(expression instanceof SearchedCaseExpression) {
+	       return evaluate((SearchedCaseExpression) expression, tuple);
+	   } else if(expression instanceof Reference) {
+		   Reference ref = (Reference)expression;
+		   if (ref.isPositional() && ref.getExpression() == null) {
+			   return getContext(ref).getVariableContext().getGlobalValue(ref.getContextSymbol());
+		   }
+		   return internalEvaluate(ref.getExpression(), tuple);
+	   } else if(expression instanceof Criteria) {
+	       return evaluate((Criteria) expression, tuple);
+	   } else if(expression instanceof ScalarSubquery) {
+	       return evaluate((ScalarSubquery) expression, tuple);
+	   } else if (expression instanceof Criteria) {
+		   return evaluate((Criteria)expression, tuple);
+	   } else if (expression instanceof TextLine){
+		   return evaluateTextLine(tuple, (TextLine)expression);
+	   } else if (expression instanceof XMLElement){
+		   return evaluateXMLElement(tuple, (XMLElement)expression);
+	   } else if (expression instanceof XMLForest){
+		   return evaluateXMLForest(tuple, (XMLForest)expression);
+	   } else if (expression instanceof XMLSerialize){
+		   return evaluateXMLSerialize(tuple, (XMLSerialize)expression);
+	   } else if (expression instanceof XMLQuery) {
+		   return evaluateXMLQuery(tuple, (XMLQuery)expression);
+	   } else if (expression instanceof QueryString) {
+		   return evaluateQueryString(tuple, (QueryString)expression);
+	   } else if (expression instanceof XMLParse){
+		   return evaluateXMLParse(tuple, (XMLParse)expression);
+	   } else {
+	       throw new TeiidComponentException("ERR.015.006.0016", QueryPlugin.Util.getString("ERR.015.006.0016", expression.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
+	   }
+	}
+
+	private Object evaluateXMLParse(List<?> tuple, final XMLParse xp) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+		Object value = internalEvaluate(xp.getExpression(), tuple);
+		if (value == null) {
+			return null;
+		}
+		XMLType.Type type = Type.DOCUMENT;
+		SQLXMLImpl result = null;
+		try {
+			if (value instanceof String) {
+				String string = (String)value;
+				result = new SQLXMLImpl(string);
+				result.setEncoding(Streamable.ENCODING);
+				if (!xp.isWellFormed()) {
+					Reader r = new StringReader(string);
+					type = validate(xp, r);
+				}
+			} else {
+				InputStreamFactory isf = null;
+				Streamable<?> s = (Streamable<?>)value;
+				isf = getInputStreamFactory(s);
+				result = new SQLXMLImpl(isf);
+				if (!xp.isWellFormed()) {
+					Reader r = result.getCharacterStream();
+					type = validate(xp, r);
+				}
+			}
+		} catch (TransformationException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		} catch (SQLException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		}
+		if (!xp.isDocument()) {
+			type = Type.CONTENT;
+		}
+		XMLType xml = new XMLType(result);
+		xml.setType(type);
+		return xml;
+	}
+
+	//TODO: determine when wrapping is not needed
+	public static InputStreamFactory getInputStreamFactory(Streamable<?> s) {
+		if (s instanceof ClobType) {
+			return new InputStreamFactory.ClobInputStreamFactory((Clob)s.getReference());
+		} else if (s instanceof BlobType){
+			return new InputStreamFactory.BlobInputStreamFactory((Blob)s.getReference());
+		}
+		return new InputStreamFactory.SQLXMLInputStreamFactory((SQLXML)s.getReference());
+	}
+
+	private Type validate(final XMLParse xp, Reader r)
+			throws TransformationException {
+		if (!xp.isDocument()) {
+			LinkedList<Reader> readers = new LinkedList<Reader>();
+			readers.add(new StringReader("<r>")); //$NON-NLS-1$
+			readers.add(r);
+			readers.add(new StringReader("</r>")); //$NON-NLS-1$
+			r = new SequenceReader(readers);
+		}
+		return StringToSQLXMLTransform.isXml(r);
+	}
+
+	//TODO: exception if length is too long?
+	private Object evaluateQueryString(List<?> tuple, QueryString queryString)
+			throws ExpressionEvaluationException, BlockedException,
+			TeiidComponentException {
+		Evaluator.NameValuePair<Object>[] pairs = getNameValuePairs(tuple, queryString.getArgs(), false);
+		String path = (String)internalEvaluate(queryString.getPath(), tuple);
+		if (path == null) {
+			path = ""; //$NON-NLS-1$
+		} 
+		boolean appendedAny = false;
+		StringBuilder result = new StringBuilder();
+		for (Evaluator.NameValuePair<Object> nameValuePair : pairs) {
+			if (nameValuePair.value == null) {
+				continue;
+			}
+			if (appendedAny) {
+				result.append('&');
+			}
+			appendedAny = true;
+			result.append(Util.httpURLEncode(nameValuePair.name)).append('=').append(Util.httpURLEncode((String)nameValuePair.value));
+		}
+		if (!appendedAny) {
+			return path;
+		}
+		result.insert(0, '?');
+		result.insert(0, path);
+		return result.toString();
+	}
+
+	private Object evaluateXMLQuery(List<?> tuple, XMLQuery xmlQuery)
+			throws BlockedException, TeiidComponentException,
+			FunctionExecutionException {
+		boolean emptyOnEmpty = true;
+		if (xmlQuery.getEmptyOnEmpty() != null)  {
+			emptyOnEmpty = xmlQuery.getEmptyOnEmpty();
+		}   
+		Result result = null;
+		try {
+			result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple);
+			return xmlQuery.getXQueryExpression().createXMLType(result.iter, this.context.getBufferManager(), emptyOnEmpty);
+		} catch (TeiidProcessingException e) {
+			throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
+		} catch (XPathException e) {
+			throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
+		} finally {
+			if (result != null) {
+				result.close();
+			}
+		}
+	}
+	
+	private Object evaluateXMLSerialize(List<?> tuple, XMLSerialize xs)
+			throws ExpressionEvaluationException, BlockedException,
+			TeiidComponentException, FunctionExecutionException {
+		XMLType value = (XMLType) internalEvaluate(xs.getExpression(), tuple);
+		if (value == null) {
+			return null;
+		}
+		try {
+			if (xs.isDocument() == null || !xs.isDocument()) {
+				return serialize(xs, value);
+			}
+			if (value.getType() == Type.UNKNOWN) {
+				Type type = StringToSQLXMLTransform.isXml(value.getCharacterStream());
+				value.setType(type);
+			}
+			if (value.getType() == Type.DOCUMENT || value.getType() == Type.ELEMENT) {
+				return serialize(xs, value);
+			}
+		} catch (SQLException e) {
+			throw new FunctionExecutionException(e, e.getMessage());
+		} catch (TransformationException e) {
+			throw new FunctionExecutionException(e, e.getMessage());
+		}
+		throw new FunctionExecutionException(QueryPlugin.Util.getString("Evaluator.xmlserialize")); //$NON-NLS-1$
+	}
+
+	private Object serialize(XMLSerialize xs, XMLType value) throws TransformationException {
+		if (xs.getType() == DataTypeManager.DefaultDataClasses.STRING) {
+			return DataTypeManager.transformValue(value, xs.getType());
+		}
+		InputStreamFactory isf = getInputStreamFactory(value);
+		return new ClobType(new ClobImpl(isf, -1));
+	}
+	
+	private Object evaluateTextLine(List<?> tuple, TextLine function) throws ExpressionEvaluationException, BlockedException, TeiidComponentException, FunctionExecutionException {
+		List<DerivedColumn> args = function.getExpressions();
+		Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true);
+		
+		try {
+			return TextLine.evaluate(Arrays.asList(nameValuePairs), new TextLine.ValueExtractor<NameValuePair<Object>>() {
+				public Object getValue(NameValuePair<Object> t) {
+					return t.value;
+				}
+			}, function.getDelimiter(), function.getQuote());
+		} catch (TransformationException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		}
+	}
+
+	private Object evaluateXMLForest(List<?> tuple, XMLForest function)
+			throws ExpressionEvaluationException, BlockedException,
+			TeiidComponentException, FunctionExecutionException {
+		List<DerivedColumn> args = function.getArgs();
+		Evaluator.NameValuePair<Object>[] nameValuePairs = getNameValuePairs(tuple, args, true); 
+			
+		try {
+			return XMLSystemFunctions.xmlForest(context, namespaces(function.getNamespaces()), nameValuePairs);
+		} catch (TeiidProcessingException e) {
+			throw new FunctionExecutionException(e, e.getMessage());
+		}
+	}
+
+	private Object evaluateXMLElement(List<?> tuple, XMLElement function)
+			throws ExpressionEvaluationException, BlockedException,
+			TeiidComponentException, FunctionExecutionException {
+		List<Expression> content = function.getContent();
+		   List<Object> values = new ArrayList<Object>(content.size());
+		   for (Expression exp : content) {
+			   values.add(internalEvaluate(exp, tuple));
+		   }
+		   try {
+			   Evaluator.NameValuePair<Object>[] attributes = null;
+			   if (function.getAttributes() != null) {
+				   attributes = getNameValuePairs(tuple, function.getAttributes().getArgs(), true);
+			   }
+			   return XMLSystemFunctions.xmlElement(context, function.getName(), namespaces(function.getNamespaces()), attributes, values);
+		   } catch (TeiidProcessingException e) {
+			   throw new FunctionExecutionException(e, e.getMessage());
+		   }
+	}
+	
+	public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple) 
+	throws BlockedException, TeiidComponentException, TeiidProcessingException {
+		HashMap<String, Object> parameters = new HashMap<String, Object>();
+		Object contextItem = null;
+		for (DerivedColumn passing : cols) {
+			Object value = this.evaluate(passing.getExpression(), tuple);
+			if (passing.getAlias() == null) {
+				contextItem = value;
+			} else {
+				parameters.put(passing.getAlias(), value);
+			}
+		}
+		return xquery.evaluateXQuery(contextItem, parameters);
+	}
+
+	private Evaluator.NameValuePair<Object>[] getNameValuePairs(List<?> tuple, List<DerivedColumn> args, boolean xmlNames)
+			throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+		Evaluator.NameValuePair<Object>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
+		for (int i = 0; i < args.size(); i++) {
+			DerivedColumn symbol = args.get(i);
+			String name = symbol.getAlias();
+			Expression ex = symbol.getExpression();
+			if (name == null && ex instanceof ElementSymbol) {
+				name = ((ElementSymbol)ex).getShortName();
+				if (xmlNames) {
+					name = XMLSystemFunctions.escapeName(name, true);
+				}
+			}
+			nameValuePairs[i] = new Evaluator.NameValuePair<Object>(name, internalEvaluate(ex, tuple));
+		}
+		return nameValuePairs;
+	}
+	
+	private Evaluator.NameValuePair<String>[] namespaces(XMLNamespaces namespaces) {
+		if (namespaces == null) {
+			return null;
+		}
+	    List<NamespaceItem> args = namespaces.getNamespaceItems();
+	    Evaluator.NameValuePair<String>[] nameValuePairs = new Evaluator.NameValuePair[args.size()];
+	    for(int i=0; i < args.size(); i++) {
+	    	NamespaceItem item = args.get(i);
+	    	nameValuePairs[i] = new Evaluator.NameValuePair<String>(item.getPrefix(), item.getUri());
+	    } 
+	    return nameValuePairs;
+	}
+	
+	private Object evaluate(CaseExpression expr, List<?> tuple)
+	throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+	    Object exprVal = internalEvaluate(expr.getExpression(), tuple);
+	    for (int i = 0; i < expr.getWhenCount(); i++) {
+	        if (EquivalenceUtil.areEqual(exprVal, internalEvaluate(expr.getWhenExpression(i), tuple))) {
+	            return internalEvaluate(expr.getThenExpression(i), tuple);
+	        }
+	    }
+	    if (expr.getElseExpression() != null) {
+	        return internalEvaluate(expr.getElseExpression(), tuple);
+	    }
+	    return null;
+	}
+	
+	private Object evaluate(SearchedCaseExpression expr, List<?> tuple)
+	throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+	    for (int i = 0; i < expr.getWhenCount(); i++) {
+	        try {
+	            if (evaluate(expr.getWhenCriteria(i), tuple)) {
+	                return internalEvaluate(expr.getThenExpression(i), tuple);
+	            }
+	        } catch (ExpressionEvaluationException e) {
+	            throw new ExpressionEvaluationException(e, "ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", "CASE", expr.getWhenCriteria(i))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	        }
+	    }
+	    if (expr.getElseExpression() != null) {
+	        return internalEvaluate(expr.getElseExpression(), tuple);
+	    }
+	    return null;
+	}
+	
+	private Object evaluate(Function function, List<?> tuple)
+		throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+	
+	    // Get function based on resolved function info
+	    FunctionDescriptor fd = function.getFunctionDescriptor();
+	    
+		// Evaluate args
+		Expression[] args = function.getArgs();
+	    Object[] values = null;
+	    int start = 0;
+	    
+	    if (fd.requiresContext()) {
+			values = new Object[args.length+1];
+	        values[0] = context;
+	        start = 1;
+	    }
+	    else {
+	        values = new Object[args.length];
+	    }
+	    
+	    for(int i=0; i < args.length; i++) {
+	        values[i+start] = internalEvaluate(args[i], tuple);
+	    }            
+	    
+	    // Check for function we can't evaluate
+	    if(fd.getPushdown() == PushDown.MUST_PUSHDOWN) {
+	        throw new TeiidComponentException(QueryPlugin.Util.getString("ExpressionEvaluator.Must_push", fd.getName())); //$NON-NLS-1$
+	    }
+	
+	    // Check for special lookup function
+	    if(fd.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)) {
+	        if(dataMgr == null) {
+	            throw new ComponentNotFoundException("ERR.015.006.0055", QueryPlugin.Util.getString("ERR.015.006.0055")); //$NON-NLS-1$ //$NON-NLS-2$
+	        }
+	
+	        String codeTableName = (String) values[0];
+	        String returnElementName = (String) values[1];
+	        String keyElementName = (String) values[2];
+	        
+	        try {
+				return dataMgr.lookupCodeValue(context, codeTableName, returnElementName, keyElementName, values[3]);
+			} catch (TeiidProcessingException e) {
+				throw new ExpressionEvaluationException(e, e.getMessage());
+			}
+	    }
+	    
+		// Execute function
+		Object result = fd.invokeFunction(values);
+		return result;        
+	}
+	
+	private Object evaluate(ScalarSubquery scalarSubquery, List<?> tuple)
+	    throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+		
+	    Object result = null;
+        ValueIterator valueIter;
+		try {
+			valueIter = evaluateSubquery(scalarSubquery, tuple);
+		} catch (TeiidProcessingException e) {
+			throw new ExpressionEvaluationException(e, e.getMessage());
+		}
+	    if(valueIter.hasNext()) {
+	        result = valueIter.next();
+	        if(valueIter.hasNext()) {
+	            // The subquery should be scalar, but has produced
+	            // more than one result value - this is an exception case
+	            throw new ExpressionEvaluationException("ERR.015.006.0058", QueryPlugin.Util.getString("ERR.015.006.0058", scalarSubquery.getCommand())); //$NON-NLS-1$ //$NON-NLS-2$
+	        }
+	    }
+	    return result;
+	}
+	
+	protected ValueIterator evaluateSubquery(SubqueryContainer container, List<?> tuple) 
+	throws TeiidProcessingException, BlockedException, TeiidComponentException {
+		throw new UnsupportedOperationException("Subquery evaluation not possible with a base Evaluator"); //$NON-NLS-1$
+	}
+
+	private CommandContext getContext(LanguageObject expression) throws TeiidComponentException {
+		if (context == null) {
+			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+		return context;
+	}   
+	    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,293 +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.function;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.TransformationException;
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.HashCodeUtil;
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * The FunctionDescriptor describes a particular function instance enough
- * that the function library can retrieve a function instance based on the 
- * descriptor.
- */
-public class FunctionDescriptor implements Serializable, Cloneable {
-	private static final long serialVersionUID = 5374103983118037242L;
-
-	private static final boolean ALLOW_NAN_INFINITY = PropertiesUtils.getBooleanProperty(System.getProperties(), "org.teiid.allowNanInfinity", false); //$NON-NLS-1$
-	
-	private String name;
-    private PushDown pushdown = PushDown.CAN_PUSHDOWN;
-	private Class[] types;
-	private Class returnType;	
-	private int hash;
-    private boolean requiresContext;
-    private boolean nullDependent;
-    private Determinism deterministic = Determinism.DETERMINISTIC;
-    
-    // This is transient as it would be useless to invoke this method in 
-    // a different VM.  This function descriptor can be used to look up 
-    // the real VM descriptor for execution.
-    private transient Method invocationMethod;
-	
-    FunctionDescriptor() {
-    }
-    
-    /** 
-     * Construct a function descriptor with all the info
-     * @param name Name of function
-     * @param types Types of the arguments
-     * @param returnType Type of the return 
-     * @param invocationMethod Reflection method used to invoke the function
-     * @param requiresContext during execution requires command context to be pushed into method as first argument
-     */
-	FunctionDescriptor(String name, PushDown pushdown, Class[] types, Class returnType, Method invocationMethod, boolean requiresContext, boolean nullDependent, Determinism deterministic) {
-		Assertion.isNotNull(name);
-		Assertion.isNotNull(types);
-		Assertion.isNotNull(returnType);
-		
-		this.name = name;
-        this.pushdown = pushdown;
-		this.types = types;
-		this.returnType = returnType;
-        this.invocationMethod = invocationMethod;
-        this.requiresContext = requiresContext;
-        this.nullDependent = nullDependent;
-        this.deterministic = deterministic;
-		
-		// Compute hash code
-		hash = HashCodeUtil.hashCode(0, name);
-		for(int i=0; i<types.length; i++) {
-			hash = HashCodeUtil.hashCode(hash, types[i]);
-		}
-	}
-
-	public String getName() {
-		return this.name;				
-	}
-    
-    public PushDown getPushdown() {
-        return this.pushdown;
-    }
-    
-    void setPushdown(PushDown pushdown) {
-        this.pushdown = pushdown;
-    }
-	
-	public Class[] getTypes() {
-		return this.types;
-	}
-	
-	public Class getReturnType() {
-		return this.returnType;
-	}		
-	
-    Method getInvocationMethod() {
-        return this.invocationMethod;
-    }
-       
-    public boolean requiresContext() {
-        return this.requiresContext;
-    }
-    
-	public int hashCode() { 
-		return this.hash;
-	}
-	
-	public boolean equals(Object obj) {
-		if(obj == this) {
-			return true;
-		}
-		
-		if(obj == null || !(obj instanceof FunctionDescriptor)) {
-			return false;			
-		}	
-		FunctionDescriptor other = (FunctionDescriptor) obj;
-		
-		// Compare names
-		if(! this.getName().equals(other.getName())) {
-			return false;
-		}
-        
-        // Compare arg types
-		Class[] thisTypes = this.getTypes();
-		Class[] otherTypes = other.getTypes();
-		if(thisTypes.length != otherTypes.length) {
-			return false;
-		}
-		for(int i=0; i<thisTypes.length; i++) { 
-			if(! thisTypes[i].equals(otherTypes[i])) {
-				return false;
-			}
-		}
-        
-        if (this.nullDependent != other.isNullDependent()) {
-            return false;
-        }
-        
-        if (this.deterministic != other.deterministic) {
-            return false;
-        }
-		 
-		// Must be a match
-		return true;
-	}
-	
-	public String toString() {
-		StringBuffer str = new StringBuffer(this.name);
-		str.append("("); //$NON-NLS-1$
-		for(int i=0; i<types.length; i++) {
-			if(types[i] != null) { 
-				str.append(types[i].getName());
-			} else {
-				str.append("null"); //$NON-NLS-1$
-			}		
-			if(i<(types.length-1)) {
-				str.append(", "); //$NON-NLS-1$
-			}
-		}
-		str.append(") : "); //$NON-NLS-1$
-        if(returnType == null) { 
-            str.append("null"); //$NON-NLS-1$
-        } else {    
-    		str.append(returnType.getName());
-        }    
-		return str.toString();
-	}
-
-    public boolean isNullDependent() {
-        return nullDependent;
-    }
-    
-    public Determinism getDeterministic() {
-        return deterministic;
-    }
-
-    void setDeterministic(Determinism deterministic) {
-        this.deterministic = deterministic;
-    }
-    
-    public Object clone() {
-        try {
-            return super.clone();
-        } catch (CloneNotSupportedException e) {
-            throw new TeiidRuntimeException(e);
-        }
-    }
-
-    void setReturnType(Class returnType) {
-        this.returnType = returnType;
-    }
-    
-    
-	/**
-	 * Invoke the function described in the function descriptor, using the
-	 * values provided.  Return the result of the function.
-	 * @param fd Function descriptor describing the name and types of the arguments
-	 * @param values Values that should match 1-to-1 with the types described in the
-	 * function descriptor
-	 * @return Result of invoking the function
-	 */
-	public Object invokeFunction(Object[] values) throws FunctionExecutionException {
-
-        if (!isNullDependent()) {
-        	for (int i = 0; i < values.length; i++) {
-				if (values[i] == null) {
-					return null;
-				}
-			}
-        }
-
-        // If descriptor is missing invokable method, find this VM's descriptor
-        // give name and types from fd
-        Method method = getInvocationMethod();
-        if(method == null) {
-        	throw new FunctionExecutionException("ERR.015.001.0002", QueryPlugin.Util.getString("ERR.015.001.0002", getName())); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        if (getDeterministic().isRestrictiveThanOrEqual(Determinism.USER_DETERMINISTIC) && values.length > 0 && values[0] instanceof CommandContext) {
-        	CommandContext cc = (CommandContext)values[0];
-        	cc.setDeterminismLevel(getDeterministic());
-        }
-        
-        // Invoke the method and return the result
-        try {
-        	if (method.isVarArgs()) {
-        		int i = method.getParameterTypes().length;
-        		Object[] newValues = Arrays.copyOf(values, i);
-        		newValues[i - 1] = Arrays.copyOfRange(values, i - 1, values.length);
-        		values = newValues;
-        	}
-            Object result = method.invoke(null, values);
-            return importValue(result, getReturnType());
-        } catch(ArithmeticException e) {
-    		throw new FunctionExecutionException(e, "ERR.015.001.0003", QueryPlugin.Util.getString("ERR.015.001.0003", getName())); //$NON-NLS-1$ //$NON-NLS-2$
-        } catch(InvocationTargetException e) {
-            throw new FunctionExecutionException(e.getTargetException(), "ERR.015.001.0003", QueryPlugin.Util.getString("ERR.015.001.0003", getName())); //$NON-NLS-1$ //$NON-NLS-2$
-        } catch(IllegalAccessException e) {
-            throw new FunctionExecutionException(e, "ERR.015.001.0004", QueryPlugin.Util.getString("ERR.015.001.0004", method.toString())); //$NON-NLS-1$ //$NON-NLS-2$
-        } catch (TransformationException e) {
-        	throw new FunctionExecutionException(e, e.getMessage());
-		}
-	}
-
-	public static Object importValue(Object result, Class<?> expectedType)
-			throws ArithmeticException, TransformationException {
-		if (!ALLOW_NAN_INFINITY) {
-			if (result instanceof Double) {
-		    	Double floatVal = (Double)result;
-		    	if (Double.isInfinite(floatVal) || Double.isNaN(floatVal)) {
-		    		throw new ArithmeticException("Infinite or invalid result");  //$NON-NLS-1$
-		    	}
-		    } else if (result instanceof Float) {
-		    	Float floatVal = (Float)result;
-		    	if (Float.isInfinite(floatVal) || Float.isNaN(floatVal)) {
-		    		throw new ArithmeticException("Infinite or invalid result");  //$NON-NLS-1$
-		    	}
-		    }
-		}
-		result = DataTypeManager.convertToRuntimeType(result);
-		result = DataTypeManager.transformValue(result, expectedType);
-		if (result instanceof String) {
-			String s = (String)result;
-			if (s.length() > DataTypeManager.MAX_STRING_LENGTH) {
-				return s.substring(0, DataTypeManager.MAX_STRING_LENGTH);
-			}
-		}
-		return result;
-	}    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java (from rev 2762, trunk/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,293 @@
+/*
+ * 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.function;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.TransformationException;
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * The FunctionDescriptor describes a particular function instance enough
+ * that the function library can retrieve a function instance based on the 
+ * descriptor.
+ */
+public class FunctionDescriptor implements Serializable, Cloneable {
+	private static final long serialVersionUID = 5374103983118037242L;
+
+	private static final boolean ALLOW_NAN_INFINITY = PropertiesUtils.getBooleanProperty(System.getProperties(), "org.teiid.allowNanInfinity", false); //$NON-NLS-1$
+	
+	private String name;
+    private PushDown pushdown = PushDown.CAN_PUSHDOWN;
+	private Class[] types;
+	private Class returnType;	
+	private int hash;
+    private boolean requiresContext;
+    private boolean nullDependent;
+    private Determinism deterministic = Determinism.DETERMINISTIC;
+    
+    // This is transient as it would be useless to invoke this method in 
+    // a different VM.  This function descriptor can be used to look up 
+    // the real VM descriptor for execution.
+    private transient Method invocationMethod;
+	
+    FunctionDescriptor() {
+    }
+    
+    /** 
+     * Construct a function descriptor with all the info
+     * @param name Name of function
+     * @param types Types of the arguments
+     * @param returnType Type of the return 
+     * @param invocationMethod Reflection method used to invoke the function
+     * @param requiresContext during execution requires command context to be pushed into method as first argument
+     */
+	FunctionDescriptor(String name, PushDown pushdown, Class[] types, Class returnType, Method invocationMethod, boolean requiresContext, boolean nullDependent, Determinism deterministic) {
+		Assertion.isNotNull(name);
+		Assertion.isNotNull(types);
+		Assertion.isNotNull(returnType);
+		
+		this.name = name;
+        this.pushdown = pushdown;
+		this.types = types;
+		this.returnType = returnType;
+        this.invocationMethod = invocationMethod;
+        this.requiresContext = requiresContext;
+        this.nullDependent = nullDependent;
+        this.deterministic = deterministic;
+		
+		// Compute hash code
+		hash = HashCodeUtil.hashCode(0, name);
+		for(int i=0; i<types.length; i++) {
+			hash = HashCodeUtil.hashCode(hash, types[i]);
+		}
+	}
+
+	public String getName() {
+		return this.name;				
+	}
+    
+    public PushDown getPushdown() {
+        return this.pushdown;
+    }
+    
+    void setPushdown(PushDown pushdown) {
+        this.pushdown = pushdown;
+    }
+	
+	public Class[] getTypes() {
+		return this.types;
+	}
+	
+	public Class getReturnType() {
+		return this.returnType;
+	}		
+	
+    Method getInvocationMethod() {
+        return this.invocationMethod;
+    }
+       
+    public boolean requiresContext() {
+        return this.requiresContext;
+    }
+    
+	public int hashCode() { 
+		return this.hash;
+	}
+	
+	public boolean equals(Object obj) {
+		if(obj == this) {
+			return true;
+		}
+		
+		if(obj == null || !(obj instanceof FunctionDescriptor)) {
+			return false;			
+		}	
+		FunctionDescriptor other = (FunctionDescriptor) obj;
+		
+		// Compare names
+		if(! this.getName().equals(other.getName())) {
+			return false;
+		}
+        
+        // Compare arg types
+		Class[] thisTypes = this.getTypes();
+		Class[] otherTypes = other.getTypes();
+		if(thisTypes.length != otherTypes.length) {
+			return false;
+		}
+		for(int i=0; i<thisTypes.length; i++) { 
+			if(! thisTypes[i].equals(otherTypes[i])) {
+				return false;
+			}
+		}
+        
+        if (this.nullDependent != other.isNullDependent()) {
+            return false;
+        }
+        
+        if (this.deterministic != other.deterministic) {
+            return false;
+        }
+		 
+		// Must be a match
+		return true;
+	}
+	
+	public String toString() {
+		StringBuffer str = new StringBuffer(this.name);
+		str.append("("); //$NON-NLS-1$
+		for(int i=0; i<types.length; i++) {
+			if(types[i] != null) { 
+				str.append(types[i].getName());
+			} else {
+				str.append("null"); //$NON-NLS-1$
+			}		
+			if(i<(types.length-1)) {
+				str.append(", "); //$NON-NLS-1$
+			}
+		}
+		str.append(") : "); //$NON-NLS-1$
+        if(returnType == null) { 
+            str.append("null"); //$NON-NLS-1$
+        } else {    
+    		str.append(returnType.getName());
+        }    
+		return str.toString();
+	}
+
+    public boolean isNullDependent() {
+        return nullDependent;
+    }
+    
+    public Determinism getDeterministic() {
+        return deterministic;
+    }
+
+    void setDeterministic(Determinism deterministic) {
+        this.deterministic = deterministic;
+    }
+    
+    public Object clone() {
+        try {
+            return super.clone();
+        } catch (CloneNotSupportedException e) {
+            throw new TeiidRuntimeException(e);
+        }
+    }
+
+    void setReturnType(Class returnType) {
+        this.returnType = returnType;
+    }
+    
+    
+	/**
+	 * Invoke the function described in the function descriptor, using the
+	 * values provided.  Return the result of the function.
+	 * @param fd Function descriptor describing the name and types of the arguments
+	 * @param values Values that should match 1-to-1 with the types described in the
+	 * function descriptor
+	 * @return Result of invoking the function
+	 */
+	public Object invokeFunction(Object[] values) throws FunctionExecutionException {
+
+        if (!isNullDependent()) {
+        	for (int i = 0; i < values.length; i++) {
+				if (values[i] == null) {
+					return null;
+				}
+			}
+        }
+
+        // If descriptor is missing invokable method, find this VM's descriptor
+        // give name and types from fd
+        Method method = getInvocationMethod();
+        if(method == null) {
+        	throw new FunctionExecutionException("ERR.015.001.0002", QueryPlugin.Util.getString("ERR.015.001.0002", getName())); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        if (getDeterministic().compareTo(Determinism.USER_DETERMINISTIC) <= 0 && values.length > 0 && values[0] instanceof CommandContext) {
+        	CommandContext cc = (CommandContext)values[0];
+        	cc.setDeterminismLevel(getDeterministic());
+        }
+        
+        // Invoke the method and return the result
+        try {
+        	if (method.isVarArgs()) {
+        		int i = method.getParameterTypes().length;
+        		Object[] newValues = Arrays.copyOf(values, i);
+        		newValues[i - 1] = Arrays.copyOfRange(values, i - 1, values.length);
+        		values = newValues;
+        	}
+            Object result = method.invoke(null, values);
+            return importValue(result, getReturnType());
+        } catch(ArithmeticException e) {
+    		throw new FunctionExecutionException(e, "ERR.015.001.0003", QueryPlugin.Util.getString("ERR.015.001.0003", getName())); //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(InvocationTargetException e) {
+            throw new FunctionExecutionException(e.getTargetException(), "ERR.015.001.0003", QueryPlugin.Util.getString("ERR.015.001.0003", getName())); //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(IllegalAccessException e) {
+            throw new FunctionExecutionException(e, "ERR.015.001.0004", QueryPlugin.Util.getString("ERR.015.001.0004", method.toString())); //$NON-NLS-1$ //$NON-NLS-2$
+        } catch (TransformationException e) {
+        	throw new FunctionExecutionException(e, e.getMessage());
+		}
+	}
+
+	public static Object importValue(Object result, Class<?> expectedType)
+			throws ArithmeticException, TransformationException {
+		if (!ALLOW_NAN_INFINITY) {
+			if (result instanceof Double) {
+		    	Double floatVal = (Double)result;
+		    	if (Double.isInfinite(floatVal) || Double.isNaN(floatVal)) {
+		    		throw new ArithmeticException("Infinite or invalid result");  //$NON-NLS-1$
+		    	}
+		    } else if (result instanceof Float) {
+		    	Float floatVal = (Float)result;
+		    	if (Float.isInfinite(floatVal) || Float.isNaN(floatVal)) {
+		    		throw new ArithmeticException("Infinite or invalid result");  //$NON-NLS-1$
+		    	}
+		    }
+		}
+		result = DataTypeManager.convertToRuntimeType(result);
+		result = DataTypeManager.transformValue(result, expectedType);
+		if (result instanceof String) {
+			String s = (String)result;
+			if (s.length() > DataTypeManager.MAX_STRING_LENGTH) {
+				return s.substring(0, DataTypeManager.MAX_STRING_LENGTH);
+			}
+		}
+		return result;
+	}    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1308 +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.function;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.math.RoundingMode;
-import java.nio.charset.Charset;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.text.DateFormat;
-import java.text.DecimalFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Properties;
-import java.util.TimeZone;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-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.TransformationException;
-import org.teiid.core.types.InputStreamFactory.BlobInputStreamFactory;
-import org.teiid.core.types.InputStreamFactory.ClobInputStreamFactory;
-import org.teiid.core.util.TimestampWithTimezone;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.util.CommandContext;
-
-/**
- * Static method hooks for most of the function library.
- */
-public final class FunctionMethods {
-
-	// ================== Function = plus =====================
-
-	public static int plus(int x, int y) {
-		return x + y;
-	}
-	
-	public static long plus(long x, long y) {
-		return x + y;
-	}
-	
-	public static float plus(float x, float y) {
-		return x + y;
-	}
-	
-	public static double plus(double x, double y) {
-		return x + y;
-	}
-	
-	public static Object plus(BigInteger x, BigInteger y) {
-		return x.add(y);
-	}
-	
-	public static Object plus(BigDecimal x, BigDecimal y) {
-		return x.add(y);
-	}
-
-	// ================== Function = minus =====================
-
-	public static int minus(int x, int y) {
-		return x - y;
-	}
-	
-	public static long minus(long x, long y) {
-		return x - y;
-	}
-	
-	public static float minus(float x, float y) {
-		return x - y;
-	}
-	
-	public static double minus(double x, double y) {
-		return x - y;
-	}
-	
-	public static Object minus(BigInteger x, BigInteger y) {
-		return x.subtract(y);
-	}
-	
-	public static Object minus(BigDecimal x, BigDecimal y) {
-		return x.subtract(y);
-	}
-
-	// ================== Function = multiply =====================
-
-	public static int multiply(int x, int y) {
-		return x * y;
-	}
-	
-	public static long multiply(long x, long y) {
-		return x * y;
-	}
-	
-	public static float multiply(float x, float y) {
-		return x * y;
-	}
-	
-	public static double multiply(double x, double y) {
-		return x * y;
-	}
-	
-	public static Object multiply(BigInteger x, BigInteger y) {
-		return x.multiply(y);
-	}
-	
-	public static Object multiply(BigDecimal x, BigDecimal y) {
-		return x.multiply(y);
-	}
-
-	// ================== Function = divide =====================
-
-	public static int divide(int x, int y) {
-		return x / y;
-	}
-	
-	public static long divide(long x, long y) {
-		return x / y;
-	}
-	
-	public static float divide(float x, float y) {
-		return x / y;
-	}
-	
-	public static double divide(double x, double y) {
-		return x / y;
-	}
-	
-	public static Object divide(BigInteger x, BigInteger y) {
-		return x.divide(y);
-	}
-	
-	public static Object divide(BigDecimal x, BigDecimal y) {
-		BigDecimal bd = x.divide(y, Math.max(16, x.scale() + y.precision() + 1), RoundingMode.HALF_UP).stripTrailingZeros();
-		return bd.setScale(Math.max(x.scale(), bd.scale()));
-	}
-
-	// ================== Function = abs =====================
-
-	public static int abs(int x) {
-		return Math.abs(x);
-	}
-	
-	public static long abs(long x) {
-		return Math.abs(x);
-	}
-	
-	public static float abs(float x) {
-		return Math.abs(x);
-	}
-	
-	public static double abs(double x) {
-		return Math.abs(x);
-	}
-	
-	public static Object abs(BigInteger x) {
-		return x.abs();
-	}
-	
-	public static Object abs(BigDecimal x) {
-		return x.abs();
-	}
-
-	// ================== Function = ceiling =====================
-
-	public static Object ceiling(Number x) {
-		return new Double(Math.ceil(x.doubleValue()));
-	}
-
-	// ================== Function = exp =====================
-
-	public static Object exp(Number x) {
-		return new Double(Math.exp(x.doubleValue()));
-	}
-
-	// ================== Function = floor =====================
-
-	public static  Object floor(Number x) {
-		return new Double(Math.floor(x.doubleValue()));
-	}
-
-	// ================== Function = log =====================
-
-	public static  Object log(Number x) {
-		return new Double(Math.log(x.doubleValue()));
-	}
-
-	// ================== Function = log10 =====================
-
-	private static final double log10baseE = Math.log(10);
-
-	public static Object log10(Number x) {
-		return new Double( Math.log(x.doubleValue()) / log10baseE);
-	}
-    
-    // ================== Function = rand=====================
-    
-    public static Object rand(CommandContext context, Object seed) throws FunctionExecutionException {        
-        if(context != null) {
-            if(seed == null) {
-                return new Double(context.getNextRand());
-            } else if(seed instanceof Integer) {
-                return new Double(context.getNextRand(((Integer)seed).longValue()));
-            }
-        }
-        throw new FunctionExecutionException("ERR.015.001.0069", QueryPlugin.Util.getString("ERR.015.001.0069", "rand", seed)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$        
-    }
-        
-    public static Object rand(CommandContext context) throws FunctionExecutionException {
-        if(context != null) {
-            return new Double(context.getNextRand());
-        }
-        throw new FunctionExecutionException("ERR.015.001.0069", QueryPlugin.Util.getString("ERR.015.001.0069", "rand")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-	// ================== Function = mod =====================
-
-	public static int mod(int x, int y) {
-		return x % y;
-	}
-	
-	public static long mod(long x, long y) {
-		return x % y;
-	}
-	
-	public static float mod(float x, float y) {
-		return x % y;
-	}
-	
-	public static double mod(double x, double y) {
-		return x % y;
-	}
-	
-	public static Object mod(BigInteger x, BigInteger y) {
-		return x.remainder(y);
-	}
-	
-	public static Object mod(BigDecimal x, BigDecimal y) {
-		return x.remainder(y);
-	}
-    
-	// ================== Function = power =====================
-	
-	public static double power(double x, double y) {
-		return Math.pow(x, y);
-	}
-	
-	public static BigInteger power(BigInteger x, int y) {
-		return x.pow(y);
-	}
-	
-	public static BigDecimal power(BigDecimal x, int y) {
-		return x.pow(y);
-	}
-
-    public static int round(int number, int places) {
-        if(places < 0){
-        	return round(new BigDecimal(number), places).intValue();
-        }
-        return number;
-    }
-    
-    public static float round(float number, int places) {
-    	return round(new BigDecimal(number), places).floatValue();
-    }
-    
-    public static double round(double number, int places) {
-    	return round(new BigDecimal(number), places).doubleValue();
-    }
-    
-    public static BigDecimal round(BigDecimal bigDecimalNumber, int places) {
-        int scale = bigDecimalNumber.scale();
-        if (scale <= places) {
-        	return bigDecimalNumber;
-        }
-        bigDecimalNumber = bigDecimalNumber.setScale(places,BigDecimal.ROUND_HALF_UP);
-        return bigDecimalNumber.setScale(scale,BigDecimal.ROUND_HALF_UP);
-    }
-
-	// ================== Function = sign =====================
-
-	public static Object sign(int x) {
-		return Integer.signum(x);
-	}
-	
-	public static Object sign(long x) {
-		return Long.signum(x);
-	}
-
-	public static Object sign(float x) {
-		return Math.signum(x);
-	}
-	
-	public static Object sign(double x) {
-		return Math.signum(x);
-	}
-	
-	public static Object sign(BigInteger x) {
-		return new Integer(x.signum());
-	}
-	
-	public static Object sign(BigDecimal x) {
-		return new Integer(x.signum());
-	}
-
-	// ================== Function = sqrt =====================
-
-
-	public static  Object sqrt(Number x) {
-		return new Double( Math.sqrt(x.doubleValue()));
-	}
-
-	// ================== Function = currentDate =====================
-
-	public static  Object currentDate() {
-		return TimestampWithTimezone.createDate(new Date());
-	}
-
-	// ================== Function = currentTime =====================
-
-	public static  Object currentTime() {
-		return TimestampWithTimezone.createTime(new Date());
-	}
-
-	// ================== Function = currentTimestamp =====================
-
-	public static  Object currentTimestamp() {
-		return new Timestamp(System.currentTimeMillis());
-	}
-
-	// ================== Helper for a bunch of date functions =====================
-
-	private static int getField(java.util.Date date, int field) {
-		Calendar cal = TimestampWithTimezone.getCalendar();
-		cal.setTime(date);
-
-		return cal.get(field);
-	}
-
-	// ================== Function = dayname =====================
-
-	static final String[] dayNames = new String[] {
-		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-
-	public static Object dayName(Date x) {
-		return dayNames[getField(x, Calendar.DAY_OF_WEEK) - 1];
-	}
-
-	// ================== Function = dayofmonth =====================
-
-	public static  Object dayOfMonth(Date x) {
-		return Integer.valueOf(getField(x, Calendar.DATE));
-	}
-
-	// ================== Function = dayofweek =====================
-
-	public static Object dayOfWeek(Date x) {
-		return Integer.valueOf(getField(x, Calendar.DAY_OF_WEEK));
-	}
-
-	// ================== Function = dayofyear =====================
-
-	public static Object dayOfYear(Date x) {
-		return Integer.valueOf(getField(x, Calendar.DAY_OF_YEAR));
-	}
-
-	// ================== Function = hour =====================
-
-	public static Object hour(Date x) {
-		return Integer.valueOf(getField(x, Calendar.HOUR_OF_DAY));
-	}
-
-	// ================== Function = minute =====================
-
-	public static Object minute(Date x) {
-		return Integer.valueOf(getField(x, Calendar.MINUTE));
-	}
-
-	// ================== Function = month =====================
-
-	public static Object month(Date x) {
-		return Integer.valueOf(getField(x, Calendar.MONTH)+1);
-	}
-
-	// ================== Function = monthname =====================
-
-	static final String[] monthNames = new String[] {
-		"January", "February", "March", "April", "May", "June", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-		"July", "August", "September", "October", "November", "December" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-
-	public static Object monthName(Date x) {
-		return monthNames[getField(x, Calendar.MONTH)];
-	}
-
-	// ================== Function = second =====================
-
-	public static Object second(Date x) {
-		return Integer.valueOf(getField(x, Calendar.SECOND));
-	}
-
-	// ================== Function = week =====================
-
-	public static Object week(Date x) {
-		return Integer.valueOf(getField(x, Calendar.WEEK_OF_YEAR));
-	}
-
-	// ================== Function = year =====================
-
-	public static Object year(Date x) {
-		return Integer.valueOf(getField(x, Calendar.YEAR));
-	}
-
-	// ================== Function = quarter =====================
-
-	public static Object quarter(Date date)
-		throws FunctionExecutionException {
-		int month = getField(date, Calendar.MONTH);
-		
-		if (month > 11) {
-			throw new FunctionExecutionException("ERR.015.001.0066", QueryPlugin.Util.getString("ERR.015.001.0066", //$NON-NLS-1$ //$NON-NLS-2$
-					new Object[] {"quarter", date.getClass().getName()})); //$NON-NLS-1$
-		}
-		return Integer.valueOf(month/3 + 1);
-	}
-
-	//	================== Function = timestampadd =====================
-
-	public static Object timestampAdd(String intervalType, Integer count, Timestamp timestamp) {
-		Calendar cal = TimestampWithTimezone.getCalendar();
-
-		int nanos = timestamp.getNanos();
-		cal.setTime(timestamp);
-
-		// case of interval = 1, fractional seconds (nanos), don't go to branches of addField()
-		if (intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
-			int countValue = count.intValue();
-			nanos += countValue;
-
-			// Handle the case of nanos > 999,999,999 and increase the second.
-			// Since the count number is an interger, so the maximum is definite,
-			// and nanos/999,999,999 can at most be added to second
-			if ( nanos > 999999999) {
-				int addSecond = nanos / 999999999;
-				int leftNanos = nanos % 999999999;
-				cal.add(Calendar.SECOND, addSecond);
-
-				Timestamp ts = new Timestamp(cal.getTime().getTime());
-				ts.setNanos(leftNanos);
-				return ts;
-			} 
-            // nanos <= 999,999,999
-			Timestamp ts = new Timestamp(cal.getTime().getTime());
-			ts.setNanos(nanos);
-			return ts;
-		}
-        // for interval from 2 to 9
-		addField(intervalType, count, cal);
-		Timestamp ts = new Timestamp(cal.getTime().getTime());
-
-		//rectify returned timestamp with original nanos
-		ts.setNanos(nanos);
-		return ts;
-	}
-	
-	/** Helper method for timestampAdd method
-	 * @param interval Integer
-	 * @param count Integer
-	 * @param cal Calendar instance
-	 */
-	private static void addField(String interval, Integer count, Calendar cal) {
-		int countValue = count.intValue();
-
-        if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
-            //nano seconds - should never get into this branch
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
-            cal.add(Calendar.SECOND, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
-            cal.add(Calendar.MINUTE, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
-            cal.add(Calendar.HOUR_OF_DAY, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
-            cal.add(Calendar.DAY_OF_YEAR, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
-            cal.add(Calendar.WEEK_OF_YEAR, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
-            cal.add(Calendar.MONTH, countValue);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
-            cal.add(Calendar.MONTH, countValue*3);
-        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
-            cal.add(Calendar.YEAR, countValue);
-        }
-	}
-
-	//	================== Function = timestampdiff =====================
-
-	/**
-     * This method truncates (ignores) figures
-     * @param interval
-     * @param timestamp1
-     * @param timestamp2
-     * @return
-     * @throws FunctionExecutionException
-     */
-    public static Object timestampDiff(String intervalType, Timestamp ts1Obj, Timestamp ts2Obj)  {
-        long ts1 = ts1Obj.getTime() / 1000 * 1000000000 + ts1Obj.getNanos();
-        long ts2 = ts2Obj.getTime() / 1000 * 1000000000 + ts2Obj.getNanos();
-        
-        long tsDiff = ts2 - ts1;
-
-        long count = 0;
-        if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
-            count = tsDiff;
-        } else { 
-        	tsDiff = tsDiff / 1000000; //convert to milliseconds
-            if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
-                count = tsDiff / 1000;
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
-                count = (tsDiff / 1000) / 60;
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
-                count = (tsDiff / 1000) / (60*60);
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
-                count = (tsDiff / 1000) / (60*60*24);
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
-                count = (tsDiff / 1000) / (60*60*24*7);
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
-                count = (tsDiff / 1000) / (60*60*24*30);
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
-                count = (tsDiff / 1000) / (60*60*24*91);
-            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
-                count = (tsDiff / 1000) / (60*60*24*365);
-            }    
-        }
-        return new Long(count);
-	}
-
-    //  ================== Function = timestampcreate =====================
-
-    /**
-     * This method truncates (ignores) figures
-     * @param interval
-     * @param timestamp1
-     * @param timestamp2
-     * @return
-     * @throws FunctionExecutionException
-     */
-    public static Object timestampCreate(java.sql.Date date, Time time) {
-        Calendar tsCal = TimestampWithTimezone.getCalendar();
-        tsCal.setTime(time);
-        int hour = tsCal.get(Calendar.HOUR_OF_DAY);
-        int minute = tsCal.get(Calendar.MINUTE);
-        int second = tsCal.get(Calendar.SECOND);
-        
-        tsCal.setTime(date);
-        
-        tsCal.set(Calendar.HOUR_OF_DAY, hour);
-        tsCal.set(Calendar.MINUTE, minute);
-        tsCal.set(Calendar.SECOND, second);
-
-        return new Timestamp(tsCal.getTime().getTime());
-    }
-
-	// ================== Function = length =====================
-
-	public static Object length(String str) {
-		return new Integer(str.length());
-	}
-
-	// ================== Function = concat =====================
-
-	public static Object concat(String str1, String str2) {
-		return str1 + str2;
-	}
-
-	// ================== Function = substring =====================
-
-	public static Object substring(String string, Integer startVal, Integer lengthVal) {
-		if (startVal < 0) {
-        	startVal = string.length() + startVal;
-        } else if (startVal > 0){
-            startVal--;     // Adjust to 1-based
-        }
-		
-		if(startVal < 0 || startVal >= string.length()) {
-		    return null;
-		}
-
-		if(lengthVal < 0) {
-		    return null;
-		}
-
-		int endVal = Math.min(startVal+lengthVal, string.length());
-
-		return string.substring(startVal, endVal);
-	}
-
-    public static Object substring(String string, Integer start) {
-        int startVal = start.intValue();
-        return substring(string, startVal, string.length());
-    }
-
-	// ================== Function = left =====================
-
-	public static Object left(String string, Integer count)
-		throws FunctionExecutionException {
-		int countValue = count.intValue();
-        if(countValue < 0) {
-            throw new FunctionExecutionException("ERR.015.001.0017", QueryPlugin.Util.getString("ERR.015.001.0017", countValue)); //$NON-NLS-1$ //$NON-NLS-2$
-        } 
-        if(string.length() < countValue) {
-            return string;
-        }
-        return string.substring(0, countValue);
-	}
-
-	// ================== Function = right =====================
-
-	public static Object right(String string, Integer count) 
-		throws FunctionExecutionException {
-		int countValue = count.intValue();
-        if(countValue < 0) {
-            throw new FunctionExecutionException("ERR.015.001.0017", QueryPlugin.Util.getString("ERR.015.001.0017", countValue)); //$NON-NLS-1$ //$NON-NLS-2$
-        } else if(string.length() < countValue) {
-            return string;
-		} else {
-			return string.substring(string.length() - countValue);
-        }
-	}
-
-	// ================== Function = lowercase =====================
-
-	public static Object lowerCase(String str) {
-		return str.toLowerCase();
-	}
-
-	// ================== Function = uppercase =====================
-
-	public static Object upperCase(String str) {
-		return str.toUpperCase();
-	}
-
-	// ================== Function = locate =====================
-
-	public static Object locate(String sub, String str) {
-		return locate(sub, str, 1);
-	}
-
-	/**
-	 * TODO: The treatment of negative start indexes is inconsistent here.
-	 * We're treating the null value like Derby, but not throwing an
-	 * exception if the value is less than 1 (less than 0 in DB2).
-	 */
-	public static Object locate(String sub, String str, Integer start) {
-		if(str == null || sub == null) {
-			return null;
-		} 
-		if (start == null) {
-			start = 1;
-		}
-		return new Integer(str.indexOf(sub, start.intValue() - 1) + 1);
-	}
-
-	// ================== Function = lefttrim =====================
-
-	private static final char SPACE = ' ';
-
-	public static Object leftTrim(String string) {
-		for(int i=0; i<string.length(); i++) {
-			if(string.charAt(i) != SPACE) {
-				// end of trim, return what's left
-				return string.substring(i);
-			}
-		}
-
-		// All spaces, so trim it all
-		return ""; //$NON-NLS-1$
-	}
-
-	// ================== Function = righttrim =====================
-
-	public static Object rightTrim(String string) {
-		for(int i=string.length()-1; i>=0; i--) {
-			if(string.charAt(i) != SPACE) {
-				// end of trim, return what's left
-				return string.substring(0, i+1);
-			}
-		}
-
-		// All spaces, so trim it all
-		return ""; //$NON-NLS-1$
-	}
-
-	// ================== Function = replace =====================
-
-	public static Object replace(String string, String subString, String replaceString) {
-		// Check some simple cases that require no work
-		if(subString.length() > string.length() || string.length() == 0 || subString.length() == 0) {
-			return string;
-		}
-
-		StringBuffer result = new StringBuffer();
-		int index = 0;
-
-		while(true) {
-			int newIndex = string.indexOf(subString, index);
-			if(newIndex < 0) {
-				// No more replacement sections, grab from old index to end of string
-				result.append( string.substring(index) );
-
-				// Break out of loop
-				break;
-
-			}
-			// Matched the substring at newIndex
-
-			// First append section from old index to new
-			result.append( string.substring( index, newIndex) );
-
-			// Then append replacement section for sub
-			result.append( replaceString );
-
-			// Then move the index counter forward
-			index = newIndex + subString.length();
-		}
-
-		return result.toString();
-	}
-
-	// ================== Function = insert =====================
-
-	public static Object insert(String string1, Integer start, Integer length, String str2)
-		throws FunctionExecutionException {
-		int startValue = start.intValue();
-		int len = length.intValue();
-
-		// Check some invalid cases
-		if(startValue < 1 || (startValue-1) > string1.length()) {
-			throw new FunctionExecutionException("ERR.015.001.0061", QueryPlugin.Util.getString("ERR.015.001.0061", start, string1)); //$NON-NLS-1$ //$NON-NLS-2$
-		} else if (len < 0) {
-			throw new FunctionExecutionException("ERR.015.001.0062", QueryPlugin.Util.getString("ERR.015.001.0062", len)); //$NON-NLS-1$ //$NON-NLS-2$
-		} else if (string1.length() == 0 && (startValue > 1 || len >0) ) {
-			throw new FunctionExecutionException("ERR.015.001.0063", QueryPlugin.Util.getString("ERR.015.001.0063")); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-
-		StringBuffer result = new StringBuffer();
-		result.append(string1.substring(0, startValue-1));
-		int endValue = startValue + len - 1;
-
-		// str2.length() = 0 is a valid case
-		if (endValue > string1.length()) {
-			result.append(str2);
-		} else {
-			result.append(str2);
-			result.append(string1.substring( endValue ));
-		}
-
-		return result.toString();
-	}
-
-	// ================== Function = repeat =====================
-	public static Object repeat(String str, Integer count) {
-		int repeatCount = count.intValue();
-		StringBuffer result = new StringBuffer();
-
-		for (int i = 0; i < repeatCount && result.length() <= DataTypeManager.MAX_STRING_LENGTH; i++) {
-			result.append(str);
-		}
-		return result.toString();
-	}
-
-    // ================== Function = ascii =====================
-
-    public static Integer ascii(String ch) {
-        if(ch.length() == 0) {
-        	return null;
-        } 
-        return (int)ch.charAt(0);
-    }
-    
-    public static Integer ascii(Character ch) {
-        return (int)ch.charValue();
-    }
-
-    // ================== Function = chr =====================
-
-    public static Object chr(int intValue) {
-        return new Character((char) intValue);
-    }
-
-    // ================== Function = initCap =====================
-
-    public static Object initCap(String s) {
-        StringBuffer cap = new StringBuffer();
-
-        boolean checkCap = true;
-        for(int i=0; i<s.length(); i++) {
-            char c = s.charAt(i);
-
-            // Decide whether to upper case
-            if(checkCap) {
-                cap.append(Character.toUpperCase(c));
-            } else {
-                cap.append(Character.toLowerCase(c));
-            }
-
-            // Reset flag for next character
-            checkCap = Character.isWhitespace(c);
-        }
-        return cap.toString();
-    }
-
-    // ================== Function = lpad =====================
-
-    public static Object lpad(String inputString, Integer padLength, String padStr)
-        throws FunctionExecutionException {
-
-    	return pad(inputString, padLength, padStr, true);
-    }
-
-    public static Object pad(String str, Integer padLength, String padStr, boolean left)
-    throws FunctionExecutionException {
-	    int length = padLength.intValue();
-	    if(length < 1) {
-	        throw new FunctionExecutionException("ERR.015.001.0025", QueryPlugin.Util.getString("ERR.015.001.0025")); //$NON-NLS-1$ //$NON-NLS-2$
-	    }
-	    if(length < str.length()) {
-	        return str.substring(0, length);
-	    }
-	    if(length > DataTypeManager.MAX_STRING_LENGTH) {
-	    	length = DataTypeManager.MAX_STRING_LENGTH;
-	    }
-	    // Get pad character
-	    if(padStr.length() == 0) {
-	        throw new FunctionExecutionException("ERR.015.001.0027", QueryPlugin.Util.getString("ERR.015.001.0027")); //$NON-NLS-1$ //$NON-NLS-2$
-	    }
-	    // Pad string
-	    StringBuffer outStr = new StringBuffer(str);
-	    while(outStr.length() < length) {
-	    	if (left) {
-	    		outStr.insert(0, padStr);
-	    	} else {
-	    		outStr.append(padStr);
-	    	}
-	    }
-	    if (left) {
-	    	return outStr.substring(outStr.length() - length);
-	    }
-	    return outStr.substring(0, length);
-	}
-
-    
-    public static final String SPACE_CHAR = " "; //$NON-NLS-1$
-
-    public static Object lpad(String inputString, Integer padLength)
-        throws FunctionExecutionException {
-
-        return lpad(inputString, padLength, SPACE_CHAR);
-    }
-
-    // ================== Function = rpad =====================
-
-    public static Object rpad(String inputString, Integer padLength, String padStr)
-        throws FunctionExecutionException {
-
-    	return pad(inputString, padLength, padStr, false);
-    }
-
-    public static Object rpad(String inputString, Integer padLength)
-        throws FunctionExecutionException {
-
-        return rpad(inputString, padLength, SPACE_CHAR);
-    }
-
-    // ================== Function = translate =====================
-
-    public static Object translate(String str, String in, String out)
-        throws FunctionExecutionException {
-        if(in.length() != out.length()) {
-            throw new FunctionExecutionException("ERR.015.001.0031", QueryPlugin.Util.getString("ERR.015.001.0031")); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-
-        if(in.length() == 0 || str.length() == 0) {
-            return str;
-        }
-
-        StringBuffer translated = new StringBuffer(str.length());
-        for(int i=0; i<str.length(); i++) {
-            char c = str.charAt(i);
-            boolean matched = false;
-            for(int j=0; j<in.length(); j++) {
-                char inChar = in.charAt(j);
-                if(c == inChar) {
-                    translated.append(out.charAt(j));
-                    matched = true;
-                    break;
-                }
-            }
-            if(! matched) {
-                translated.append(c);
-            }
-        }
-        return translated.toString();
-    }
-
-	// ================== Function = convert =====================
-
-	@SuppressWarnings("unchecked")
-	public static Object convert(Object src, String type)
-		throws FunctionExecutionException {
-		try {
-			return DataTypeManager.transformValue(src, DataTypeManager.getDataTypeClass(type));
-		} catch(TransformationException e) {
-			throw new FunctionExecutionException(e, "ERR.015.001.0033", QueryPlugin.Util.getString("ERR.015.001.0033", new Object[]{src, DataTypeManager.getDataTypeName(src.getClass()), type})); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-	}
-
-    // ================== Function = context and rowlimit =====================
-
-    /**
-     * This function should never actually be called - it is here solely so the
-     * xml context function can be resolved properly.  The actual function is
-     * implemented in the XML planner.
-     * @param context The context to apply the criteria in
-     * @param expression The expression on the left side of the criteria
-     * @return Same as expression
-     */
-    public static Object context(Object context, Object expression)
-        throws FunctionExecutionException {
-
-        throw new FunctionExecutionException("ERR.015.001.0035", QueryPlugin.Util.getString("ERR.015.001.0035")); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /**
-     * This pseudo-function should never actually be called - it is here solely so the
-     * xml rowlimit function can be resolved properly.  The actual functionality is
-     * implemented in the XML planner/processor.
-     * @param expression The expression on the left side of the criteria, an xml node
-     * @return doesn't really return anything; this pseudo-function is used to control
-     * the number of rows returned from a mapping class.
-     */
-    public static Object rowlimit(Object expression)
-        throws FunctionExecutionException {
-    
-        throw new FunctionExecutionException("ERR.015.001.0035a", QueryPlugin.Util.getString("ERR.015.001.0035a")); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    /**
-     * This pseudo-function should never actually be called - it is here solely so the
-     * xml rowlimitexception function can be resolved properly.  The actual functionality is
-     * implemented in the XML planner/processor.
-     * @param expression The expression on the left side of the criteria, an xml node
-     * @return doesn't really return anything; this pseudo-function is used to control
-     * the number of rows returned from a mapping class.
-     */
-    public static Object rowlimitexception(Object expression)
-        throws FunctionExecutionException {
-    
-        throw new FunctionExecutionException("ERR.015.001.0035a", QueryPlugin.Util.getString("ERR.015.001.0035a")); //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    // ================== Function = lookup =====================
-
-    /**
-     * This function should never actually be called - it is here solely so the
-     * lookup function can be resolved properly.  The actual function is
-     * implemented in the ExpresionEvaluator
-     * @param context The context to apply the criteria in
-     * @param expression The expression on the left side of the criteria
-     * @return Same as expression
-     */
-    public static Object lookup(Object codeTable, Object returnElement, Object keyElement, Object keyValue) {
-
-        throw new UnsupportedOperationException("This method should never be called."); //$NON-NLS-1$
-    }
-	
-    // ================== Function = nvl =====================
-    
-    public static Object ifnull(Object value, Object ifNullValue) {
-    	return coalesce(value, ifNullValue);
-    }
-    
-    public static Object coalesce(Object value, Object value1, Object... other) {
-    	if (value != null) {
-    		return value;
-    	}
-    	if (value1 != null) {
-    		return value1;
-    	}
-        for (Object object : other) {
-			if (object != null) {
-				return object;
-			}
-		}
-        return null;
-    }
-
-	// ================== Format date/time/timestamp TO String ==================
-	public static String format(Date date, String format)
-		throws FunctionExecutionException {
-		try {
-            SimpleDateFormat sdf = new SimpleDateFormat(format);
-            return sdf.format(date);
-		} catch (IllegalArgumentException iae) {
-			throw new FunctionExecutionException("ERR.015.001.0042", QueryPlugin.Util.getString("ERR.015.001.0042" , //$NON-NLS-1$ //$NON-NLS-2$
-				iae.getMessage()));
-		}
-	}
-
-	//	================== Parse String TO date/time/timestamp  ==================
-	private static Date parseDateHelper(String date, String format)
-			throws FunctionExecutionException {
-		DateFormat df = new SimpleDateFormat(format);
-		try {
-			return df.parse(date);
-		} catch (ParseException e) {
-			throw new FunctionExecutionException("ERR.015.001.0043", QueryPlugin.Util.getString("ERR.015.001.0043" , //$NON-NLS-1$ //$NON-NLS-2$
-					date, format));
-		}
-	}
-	
-	public static Timestamp parseTimestamp(String timestamp, String format)
-		throws FunctionExecutionException {
-        return new Timestamp(parseDateHelper(timestamp, format).getTime());
-	}
-
-	//	================== Format number TO String ==================
-	public static String format(Number number, String format)
-	throws FunctionExecutionException {
-		try {
-	        DecimalFormat df = new DecimalFormat(format);
-	        return df.format(number);
-		} catch (IllegalArgumentException iae) {
-			throw new FunctionExecutionException("ERR.015.001.0042", QueryPlugin.Util.getString("ERR.015.001.0042" , //$NON-NLS-1$ //$NON-NLS-2$
-			iae.getMessage()));
-		}
-	}
-
-	//	================== Parse String TO numbers ==================
-	public static Object parseInteger(String number, String format)
-		throws FunctionExecutionException {
-		Number intNum = parseNumberHelper(number, format);
-		return new Integer(intNum.intValue());
-	}
-
-	public static Object parseLong(String number, String format)
-		throws FunctionExecutionException {
-		Number longNum = parseNumberHelper(number, format);
-		return new Long(longNum.longValue());
-	}
-
-	public static Object parseDouble(String number, String format)
-		throws FunctionExecutionException {
-		Number doubleNum = parseNumberHelper(number, format);
-		return new Double(doubleNum.doubleValue());
-	}
-
-	public static Object parseFloat(String number, String format)
-		throws FunctionExecutionException {
-		Number longNum = parseNumberHelper(number, format);
-		return new Float(longNum.floatValue());
-	}
-
-	public static Object parseBigInteger(String number, String format)
-		throws FunctionExecutionException {
-		Number bigIntegerNum = parseNumberHelper(number, format);
-		return new BigInteger(bigIntegerNum.toString());
-	}
-
-	public static Object parseBigDecimal(String number, String format)
-		throws FunctionExecutionException {
-		Number bigDecimalNum = parseNumberHelper(number, format);
-		return new BigDecimal(bigDecimalNum.toString());
-	}
-
-	// ============== Helper Function for format/parse numbers ==================
-
-	private static Number parseNumberHelper(String number, String format)
-		throws FunctionExecutionException {
-		DecimalFormat df= new DecimalFormat(format);
-		try {
-			return df.parse(number);
-		} catch (ParseException e) {
-			throw new FunctionExecutionException("ERR.015.001.0043", QueryPlugin.Util.getString("ERR.015.001.0043" , //$NON-NLS-1$ //$NON-NLS-2$
-					number,format));
-		}
-	}
-
-	// ================== Function - ACOS =====================
-	public static Object acos(Number number) {
-		return new Double(Math.acos(number.doubleValue()));
-	}
-
-	// ================== Function - ASIN =====================
-	public static Object asin(Number number) {
-		return new Double(Math.asin(number.doubleValue()));
-	}
-
-	// ================== Function - ATAN =====================
-	public static Object atan(Number number) {
-		return new Double(Math.atan(number.doubleValue()));
-	}
-
-	// ================== Function - ATAN2 =====================
-	public static Object atan2(Number number1, Number number2) {
-		return new Double(Math.atan2(number1.doubleValue(), number2.doubleValue()));
-	}
-
-	// ================== Function - COS =====================
-	public static Object cos(Number number) {
-		return new Double(Math.cos(number.doubleValue()));
-	}
-
-	// ================== Function - COT =====================
-	public static Object cot(Number number) {
-		return new Double(1/Math.tan(number.doubleValue()));
-	}
-
-	// ================== Function - DEGREES =====================
-	public static Object degrees(Number number) {
-		return new Double(Math.toDegrees(number.doubleValue()));
-	}
-
-	// ================== Function - PI =====================
-	public static Object pi() {
-		return new Double(Math.PI);
-	}
-
-	// ================== Function - RADIANS =====================
-	public static Object radians(Number number) {
-		return new Double(Math.toRadians(number.doubleValue()));
-	}
-
-	// ================== Function - SIN =====================
-	public static Object sin(Number number) {
-		return new Double(Math.sin(number.doubleValue()));
-	}
-
-	// ================== Function - TAN =====================
-	public static Object tan(Number number) {
-		return new Double(Math.tan(number.doubleValue()));
-	}
-
-    // ================== Function - BITAND =====================
-	public static Object bitand(int x, int y) {
-        return x & y;
-	}
-
-    // ================== Function - BITOR =====================
-    public static Object bitor(int x, int y) {
-        return x | y;
-    }
-
-    // ================== Function - BITXOR =====================
-    public static Object bitxor(int x, int y) {
-        return x ^ y;
-    }
-
-    // ================== Function - BITNOT =====================
-    public static int bitnot(int x) {
-        return x ^ 0xFFFFFFFF;
-    }
-
-    // ================= Function - USER ========================
-    public static Object user(CommandContext context) {
-        return context.getUserName();
-    }
-    
-    public static Object current_database(CommandContext context) {
-    	return context.getVdbName();
-    }
-
-    // ================= Function - COMMANDPAYLOAD ========================
-    public static Object commandPayload(CommandContext context) {
-        Serializable payload = context.getCommandPayload();
-        if(payload == null) {
-            return null;
-        }
-        // 0-arg form - just return payload as a string if it exists
-        return payload.toString();
-    }
-
-    public static Object commandPayload(CommandContext context, String param) 
-        throws ExpressionEvaluationException, FunctionExecutionException{
-        Serializable payload = context.getCommandPayload();
-        if(payload == null) {
-            return null;
-        }
-        
-        // 1-arg form - assume payload is a Properties object
-        if(payload instanceof Properties) {
-            return ((Properties)payload).getProperty(param);
-        }            
-        // Payload was bad
-        throw new ExpressionEvaluationException(QueryPlugin.Util.getString("ExpressionEvaluator.Expected_props_for_payload_function", "commandPayload", payload.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    // ================= Function - ENV ========================
-    public static Object env(CommandContext context, String propertyName) {
-        // All context property keys must be lowercase - we lowercase the incoming key here to match regardless of case
-        String propertyNameNocase = propertyName.toLowerCase();
-        Properties envProps = context.getEnvironmentProperties();
-        if(envProps != null && envProps.containsKey(propertyNameNocase)) {
-            return envProps.getProperty(propertyNameNocase);
-        }
-        String value = System.getProperty(propertyName);
-        if (value == null) {
-            value = System.getProperty(propertyNameNocase);
-        }
-        return value;            
-    }
-    
-    public static Object session_id(CommandContext context) {
-        return context.getConnectionID();
-    }
-    
-    // ================= Function - MODIFYTIMEZONE ========================
-    
-    public static Object modifyTimeZone(Timestamp value, String originalTimezoneString, String targetTimezoneString) {
-        TimeZone originalTimeZone = TimeZone.getTimeZone(originalTimezoneString);
-        TimeZone dbmsTimeZone = TimeZone.getTimeZone(targetTimezoneString);
-
-        // Check that the dbms time zone is really different than the local time zone
-        if (originalTimeZone.equals(dbmsTimeZone)) {
-            return value;
-        }
-
-        Calendar cal = Calendar.getInstance(dbmsTimeZone);
-        
-        return TimestampWithTimezone.createTimestamp(value, originalTimeZone, cal);
-    }
-
-    public static Object modifyTimeZone(CommandContext context, Timestamp value, String targetTimezoneString) {
-        TimeZone dbmsTimeZone = TimeZone.getTimeZone(targetTimezoneString);
-
-        Calendar cal = Calendar.getInstance(dbmsTimeZone);
-        
-        return TimestampWithTimezone.createTimestamp(value, context.getServerTimeZone(), cal);
-    } 
-    
-    public static Clob toChars(BlobType value, String encoding) {
-    	Charset cs = getCharset(encoding);
-		BlobInputStreamFactory bisf = new BlobInputStreamFactory(value.getReference());
-    	ClobImpl clob = new ClobImpl(bisf, -1);
-    	clob.setCharset(cs);
-    	return new ClobType(clob);
-    }
-    
-    public static Blob toBytes(ClobType value, String encoding) throws IOException {
-    	Charset cs = getCharset(encoding);
-    	ClobInputStreamFactory cisf = new ClobInputStreamFactory(value.getReference());
-    	cisf.setCharset(cs);
-    	if (CharsetUtils.BASE64_NAME.equalsIgnoreCase(encoding) || CharsetUtils.HEX_NAME.equalsIgnoreCase(encoding)) {
-    		//validate that the binary conversion is possible
-    		//TODO: cache the result in a filestore
-    		InputStream is = cisf.getInputStream();
-    		try {
-	    		while (is.read() != -1) {
-	    			
-	    		}
-    		} finally {
-    			is.close();
-    		}
-    	}
-    	return new BlobType(new BlobImpl(cisf));
-	}
-    
-    public static Charset getCharset(String encoding) {
-    	if (CharsetUtils.BASE64_NAME.equalsIgnoreCase(encoding)) {
-    		return CharsetUtils.BASE64;
-    	}
-    	if (CharsetUtils.HEX_NAME.equalsIgnoreCase(encoding)) {
-    		return CharsetUtils.HEX;
-    	}
-    	return Charset.forName(encoding);
-	}
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java (from rev 2764, trunk/engine/src/main/java/org/teiid/query/function/FunctionMethods.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1378 @@
+/*
+ * 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.function;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.math.RoundingMode;
+import java.nio.charset.Charset;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.DateFormat;
+import java.text.DecimalFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+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.TransformationException;
+import org.teiid.core.types.InputStreamFactory.BlobInputStreamFactory;
+import org.teiid.core.types.InputStreamFactory.ClobInputStreamFactory;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.util.CommandContext;
+
+/**
+ * Static method hooks for most of the function library.
+ */
+public final class FunctionMethods {
+
+	// ================== Function = plus =====================
+
+	public static int plus(int x, int y) {
+		return x + y;
+	}
+	
+	public static long plus(long x, long y) {
+		return x + y;
+	}
+	
+	public static float plus(float x, float y) {
+		return x + y;
+	}
+	
+	public static double plus(double x, double y) {
+		return x + y;
+	}
+	
+	public static Object plus(BigInteger x, BigInteger y) {
+		return x.add(y);
+	}
+	
+	public static Object plus(BigDecimal x, BigDecimal y) {
+		return x.add(y);
+	}
+
+	// ================== Function = minus =====================
+
+	public static int minus(int x, int y) {
+		return x - y;
+	}
+	
+	public static long minus(long x, long y) {
+		return x - y;
+	}
+	
+	public static float minus(float x, float y) {
+		return x - y;
+	}
+	
+	public static double minus(double x, double y) {
+		return x - y;
+	}
+	
+	public static Object minus(BigInteger x, BigInteger y) {
+		return x.subtract(y);
+	}
+	
+	public static Object minus(BigDecimal x, BigDecimal y) {
+		return x.subtract(y);
+	}
+
+	// ================== Function = multiply =====================
+
+	public static int multiply(int x, int y) {
+		return x * y;
+	}
+	
+	public static long multiply(long x, long y) {
+		return x * y;
+	}
+	
+	public static float multiply(float x, float y) {
+		return x * y;
+	}
+	
+	public static double multiply(double x, double y) {
+		return x * y;
+	}
+	
+	public static Object multiply(BigInteger x, BigInteger y) {
+		return x.multiply(y);
+	}
+	
+	public static Object multiply(BigDecimal x, BigDecimal y) {
+		return x.multiply(y);
+	}
+
+	// ================== Function = divide =====================
+
+	public static int divide(int x, int y) {
+		return x / y;
+	}
+	
+	public static long divide(long x, long y) {
+		return x / y;
+	}
+	
+	public static float divide(float x, float y) {
+		return x / y;
+	}
+	
+	public static double divide(double x, double y) {
+		return x / y;
+	}
+	
+	public static Object divide(BigInteger x, BigInteger y) {
+		return x.divide(y);
+	}
+	
+	public static Object divide(BigDecimal x, BigDecimal y) {
+		BigDecimal bd = x.divide(y, Math.max(16, x.scale() + y.precision() + 1), RoundingMode.HALF_UP).stripTrailingZeros();
+		return bd.setScale(Math.max(x.scale(), bd.scale()));
+	}
+
+	// ================== Function = abs =====================
+
+	public static int abs(int x) {
+		return Math.abs(x);
+	}
+	
+	public static long abs(long x) {
+		return Math.abs(x);
+	}
+	
+	public static float abs(float x) {
+		return Math.abs(x);
+	}
+	
+	public static double abs(double x) {
+		return Math.abs(x);
+	}
+	
+	public static Object abs(BigInteger x) {
+		return x.abs();
+	}
+	
+	public static Object abs(BigDecimal x) {
+		return x.abs();
+	}
+
+	// ================== Function = ceiling =====================
+
+	public static Object ceiling(Number x) {
+		return new Double(Math.ceil(x.doubleValue()));
+	}
+
+	// ================== Function = exp =====================
+
+	public static Object exp(Number x) {
+		return new Double(Math.exp(x.doubleValue()));
+	}
+
+	// ================== Function = floor =====================
+
+	public static  Object floor(Number x) {
+		return new Double(Math.floor(x.doubleValue()));
+	}
+
+	// ================== Function = log =====================
+
+	public static  Object log(Number x) {
+		return new Double(Math.log(x.doubleValue()));
+	}
+
+	// ================== Function = log10 =====================
+
+	private static final double log10baseE = Math.log(10);
+
+	public static Object log10(Number x) {
+		return new Double( Math.log(x.doubleValue()) / log10baseE);
+	}
+    
+    // ================== Function = rand=====================
+    
+    public static Object rand(CommandContext context, Object seed) throws FunctionExecutionException {        
+        if(context != null) {
+            if(seed == null) {
+                return new Double(context.getNextRand());
+            } else if(seed instanceof Integer) {
+                return new Double(context.getNextRand(((Integer)seed).longValue()));
+            }
+        }
+        throw new FunctionExecutionException("ERR.015.001.0069", QueryPlugin.Util.getString("ERR.015.001.0069", "rand", seed)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$        
+    }
+        
+    public static Object rand(CommandContext context) throws FunctionExecutionException {
+        if(context != null) {
+            return new Double(context.getNextRand());
+        }
+        throw new FunctionExecutionException("ERR.015.001.0069", QueryPlugin.Util.getString("ERR.015.001.0069", "rand")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+	// ================== Function = mod =====================
+
+	public static int mod(int x, int y) {
+		return x % y;
+	}
+	
+	public static long mod(long x, long y) {
+		return x % y;
+	}
+	
+	public static float mod(float x, float y) {
+		return x % y;
+	}
+	
+	public static double mod(double x, double y) {
+		return x % y;
+	}
+	
+	public static Object mod(BigInteger x, BigInteger y) {
+		return x.remainder(y);
+	}
+	
+	public static Object mod(BigDecimal x, BigDecimal y) {
+		return x.remainder(y);
+	}
+    
+	// ================== Function = power =====================
+	
+	public static double power(double x, double y) {
+		return Math.pow(x, y);
+	}
+	
+	public static BigInteger power(BigInteger x, int y) {
+		return x.pow(y);
+	}
+	
+	public static BigDecimal power(BigDecimal x, int y) {
+		return x.pow(y);
+	}
+
+    public static int round(int number, int places) {
+        if(places < 0){
+        	return round(new BigDecimal(number), places).intValue();
+        }
+        return number;
+    }
+    
+    public static float round(float number, int places) {
+    	return round(new BigDecimal(number), places).floatValue();
+    }
+    
+    public static double round(double number, int places) {
+    	return round(new BigDecimal(number), places).doubleValue();
+    }
+    
+    public static BigDecimal round(BigDecimal bigDecimalNumber, int places) {
+        int scale = bigDecimalNumber.scale();
+        if (scale <= places) {
+        	return bigDecimalNumber;
+        }
+        bigDecimalNumber = bigDecimalNumber.setScale(places,BigDecimal.ROUND_HALF_UP);
+        return bigDecimalNumber.setScale(scale,BigDecimal.ROUND_HALF_UP);
+    }
+
+	// ================== Function = sign =====================
+
+	public static Object sign(int x) {
+		return Integer.signum(x);
+	}
+	
+	public static Object sign(long x) {
+		return Long.signum(x);
+	}
+
+	public static Object sign(float x) {
+		return Math.signum(x);
+	}
+	
+	public static Object sign(double x) {
+		return Math.signum(x);
+	}
+	
+	public static Object sign(BigInteger x) {
+		return new Integer(x.signum());
+	}
+	
+	public static Object sign(BigDecimal x) {
+		return new Integer(x.signum());
+	}
+
+	// ================== Function = sqrt =====================
+
+
+	public static  Object sqrt(Number x) {
+		return new Double( Math.sqrt(x.doubleValue()));
+	}
+
+	// ================== Function = currentDate =====================
+
+	public static  Object currentDate() {
+		return TimestampWithTimezone.createDate(new Date());
+	}
+
+	// ================== Function = currentTime =====================
+
+	public static  Object currentTime() {
+		return TimestampWithTimezone.createTime(new Date());
+	}
+
+	// ================== Function = currentTimestamp =====================
+
+	public static  Object currentTimestamp() {
+		return new Timestamp(System.currentTimeMillis());
+	}
+
+	// ================== Helper for a bunch of date functions =====================
+
+	private static int getField(java.util.Date date, int field) {
+		Calendar cal = TimestampWithTimezone.getCalendar();
+		cal.setTime(date);
+
+		return cal.get(field);
+	}
+
+	// ================== Function = dayname =====================
+
+	static final String[] dayNames = new String[] {
+		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+
+	public static Object dayName(Date x) {
+		return dayNames[getField(x, Calendar.DAY_OF_WEEK) - 1];
+	}
+
+	// ================== Function = dayofmonth =====================
+
+	public static  Object dayOfMonth(Date x) {
+		return Integer.valueOf(getField(x, Calendar.DATE));
+	}
+
+	// ================== Function = dayofweek =====================
+
+	public static Object dayOfWeek(Date x) {
+		return Integer.valueOf(getField(x, Calendar.DAY_OF_WEEK));
+	}
+
+	// ================== Function = dayofyear =====================
+
+	public static Object dayOfYear(Date x) {
+		return Integer.valueOf(getField(x, Calendar.DAY_OF_YEAR));
+	}
+
+	// ================== Function = hour =====================
+
+	public static Object hour(Date x) {
+		return Integer.valueOf(getField(x, Calendar.HOUR_OF_DAY));
+	}
+
+	// ================== Function = minute =====================
+
+	public static Object minute(Date x) {
+		return Integer.valueOf(getField(x, Calendar.MINUTE));
+	}
+
+	// ================== Function = month =====================
+
+	public static Object month(Date x) {
+		return Integer.valueOf(getField(x, Calendar.MONTH)+1);
+	}
+
+	// ================== Function = monthname =====================
+
+	static final String[] monthNames = new String[] {
+		"January", "February", "March", "April", "May", "June", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+		"July", "August", "September", "October", "November", "December" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+
+	public static Object monthName(Date x) {
+		return monthNames[getField(x, Calendar.MONTH)];
+	}
+
+	// ================== Function = second =====================
+
+	public static Object second(Date x) {
+		return Integer.valueOf(getField(x, Calendar.SECOND));
+	}
+
+	// ================== Function = week =====================
+
+	public static Object week(Date x) {
+		return Integer.valueOf(getField(x, Calendar.WEEK_OF_YEAR));
+	}
+
+	// ================== Function = year =====================
+
+	public static Object year(Date x) {
+		return Integer.valueOf(getField(x, Calendar.YEAR));
+	}
+
+	// ================== Function = quarter =====================
+
+	public static Object quarter(Date date)
+		throws FunctionExecutionException {
+		int month = getField(date, Calendar.MONTH);
+		
+		if (month > 11) {
+			throw new FunctionExecutionException("ERR.015.001.0066", QueryPlugin.Util.getString("ERR.015.001.0066", //$NON-NLS-1$ //$NON-NLS-2$
+					new Object[] {"quarter", date.getClass().getName()})); //$NON-NLS-1$
+		}
+		return Integer.valueOf(month/3 + 1);
+	}
+
+	//	================== Function = timestampadd =====================
+
+	public static Object timestampAdd(String intervalType, Integer count, Timestamp timestamp) {
+		Calendar cal = TimestampWithTimezone.getCalendar();
+
+		int nanos = timestamp.getNanos();
+		cal.setTime(timestamp);
+
+		// case of interval = 1, fractional seconds (nanos), don't go to branches of addField()
+		if (intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
+			int countValue = count.intValue();
+			nanos += countValue;
+
+			// Handle the case of nanos > 999,999,999 and increase the second.
+			// Since the count number is an interger, so the maximum is definite,
+			// and nanos/999,999,999 can at most be added to second
+			if ( nanos > 999999999) {
+				int addSecond = nanos / 999999999;
+				int leftNanos = nanos % 999999999;
+				cal.add(Calendar.SECOND, addSecond);
+
+				Timestamp ts = new Timestamp(cal.getTime().getTime());
+				ts.setNanos(leftNanos);
+				return ts;
+			} 
+            // nanos <= 999,999,999
+			Timestamp ts = new Timestamp(cal.getTime().getTime());
+			ts.setNanos(nanos);
+			return ts;
+		}
+        // for interval from 2 to 9
+		addField(intervalType, count, cal);
+		Timestamp ts = new Timestamp(cal.getTime().getTime());
+
+		//rectify returned timestamp with original nanos
+		ts.setNanos(nanos);
+		return ts;
+	}
+	
+	/** Helper method for timestampAdd method
+	 * @param interval Integer
+	 * @param count Integer
+	 * @param cal Calendar instance
+	 */
+	private static void addField(String interval, Integer count, Calendar cal) {
+		int countValue = count.intValue();
+
+        if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
+            //nano seconds - should never get into this branch
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
+            cal.add(Calendar.SECOND, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
+            cal.add(Calendar.MINUTE, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
+            cal.add(Calendar.HOUR_OF_DAY, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
+            cal.add(Calendar.DAY_OF_YEAR, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
+            cal.add(Calendar.WEEK_OF_YEAR, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
+            cal.add(Calendar.MONTH, countValue);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
+            cal.add(Calendar.MONTH, countValue*3);
+        } else if(interval.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
+            cal.add(Calendar.YEAR, countValue);
+        }
+	}
+
+	//	================== Function = timestampdiff =====================
+
+	/**
+     * This method truncates (ignores) figures
+     * @param interval
+     * @param timestamp1
+     * @param timestamp2
+     * @return
+     * @throws FunctionExecutionException
+     */
+    public static Object timestampDiff(String intervalType, Timestamp ts1Obj, Timestamp ts2Obj)  {
+        long ts1 = ts1Obj.getTime() / 1000 * 1000000000 + ts1Obj.getNanos();
+        long ts2 = ts2Obj.getTime() / 1000 * 1000000000 + ts2Obj.getNanos();
+        
+        long tsDiff = ts2 - ts1;
+
+        long count = 0;
+        if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_FRAC_SECOND)) {
+            count = tsDiff;
+        } else { 
+        	tsDiff = tsDiff / 1000000; //convert to milliseconds
+            if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_SECOND)) {
+                count = tsDiff / 1000;
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MINUTE)) {
+                count = (tsDiff / 1000) / 60;
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_HOUR)) {
+                count = (tsDiff / 1000) / (60*60);
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_DAY)) {
+                count = (tsDiff / 1000) / (60*60*24);
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_WEEK)) {
+                count = (tsDiff / 1000) / (60*60*24*7);
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_MONTH)) {
+                count = (tsDiff / 1000) / (60*60*24*30);
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_QUARTER)) {
+                count = (tsDiff / 1000) / (60*60*24*91);
+            } else if(intervalType.equalsIgnoreCase(NonReserved.SQL_TSI_YEAR)) {
+                count = (tsDiff / 1000) / (60*60*24*365);
+            }    
+        }
+        return new Long(count);
+	}
+
+    //  ================== Function = timestampcreate =====================
+
+    /**
+     * This method truncates (ignores) figures
+     * @param interval
+     * @param timestamp1
+     * @param timestamp2
+     * @return
+     * @throws FunctionExecutionException
+     */
+    public static Object timestampCreate(java.sql.Date date, Time time) {
+        Calendar tsCal = TimestampWithTimezone.getCalendar();
+        tsCal.setTime(time);
+        int hour = tsCal.get(Calendar.HOUR_OF_DAY);
+        int minute = tsCal.get(Calendar.MINUTE);
+        int second = tsCal.get(Calendar.SECOND);
+        
+        tsCal.setTime(date);
+        
+        tsCal.set(Calendar.HOUR_OF_DAY, hour);
+        tsCal.set(Calendar.MINUTE, minute);
+        tsCal.set(Calendar.SECOND, second);
+
+        return new Timestamp(tsCal.getTime().getTime());
+    }
+
+	// ================== Function = length =====================
+
+	public static Object length(String str) {
+		return new Integer(str.length());
+	}
+
+	// ================== Function = concat =====================
+
+	public static Object concat(String str1, String str2) {
+		return str1 + str2;
+	}
+
+	// ================== Function = substring =====================
+
+	public static Object substring(String string, Integer startVal, Integer lengthVal) {
+		if (startVal < 0) {
+        	startVal = string.length() + startVal;
+        } else if (startVal > 0){
+            startVal--;     // Adjust to 1-based
+        }
+		
+		if(startVal < 0 || startVal >= string.length()) {
+		    return null;
+		}
+
+		if(lengthVal < 0) {
+		    return null;
+		}
+
+		int endVal = Math.min(startVal+lengthVal, string.length());
+
+		return string.substring(startVal, endVal);
+	}
+
+    public static Object substring(String string, Integer start) {
+        int startVal = start.intValue();
+        return substring(string, startVal, string.length());
+    }
+
+	// ================== Function = left =====================
+
+	public static Object left(String string, Integer count)
+		throws FunctionExecutionException {
+		int countValue = count.intValue();
+        if(countValue < 0) {
+            throw new FunctionExecutionException("ERR.015.001.0017", QueryPlugin.Util.getString("ERR.015.001.0017", countValue)); //$NON-NLS-1$ //$NON-NLS-2$
+        } 
+        if(string.length() < countValue) {
+            return string;
+        }
+        return string.substring(0, countValue);
+	}
+
+	// ================== Function = right =====================
+
+	public static Object right(String string, Integer count) 
+		throws FunctionExecutionException {
+		int countValue = count.intValue();
+        if(countValue < 0) {
+            throw new FunctionExecutionException("ERR.015.001.0017", QueryPlugin.Util.getString("ERR.015.001.0017", countValue)); //$NON-NLS-1$ //$NON-NLS-2$
+        } else if(string.length() < countValue) {
+            return string;
+		} else {
+			return string.substring(string.length() - countValue);
+        }
+	}
+
+	// ================== Function = lowercase =====================
+
+	public static Object lowerCase(String str) {
+		return str.toLowerCase();
+	}
+
+	// ================== Function = uppercase =====================
+
+	public static Object upperCase(String str) {
+		return str.toUpperCase();
+	}
+
+	// ================== Function = locate =====================
+
+	public static Object locate(String sub, String str) {
+		return locate(sub, str, 1);
+	}
+
+	/**
+	 * TODO: The treatment of negative start indexes is inconsistent here.
+	 * We're treating the null value like Derby, but not throwing an
+	 * exception if the value is less than 1 (less than 0 in DB2).
+	 */
+	public static Object locate(String sub, String str, Integer start) {
+		if(str == null || sub == null) {
+			return null;
+		} 
+		if (start == null) {
+			start = 1;
+		}
+		return new Integer(str.indexOf(sub, start.intValue() - 1) + 1);
+	}
+
+	// ================== Function = lefttrim =====================
+
+	private static final char SPACE = ' ';
+
+	public static Object leftTrim(String string) {
+		for(int i=0; i<string.length(); i++) {
+			if(string.charAt(i) != SPACE) {
+				// end of trim, return what's left
+				return string.substring(i);
+			}
+		}
+
+		// All spaces, so trim it all
+		return ""; //$NON-NLS-1$
+	}
+
+	// ================== Function = righttrim =====================
+
+	public static Object rightTrim(String string) {
+		for(int i=string.length()-1; i>=0; i--) {
+			if(string.charAt(i) != SPACE) {
+				// end of trim, return what's left
+				return string.substring(0, i+1);
+			}
+		}
+
+		// All spaces, so trim it all
+		return ""; //$NON-NLS-1$
+	}
+
+	// ================== Function = replace =====================
+
+	public static Object replace(String string, String subString, String replaceString) {
+		// Check some simple cases that require no work
+		if(subString.length() > string.length() || string.length() == 0 || subString.length() == 0) {
+			return string;
+		}
+
+		StringBuffer result = new StringBuffer();
+		int index = 0;
+
+		while(true) {
+			int newIndex = string.indexOf(subString, index);
+			if(newIndex < 0) {
+				// No more replacement sections, grab from old index to end of string
+				result.append( string.substring(index) );
+
+				// Break out of loop
+				break;
+
+			}
+			// Matched the substring at newIndex
+
+			// First append section from old index to new
+			result.append( string.substring( index, newIndex) );
+
+			// Then append replacement section for sub
+			result.append( replaceString );
+
+			// Then move the index counter forward
+			index = newIndex + subString.length();
+		}
+
+		return result.toString();
+	}
+
+	// ================== Function = insert =====================
+
+	public static Object insert(String string1, Integer start, Integer length, String str2)
+		throws FunctionExecutionException {
+		int startValue = start.intValue();
+		int len = length.intValue();
+
+		// Check some invalid cases
+		if(startValue < 1 || (startValue-1) > string1.length()) {
+			throw new FunctionExecutionException("ERR.015.001.0061", QueryPlugin.Util.getString("ERR.015.001.0061", start, string1)); //$NON-NLS-1$ //$NON-NLS-2$
+		} else if (len < 0) {
+			throw new FunctionExecutionException("ERR.015.001.0062", QueryPlugin.Util.getString("ERR.015.001.0062", len)); //$NON-NLS-1$ //$NON-NLS-2$
+		} else if (string1.length() == 0 && (startValue > 1 || len >0) ) {
+			throw new FunctionExecutionException("ERR.015.001.0063", QueryPlugin.Util.getString("ERR.015.001.0063")); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+
+		StringBuffer result = new StringBuffer();
+		result.append(string1.substring(0, startValue-1));
+		int endValue = startValue + len - 1;
+
+		// str2.length() = 0 is a valid case
+		if (endValue > string1.length()) {
+			result.append(str2);
+		} else {
+			result.append(str2);
+			result.append(string1.substring( endValue ));
+		}
+
+		return result.toString();
+	}
+
+	// ================== Function = repeat =====================
+	public static Object repeat(String str, Integer count) {
+		int repeatCount = count.intValue();
+		StringBuffer result = new StringBuffer();
+
+		for (int i = 0; i < repeatCount && result.length() <= DataTypeManager.MAX_STRING_LENGTH; i++) {
+			result.append(str);
+		}
+		return result.toString();
+	}
+
+    // ================== Function = ascii =====================
+
+    public static Integer ascii(String ch) {
+        if(ch.length() == 0) {
+        	return null;
+        } 
+        return (int)ch.charAt(0);
+    }
+    
+    public static Integer ascii(Character ch) {
+        return (int)ch.charValue();
+    }
+
+    // ================== Function = chr =====================
+
+    public static Object chr(int intValue) {
+        return new Character((char) intValue);
+    }
+
+    // ================== Function = initCap =====================
+
+    public static Object initCap(String s) {
+        StringBuffer cap = new StringBuffer();
+
+        boolean checkCap = true;
+        for(int i=0; i<s.length(); i++) {
+            char c = s.charAt(i);
+
+            // Decide whether to upper case
+            if(checkCap) {
+                cap.append(Character.toUpperCase(c));
+            } else {
+                cap.append(Character.toLowerCase(c));
+            }
+
+            // Reset flag for next character
+            checkCap = Character.isWhitespace(c);
+        }
+        return cap.toString();
+    }
+
+    // ================== Function = lpad =====================
+
+    public static Object lpad(String inputString, Integer padLength, String padStr)
+        throws FunctionExecutionException {
+
+    	return pad(inputString, padLength, padStr, true);
+    }
+
+    public static Object pad(String str, Integer padLength, String padStr, boolean left)
+    throws FunctionExecutionException {
+	    int length = padLength.intValue();
+	    if(length < 1) {
+	        throw new FunctionExecutionException("ERR.015.001.0025", QueryPlugin.Util.getString("ERR.015.001.0025")); //$NON-NLS-1$ //$NON-NLS-2$
+	    }
+	    if(length < str.length()) {
+	        return str.substring(0, length);
+	    }
+	    if(length > DataTypeManager.MAX_STRING_LENGTH) {
+	    	length = DataTypeManager.MAX_STRING_LENGTH;
+	    }
+	    // Get pad character
+	    if(padStr.length() == 0) {
+	        throw new FunctionExecutionException("ERR.015.001.0027", QueryPlugin.Util.getString("ERR.015.001.0027")); //$NON-NLS-1$ //$NON-NLS-2$
+	    }
+	    // Pad string
+	    StringBuffer outStr = new StringBuffer(str);
+	    while(outStr.length() < length) {
+	    	if (left) {
+	    		outStr.insert(0, padStr);
+	    	} else {
+	    		outStr.append(padStr);
+	    	}
+	    }
+	    if (left) {
+	    	return outStr.substring(outStr.length() - length);
+	    }
+	    return outStr.substring(0, length);
+	}
+
+    
+    public static final String SPACE_CHAR = " "; //$NON-NLS-1$
+
+    public static Object lpad(String inputString, Integer padLength)
+        throws FunctionExecutionException {
+
+        return lpad(inputString, padLength, SPACE_CHAR);
+    }
+
+    // ================== Function = rpad =====================
+
+    public static Object rpad(String inputString, Integer padLength, String padStr)
+        throws FunctionExecutionException {
+
+    	return pad(inputString, padLength, padStr, false);
+    }
+
+    public static Object rpad(String inputString, Integer padLength)
+        throws FunctionExecutionException {
+
+        return rpad(inputString, padLength, SPACE_CHAR);
+    }
+
+    // ================== Function = translate =====================
+
+    public static Object translate(String str, String in, String out)
+        throws FunctionExecutionException {
+        if(in.length() != out.length()) {
+            throw new FunctionExecutionException("ERR.015.001.0031", QueryPlugin.Util.getString("ERR.015.001.0031")); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+
+        if(in.length() == 0 || str.length() == 0) {
+            return str;
+        }
+
+        StringBuffer translated = new StringBuffer(str.length());
+        for(int i=0; i<str.length(); i++) {
+            char c = str.charAt(i);
+            boolean matched = false;
+            for(int j=0; j<in.length(); j++) {
+                char inChar = in.charAt(j);
+                if(c == inChar) {
+                    translated.append(out.charAt(j));
+                    matched = true;
+                    break;
+                }
+            }
+            if(! matched) {
+                translated.append(c);
+            }
+        }
+        return translated.toString();
+    }
+
+	// ================== Function = convert =====================
+
+	@SuppressWarnings("unchecked")
+	public static Object convert(Object src, String type)
+		throws FunctionExecutionException {
+		try {
+			return DataTypeManager.transformValue(src, DataTypeManager.getDataTypeClass(type));
+		} catch(TransformationException e) {
+			throw new FunctionExecutionException(e, "ERR.015.001.0033", QueryPlugin.Util.getString("ERR.015.001.0033", new Object[]{src, DataTypeManager.getDataTypeName(src.getClass()), type})); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+
+    // ================== Function = context and rowlimit =====================
+
+    /**
+     * This function should never actually be called - it is here solely so the
+     * xml context function can be resolved properly.  The actual function is
+     * implemented in the XML planner.
+     * @param context The context to apply the criteria in
+     * @param expression The expression on the left side of the criteria
+     * @return Same as expression
+     */
+    public static Object context(Object context, Object expression)
+        throws FunctionExecutionException {
+
+        throw new FunctionExecutionException("ERR.015.001.0035", QueryPlugin.Util.getString("ERR.015.001.0035")); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /**
+     * This pseudo-function should never actually be called - it is here solely so the
+     * xml rowlimit function can be resolved properly.  The actual functionality is
+     * implemented in the XML planner/processor.
+     * @param expression The expression on the left side of the criteria, an xml node
+     * @return doesn't really return anything; this pseudo-function is used to control
+     * the number of rows returned from a mapping class.
+     */
+    public static Object rowlimit(Object expression)
+        throws FunctionExecutionException {
+    
+        throw new FunctionExecutionException("ERR.015.001.0035a", QueryPlugin.Util.getString("ERR.015.001.0035a")); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    /**
+     * This pseudo-function should never actually be called - it is here solely so the
+     * xml rowlimitexception function can be resolved properly.  The actual functionality is
+     * implemented in the XML planner/processor.
+     * @param expression The expression on the left side of the criteria, an xml node
+     * @return doesn't really return anything; this pseudo-function is used to control
+     * the number of rows returned from a mapping class.
+     */
+    public static Object rowlimitexception(Object expression)
+        throws FunctionExecutionException {
+    
+        throw new FunctionExecutionException("ERR.015.001.0035a", QueryPlugin.Util.getString("ERR.015.001.0035a")); //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    // ================== Function = lookup =====================
+
+    /**
+     * This function should never actually be called - it is here solely so the
+     * lookup function can be resolved properly.  The actual function is
+     * implemented in the ExpresionEvaluator
+     * @param context The context to apply the criteria in
+     * @param expression The expression on the left side of the criteria
+     * @return Same as expression
+     */
+    public static Object lookup(Object codeTable, Object returnElement, Object keyElement, Object keyValue) {
+
+        throw new UnsupportedOperationException("This method should never be called."); //$NON-NLS-1$
+    }
+	
+    // ================== Function = nvl =====================
+    
+    public static Object ifnull(Object value, Object ifNullValue) {
+    	return coalesce(value, ifNullValue);
+    }
+    
+    public static Object coalesce(Object value, Object value1, Object... other) {
+    	if (value != null) {
+    		return value;
+    	}
+    	if (value1 != null) {
+    		return value1;
+    	}
+        for (Object object : other) {
+			if (object != null) {
+				return object;
+			}
+		}
+        return null;
+    }
+
+	// ================== Format date/time/timestamp TO String ==================
+	public static String format(Date date, String format)
+		throws FunctionExecutionException {
+		try {
+            SimpleDateFormat sdf = new SimpleDateFormat(format);
+            return sdf.format(date);
+		} catch (IllegalArgumentException iae) {
+			throw new FunctionExecutionException("ERR.015.001.0042", QueryPlugin.Util.getString("ERR.015.001.0042" , //$NON-NLS-1$ //$NON-NLS-2$
+				iae.getMessage()));
+		}
+	}
+
+	//	================== Parse String TO date/time/timestamp  ==================
+	private static Date parseDateHelper(String date, String format)
+			throws FunctionExecutionException {
+		DateFormat df = new SimpleDateFormat(format);
+		try {
+			return df.parse(date);
+		} catch (ParseException e) {
+			throw new FunctionExecutionException("ERR.015.001.0043", QueryPlugin.Util.getString("ERR.015.001.0043" , //$NON-NLS-1$ //$NON-NLS-2$
+					date, format));
+		}
+	}
+	
+	public static Timestamp parseTimestamp(String timestamp, String format)
+		throws FunctionExecutionException {
+        return new Timestamp(parseDateHelper(timestamp, format).getTime());
+	}
+
+	//	================== Format number TO String ==================
+	public static String format(Number number, String format)
+	throws FunctionExecutionException {
+		try {
+	        DecimalFormat df = new DecimalFormat(format);
+	        return df.format(number);
+		} catch (IllegalArgumentException iae) {
+			throw new FunctionExecutionException("ERR.015.001.0042", QueryPlugin.Util.getString("ERR.015.001.0042" , //$NON-NLS-1$ //$NON-NLS-2$
+			iae.getMessage()));
+		}
+	}
+
+	//	================== Parse String TO numbers ==================
+	public static Object parseInteger(String number, String format)
+		throws FunctionExecutionException {
+		Number intNum = parseNumberHelper(number, format);
+		return new Integer(intNum.intValue());
+	}
+
+	public static Object parseLong(String number, String format)
+		throws FunctionExecutionException {
+		Number longNum = parseNumberHelper(number, format);
+		return new Long(longNum.longValue());
+	}
+
+	public static Object parseDouble(String number, String format)
+		throws FunctionExecutionException {
+		Number doubleNum = parseNumberHelper(number, format);
+		return new Double(doubleNum.doubleValue());
+	}
+
+	public static Object parseFloat(String number, String format)
+		throws FunctionExecutionException {
+		Number longNum = parseNumberHelper(number, format);
+		return new Float(longNum.floatValue());
+	}
+
+	public static Object parseBigInteger(String number, String format)
+		throws FunctionExecutionException {
+		Number bigIntegerNum = parseNumberHelper(number, format);
+		return new BigInteger(bigIntegerNum.toString());
+	}
+
+	public static Object parseBigDecimal(String number, String format)
+		throws FunctionExecutionException {
+		Number bigDecimalNum = parseNumberHelper(number, format);
+		return new BigDecimal(bigDecimalNum.toString());
+	}
+
+	// ============== Helper Function for format/parse numbers ==================
+
+	private static Number parseNumberHelper(String number, String format)
+		throws FunctionExecutionException {
+		DecimalFormat df= new DecimalFormat(format);
+		try {
+			return df.parse(number);
+		} catch (ParseException e) {
+			throw new FunctionExecutionException("ERR.015.001.0043", QueryPlugin.Util.getString("ERR.015.001.0043" , //$NON-NLS-1$ //$NON-NLS-2$
+					number,format));
+		}
+	}
+
+	// ================== Function - ACOS =====================
+	public static Object acos(Number number) {
+		return new Double(Math.acos(number.doubleValue()));
+	}
+
+	// ================== Function - ASIN =====================
+	public static Object asin(Number number) {
+		return new Double(Math.asin(number.doubleValue()));
+	}
+
+	// ================== Function - ATAN =====================
+	public static Object atan(Number number) {
+		return new Double(Math.atan(number.doubleValue()));
+	}
+
+	// ================== Function - ATAN2 =====================
+	public static Object atan2(Number number1, Number number2) {
+		return new Double(Math.atan2(number1.doubleValue(), number2.doubleValue()));
+	}
+
+	// ================== Function - COS =====================
+	public static Object cos(Number number) {
+		return new Double(Math.cos(number.doubleValue()));
+	}
+
+	// ================== Function - COT =====================
+	public static Object cot(Number number) {
+		return new Double(1/Math.tan(number.doubleValue()));
+	}
+
+	// ================== Function - DEGREES =====================
+	public static Object degrees(Number number) {
+		return new Double(Math.toDegrees(number.doubleValue()));
+	}
+
+	// ================== Function - PI =====================
+	public static Object pi() {
+		return new Double(Math.PI);
+	}
+
+	// ================== Function - RADIANS =====================
+	public static Object radians(Number number) {
+		return new Double(Math.toRadians(number.doubleValue()));
+	}
+
+	// ================== Function - SIN =====================
+	public static Object sin(Number number) {
+		return new Double(Math.sin(number.doubleValue()));
+	}
+
+	// ================== Function - TAN =====================
+	public static Object tan(Number number) {
+		return new Double(Math.tan(number.doubleValue()));
+	}
+
+    // ================== Function - BITAND =====================
+	public static Object bitand(int x, int y) {
+        return x & y;
+	}
+
+    // ================== Function - BITOR =====================
+    public static Object bitor(int x, int y) {
+        return x | y;
+    }
+
+    // ================== Function - BITXOR =====================
+    public static Object bitxor(int x, int y) {
+        return x ^ y;
+    }
+
+    // ================== Function - BITNOT =====================
+    public static int bitnot(int x) {
+        return x ^ 0xFFFFFFFF;
+    }
+
+    // ================= Function - USER ========================
+    public static Object user(CommandContext context) {
+        return context.getUserName();
+    }
+    
+    public static Object current_database(CommandContext context) {
+    	return context.getVdbName();
+    }
+
+    // ================= Function - COMMANDPAYLOAD ========================
+    public static Object commandPayload(CommandContext context) {
+        Serializable payload = context.getCommandPayload();
+        if(payload == null) {
+            return null;
+        }
+        // 0-arg form - just return payload as a string if it exists
+        return payload.toString();
+    }
+
+    public static Object commandPayload(CommandContext context, String param) 
+        throws ExpressionEvaluationException, FunctionExecutionException{
+        Serializable payload = context.getCommandPayload();
+        if(payload == null) {
+            return null;
+        }
+        
+        // 1-arg form - assume payload is a Properties object
+        if(payload instanceof Properties) {
+            return ((Properties)payload).getProperty(param);
+        }            
+        // Payload was bad
+        throw new ExpressionEvaluationException(QueryPlugin.Util.getString("ExpressionEvaluator.Expected_props_for_payload_function", "commandPayload", payload.getClass().getName())); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    // ================= Function - ENV ========================
+    public static Object env(CommandContext context, String propertyName) {
+        // All context property keys must be lowercase - we lowercase the incoming key here to match regardless of case
+        String propertyNameNocase = propertyName.toLowerCase();
+        Properties envProps = context.getEnvironmentProperties();
+        if(envProps != null && envProps.containsKey(propertyNameNocase)) {
+            return envProps.getProperty(propertyNameNocase);
+        }
+        String value = System.getProperty(propertyName);
+        if (value == null) {
+            value = System.getProperty(propertyNameNocase);
+        }
+        return value;            
+    }
+    
+    public static Object session_id(CommandContext context) {
+        return context.getConnectionID();
+    }
+    
+    // ================= Function - MODIFYTIMEZONE ========================
+    
+    public static Object modifyTimeZone(Timestamp value, String originalTimezoneString, String targetTimezoneString) {
+        TimeZone originalTimeZone = TimeZone.getTimeZone(originalTimezoneString);
+        TimeZone dbmsTimeZone = TimeZone.getTimeZone(targetTimezoneString);
+
+        // Check that the dbms time zone is really different than the local time zone
+        if (originalTimeZone.equals(dbmsTimeZone)) {
+            return value;
+        }
+
+        Calendar cal = Calendar.getInstance(dbmsTimeZone);
+        
+        return TimestampWithTimezone.createTimestamp(value, originalTimeZone, cal);
+    }
+
+    public static Object modifyTimeZone(CommandContext context, Timestamp value, String targetTimezoneString) {
+        TimeZone dbmsTimeZone = TimeZone.getTimeZone(targetTimezoneString);
+
+        Calendar cal = Calendar.getInstance(dbmsTimeZone);
+        
+        return TimestampWithTimezone.createTimestamp(value, context.getServerTimeZone(), cal);
+    } 
+    
+    public static Clob toChars(BlobType value, String encoding) {
+    	Charset cs = getCharset(encoding);
+		BlobInputStreamFactory bisf = new BlobInputStreamFactory(value.getReference());
+    	ClobImpl clob = new ClobImpl(bisf, -1);
+    	clob.setCharset(cs);
+    	return new ClobType(clob);
+    }
+    
+    public static Blob toBytes(ClobType value, String encoding) throws IOException {
+    	Charset cs = getCharset(encoding);
+    	ClobInputStreamFactory cisf = new ClobInputStreamFactory(value.getReference());
+    	cisf.setCharset(cs);
+    	if (CharsetUtils.BASE64_NAME.equalsIgnoreCase(encoding) || CharsetUtils.HEX_NAME.equalsIgnoreCase(encoding)) {
+    		//validate that the binary conversion is possible
+    		//TODO: cache the result in a filestore
+    		InputStream is = cisf.getInputStream();
+    		try {
+	    		while (is.read() != -1) {
+	    			
+	    		}
+    		} finally {
+    			is.close();
+    		}
+    	}
+    	return new BlobType(new BlobImpl(cisf));
+	}
+    
+    public static Charset getCharset(String encoding) {
+    	if (CharsetUtils.BASE64_NAME.equalsIgnoreCase(encoding)) {
+    		return CharsetUtils.BASE64;
+    	}
+    	if (CharsetUtils.HEX_NAME.equalsIgnoreCase(encoding)) {
+    		return CharsetUtils.HEX;
+    	}
+    	return Charset.forName(encoding);
+	}
+
+    public static String unescape(String string) {
+    	StringBuilder sb = new StringBuilder();
+    	boolean escaped = false;
+    	for (int i = 0; i < string.length(); i++) {
+    		char c = string.charAt(i);
+    		if (escaped) {
+	    		switch (c) {
+	    		case 'b':
+	    			sb.append('\b');
+	    			break;
+	    		case 't':
+	    			sb.append('\t');
+	    			break;
+	    		case 'n':
+	    			sb.append('\n');
+	    			break;
+	    		case 'f':
+	    			sb.append('\f');
+	    			break;
+	    		case 'r':
+	    			sb.append('\r');
+	    			break;
+	    		case 'u':
+					i = parseNumericValue(string, sb, i, 0, 4, 4);
+					//TODO: this should probably be strict about needing 4 digits
+	    			break;
+    			default:
+    				int value = Character.digit(c, 8);
+					if (value == -1) {
+						sb.append(c);
+					} else {
+						int possibleDigits = value < 3 ? 2:1;
+						int radixExp = 3;
+    					i = parseNumericValue(string, sb, i, value, possibleDigits, radixExp);
+    				}
+	    		}
+	    		escaped = false;
+    		} else {
+    			if (c == '\\') {
+    				escaped = true;
+    			} else {
+					sb.append(c);
+    			}
+    		}
+    	}
+    	//TODO: should this be strict?
+    	//if (escaped) {
+    		//throw new FunctionExecutionException();
+    	//}
+    	return sb.toString();
+    }
+
+	private static int parseNumericValue(String string, StringBuilder sb,
+			int i, int value, int possibleDigits, int radixExp) {
+		for (int j = 0; j < possibleDigits; j++) {
+			if (i + 1 == string.length()) {
+				break;
+			}
+			char digit = string.charAt(i + 1);
+			int val = Character.digit(digit, 1 << radixExp);
+			if (val == -1) {
+				break;
+			}
+			i++;
+			value = (value << radixExp) + val;
+		}
+		sb.append((char)value);
+		return i;
+	}
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/FunctionTree.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,408 +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.function;
-
-import java.lang.reflect.Array;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.Assertion;
-import org.teiid.core.util.ReflectionHelper;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.AbstractMetadataRecord;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.metadata.FunctionCategoryConstants;
-import org.teiid.query.util.CommandContext;
-
-
-/**
- * Data structure used to store function signature information. There are multiple uses
- * of this signature information so there are multiple data structures within the FunctionTree
- * for handling each.  One type of information is the function metadata required by users of
- * this class for data driving GUIs or function selection.  The other type of information is that
- * needed to quickly find and/or invoke the functions at execution time.  In general all methods
- * are concerned with function metadata EXCEPT {@link #getFunction} which is used to find a function
- * for execution.
- */
-public class FunctionTree {
-
-    // Constant used to look up the special descriptor key in a node map
-    private static final Integer DESCRIPTOR_KEY = new Integer(-1);
-
-    private Map<String, Set<String>> categories = new HashMap<String, Set<String>>();
-
-    private Map<String, List<FunctionMethod>> functionsByName = new HashMap<String, List<FunctionMethod>>();
-    
-    private Set<FunctionMethod> allFunctions = new HashSet<FunctionMethod>();
-
-	/**
-	 * Function lookup and invocation use: Function name (uppercase) to Map (recursive tree)
-	 */
-    private Map treeRoot = new HashMap();
-    private boolean validateClass;
-
-    /**
-     * Construct a new tree with the given source of function metadata.
-     * @param source The metadata source
-     */
-    public FunctionTree(FunctionMetadataSource source) {
-    	this(source, false);
-    }
-    
-    /**
-     * Construct a new tree with the given source of function metadata.
-     * @param source The metadata source
-     */
-    public FunctionTree(FunctionMetadataSource source, boolean validateClass) {
-        // Load data structures
-    	this.validateClass = validateClass;
-        addSource(source);
-    }
-
-    /**
-     * Add all functions from a metadata source to the data structures.
-     * @param source The source of the functions
-     */
-    private void addSource(FunctionMetadataSource source) {
-        if(source == null) {
-            return;
-        }
-
-        Collection functions = source.getFunctionMethods();
-        if(functions != null) {
-            Iterator functionIter = functions.iterator();
-            while(functionIter.hasNext()) {
-                Object functionObj = functionIter.next();
-                if(! (functionObj instanceof FunctionMethod)) {
-                    Assertion.failed(QueryPlugin.Util.getString("ERR.015.001.0045", functionObj.getClass().getName())); //$NON-NLS-1$
-                }
-                FunctionMethod method = (FunctionMethod) functionObj;
-
-				if (!containsIndistinguishableFunction(method)){
-                    // Store method metadata for retrieval
-                    addMetadata(method);
-
-                    // Add to tree
-                    addFunction(source, method);
-				} else {
-                    LogManager.logWarning(LogConstants.CTX_FUNCTION_TREE, QueryPlugin.Util.getString("ERR.015.001.0046", new Object[]{method})); //$NON-NLS-1$
-				}
-            }
-        }
-    }
-
-	// ---------------------- FUNCTION SELECTION USE METHODS ----------------------
-
-	/*
-	 * Per defect 4612 -
-	 * Because of the fix for defect 4264, it is possible in the modeler to
-	 * define two functions with different implementations, but having the
-	 * same name (using the "alias") and the same parameter types, making the
-	 * two FunctionMethod objects indistinguishable by their equals method.
-	 * This method will check if any indistinguishable functions are already
-	 * present in this FunctionTree.  If so, it will be logged and any
-	 * newer indistinguishable functions will just not be added.
-	 */
-	private boolean containsIndistinguishableFunction(FunctionMethod method){
-        return allFunctions.contains(method);
-	}
-
-    /**
-     * Store the method in the function metadata.
-     * @param method The function metadata for a particular method signature
-     */
-    private void addMetadata(FunctionMethod method) {
-    	String categoryKey = method.getCategory();
-    	if (categoryKey == null) {
-    		method.setCategory(FunctionCategoryConstants.MISCELLANEOUS);
-    		categoryKey = FunctionCategoryConstants.MISCELLANEOUS;
-    	}
-    	categoryKey = categoryKey.toUpperCase();
-        String nameKey = method.getName().toUpperCase();
-        
-        // Look up function map (create if necessary)
-        Set<String> functions = categories.get(categoryKey);
-        if (functions == null) {
-            functions = new HashSet<String>();
-            categories.put(categoryKey, functions);
-        }
-
-        int index = -1;
-        while (true){
-	        // Look up function in function map
-	        functions.add(nameKey);
-	
-	        // Add method to list by function name
-	        List<FunctionMethod> knownMethods = functionsByName.get(nameKey);
-	        if(knownMethods == null) {
-	            knownMethods = new ArrayList<FunctionMethod>();
-	            functionsByName.put(nameKey, knownMethods);
-	        }
-	        knownMethods.add(method);
-	        
-	        // if the function is "." delimited, then add all possible forms
-	        index = nameKey.indexOf(AbstractMetadataRecord.NAME_DELIM_CHAR, index+1);
-	        if (index != -1) {
-	        	nameKey = nameKey.substring(index+1);
-	        }
-	        else {
-	        	break;
-	        }
-        } 
-        allFunctions.add(method);
-    }
-
-    /**
-     * Get collection of category names.
-     * @return Category names
-     */
-    Collection<String> getCategories() {
-        return categories.keySet();
-    }
-
-    /**
-     * Get collection of function forms in a category
-     * @param category Category to get (case-insensitive)
-     * @return Collection of {@link FunctionForm}s
-     */
-    Collection<FunctionForm> getFunctionForms(String category) {
-        Set<FunctionForm> functionForms = new HashSet<FunctionForm>();
-
-        Set<String> functions = categories.get(category.toUpperCase());
-        if(functions != null) {
-        	for (String functionName : functions) {
-        		for (FunctionMethod functionMethod : this.functionsByName.get(functionName)) {
-                    functionForms.add(new FunctionForm(functionMethod));
-                }
-            }
-        }
-
-        return functionForms;
-    }
-
-    /**
-     * Find function form based on function name and # of arguments.
-     * @param name Function name, case insensitive
-     * @param args Number of arguments
-     * @return Corresponding form or null if not found
-     */
-    FunctionForm findFunctionForm(String name, int args) {
-    	List<FunctionMethod> results = findFunctionMethods(name, args);
-    	if (results.size() > 0) {
-    		return new FunctionForm(results.get(0));
-    	}
-    	return null;
-    }
-    
-    /**
-     * Find all function methods with the given name and arg length
-     * @param name Function name, case insensitive
-     * @param args Number of arguments
-     * @return Corresponding form or null if not found
-     */
-    List<FunctionMethod> findFunctionMethods(String name, int args) {
-        final List<FunctionMethod> allMatches = new ArrayList<FunctionMethod>();
-        List<FunctionMethod> methods = functionsByName.get(name.toUpperCase());
-        if(methods == null || methods.size() == 0) {
-            return allMatches;
-        }
-
-        for (FunctionMethod functionMethod : methods) {
-            if(functionMethod.getInputParameterCount() == args || functionMethod.isVarArgs() && args >= functionMethod.getInputParameterCount() - 1) {
-                allMatches.add(functionMethod);
-            }
-        }
-
-        return allMatches;
-    }    
-
-	// ---------------------- FUNCTION INVOCATION USE METHODS ----------------------
-
-    /**
-     * Store the method for function resolution and invocation.
-     * @param source The function metadata source, which knows how to obtain the invocation class
-     * @param method The function metadata for a particular method signature
-     */
-    private void addFunction(FunctionMetadataSource source, FunctionMethod method) {
-        // Get method name
-        String methodName = method.getName();
-
-        // Get input types for path
-        FunctionParameter[] inputParams = method.getInputParameters();
-        List<Class> inputTypes = new LinkedList<Class>();
-        if(inputParams != null) {
-            for(int i=0; i<inputParams.length; i++) {
-                String typeName = inputParams[i].getType();
-                inputTypes.add(DataTypeManager.getDataTypeClass(typeName));
-            }
-        }
-        Class[] types = inputTypes.toArray(new Class[inputTypes.size()]);
-
-        if (method.isVarArgs()) {
-        	inputTypes.set(inputTypes.size() - 1, Array.newInstance(inputTypes.get(inputTypes.size() - 1), 0).getClass());
-        }
-
-        // Get return type
-        FunctionParameter outputParam = method.getOutputParameter();
-        Class outputType = null;
-        if(outputParam != null) {
-            outputType = DataTypeManager.getDataTypeClass(outputParam.getType());
-        }
-
-        Method invocationMethod = null;
-        boolean requiresContext = false;
-        // Defect 20007 - Ignore the invocation method if pushdown is not required.
-        if (method.getPushdown() == PushDown.CAN_PUSHDOWN || method.getPushdown() == PushDown.CANNOT_PUSHDOWN) {
-            try {
-                Class<?> methodClass = source.getInvocationClass(method.getInvocationClass());
-                ReflectionHelper helper = new ReflectionHelper(methodClass);
-                try {
-                	invocationMethod = helper.findBestMethodWithSignature(method.getInvocationMethod(), inputTypes);
-                } catch (NoSuchMethodException e) {
-                    inputTypes.add(0, CommandContext.class);
-                	invocationMethod = helper.findBestMethodWithSignature(method.getInvocationMethod(), inputTypes);
-                	requiresContext = true;
-                }
-            } catch (ClassNotFoundException e) {
-            	if (validateClass) {
-            		throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.no_class", method.getName(), method.getInvocationClass())); //$NON-NLS-1$ //$NON-NLS-2$
-            	}
-            } catch (NoSuchMethodException e) {
-            	throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.no_method", method, method.getInvocationClass(), method.getInvocationMethod())); //$NON-NLS-1$ //$NON-NLS-2$
-            } catch (Exception e) {                
-                throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("ERR.015.001.0047", method, method.getInvocationClass(), method.getInvocationMethod())); //$NON-NLS-1$ //$NON-NLS-2$
-            } 
-            if (invocationMethod != null) {
-            	// Check return type is non void
-        		Class<?> methodReturn = invocationMethod.getReturnType();
-        		if(methodReturn.equals(Void.TYPE)) {
-        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_void", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
-        		}
-
-        		// Check that method is public
-        		int modifiers = invocationMethod.getModifiers();
-        		if(! Modifier.isPublic(modifiers)) {
-        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_public", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
-        		}
-
-        		// Check that method is static
-        		if(! Modifier.isStatic(modifiers)) {
-        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_static", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
-        		}
-            }
-        } else {
-            inputTypes.add(0, CommandContext.class);
-        }
-
-        FunctionDescriptor descriptor = new FunctionDescriptor(method.getName(), method.getPushdown(), types, outputType, invocationMethod, requiresContext, method.isNullOnNull(), method.getDeterminism());
-        // Store this path in the function tree
-        
-        int index = -1;
-        while(true) {
-        	Map node = treeRoot;
-	        Object[] path = buildPath(methodName, types);
-	        for(int pathIndex = 0; pathIndex < path.length; pathIndex++) {
-	            Object pathPart = path[pathIndex];
-	            Map children = (Map) node.get(pathPart);
-	            if(children == null) {
-	                children = new HashMap();
-	                node.put(pathPart, children);
-	            }
-	            if (method.isVarArgs() && pathIndex == path.length - 1) {
-	        		node.put(DESCRIPTOR_KEY, descriptor);
-	            }
-	            node = children;
-	        }
-	
-	        if (method.isVarArgs()) {
-	        	node.put(types[types.length - 1], node);
-	        }
-	        // Store the leaf descriptor in the tree
-	        node.put(DESCRIPTOR_KEY, descriptor);
-	        
-	        index = methodName.indexOf(AbstractMetadataRecord.NAME_DELIM_CHAR, index+1);
-	        if (index == -1) {
-	        	break;
-	        }
-	        methodName = methodName.substring(index+1);
-        }
-    }
-    
-    /**
-     * Look up a function descriptor by signature in the tree.  If none is
-     * found, null is returned.
-     * @param name Name of the function, case is not important
-     * @param argTypes Types of each argument in the function
-     * @return Descriptor which can be used to invoke the function
-     */
-    FunctionDescriptor getFunction(String name, Class[] argTypes) {
-        // Build search path
-        Object[] path = buildPath(name, argTypes);
-
-        // Walk path in tree
-        Map node = treeRoot;
-        for(int i=0; i<path.length; i++) {
-        	node = (Map)node.get(path[i]);
-        	if (node == null) {
-        		return null;
-            }
-        }
-
-        // Look for key at the end
-        if(node.containsKey(DESCRIPTOR_KEY)) {
-            // This is the end - return descriptor
-            return (FunctionDescriptor) node.get(DESCRIPTOR_KEY);
-        }
-        // No descriptor at this location in tree
-        return null;
-    }
-
-    /**
-     * Build the path in the function storage tree.  The path for a function consists
-     * of it's name (uppercased) and each of the argument classes.
-     * @param name Name of function
-     * @param argTypes Types of each arguments
-     * @return Path in function storage tree
-     */
-    private Object[] buildPath(String name, Class[] argTypes) {
-        Object[] path = new Object[argTypes.length + 1];
-        path[0] = name.toUpperCase();
-        System.arraycopy(argTypes, 0, path, 1, argTypes.length);
-        return path;
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java (from rev 2764, trunk/engine/src/main/java/org/teiid/query/function/FunctionTree.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/FunctionTree.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,408 @@
+/*
+ * 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.function;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.Assertion;
+import org.teiid.core.util.ReflectionHelper;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.metadata.FunctionCategoryConstants;
+import org.teiid.query.util.CommandContext;
+
+
+/**
+ * Data structure used to store function signature information. There are multiple uses
+ * of this signature information so there are multiple data structures within the FunctionTree
+ * for handling each.  One type of information is the function metadata required by users of
+ * this class for data driving GUIs or function selection.  The other type of information is that
+ * needed to quickly find and/or invoke the functions at execution time.  In general all methods
+ * are concerned with function metadata EXCEPT {@link #getFunction} which is used to find a function
+ * for execution.
+ */
+public class FunctionTree {
+
+    // Constant used to look up the special descriptor key in a node map
+    private static final Integer DESCRIPTOR_KEY = new Integer(-1);
+
+    private Map<String, Set<String>> categories = new HashMap<String, Set<String>>();
+
+    private Map<String, List<FunctionMethod>> functionsByName = new HashMap<String, List<FunctionMethod>>();
+    
+    private Set<FunctionMethod> allFunctions = new HashSet<FunctionMethod>();
+
+	/**
+	 * Function lookup and invocation use: Function name (uppercase) to Map (recursive tree)
+	 */
+    private Map treeRoot = new HashMap();
+    private boolean validateClass;
+
+    /**
+     * Construct a new tree with the given source of function metadata.
+     * @param source The metadata source
+     */
+    public FunctionTree(FunctionMetadataSource source) {
+    	this(source, false);
+    }
+    
+    /**
+     * Construct a new tree with the given source of function metadata.
+     * @param source The metadata source
+     */
+    public FunctionTree(FunctionMetadataSource source, boolean validateClass) {
+        // Load data structures
+    	this.validateClass = validateClass;
+        addSource(source);
+    }
+
+    /**
+     * Add all functions from a metadata source to the data structures.
+     * @param source The source of the functions
+     */
+    private void addSource(FunctionMetadataSource source) {
+        if(source == null) {
+            return;
+        }
+
+        Collection functions = source.getFunctionMethods();
+        if(functions != null) {
+            Iterator functionIter = functions.iterator();
+            while(functionIter.hasNext()) {
+                Object functionObj = functionIter.next();
+                if(! (functionObj instanceof FunctionMethod)) {
+                    Assertion.failed(QueryPlugin.Util.getString("ERR.015.001.0045", functionObj.getClass().getName())); //$NON-NLS-1$
+                }
+                FunctionMethod method = (FunctionMethod) functionObj;
+
+				if (!containsIndistinguishableFunction(method)){
+                    // Store method metadata for retrieval
+                    addMetadata(method);
+
+                    // Add to tree
+                    addFunction(source, method);
+				} else {
+                    LogManager.logWarning(LogConstants.CTX_FUNCTION_TREE, QueryPlugin.Util.getString("ERR.015.001.0046", new Object[]{method})); //$NON-NLS-1$
+				}
+            }
+        }
+    }
+
+	// ---------------------- FUNCTION SELECTION USE METHODS ----------------------
+
+	/*
+	 * Per defect 4612 -
+	 * Because of the fix for defect 4264, it is possible in the modeler to
+	 * define two functions with different implementations, but having the
+	 * same name (using the "alias") and the same parameter types, making the
+	 * two FunctionMethod objects indistinguishable by their equals method.
+	 * This method will check if any indistinguishable functions are already
+	 * present in this FunctionTree.  If so, it will be logged and any
+	 * newer indistinguishable functions will just not be added.
+	 */
+	private boolean containsIndistinguishableFunction(FunctionMethod method){
+        return allFunctions.contains(method);
+	}
+
+    /**
+     * Store the method in the function metadata.
+     * @param method The function metadata for a particular method signature
+     */
+    private void addMetadata(FunctionMethod method) {
+    	String categoryKey = method.getCategory();
+    	if (categoryKey == null) {
+    		method.setCategory(FunctionCategoryConstants.MISCELLANEOUS);
+    		categoryKey = FunctionCategoryConstants.MISCELLANEOUS;
+    	}
+    	categoryKey = categoryKey.toUpperCase();
+        String nameKey = method.getName().toUpperCase();
+        
+        // Look up function map (create if necessary)
+        Set<String> functions = categories.get(categoryKey);
+        if (functions == null) {
+            functions = new HashSet<String>();
+            categories.put(categoryKey, functions);
+        }
+
+        int index = -1;
+        while (true){
+	        // Look up function in function map
+	        functions.add(nameKey);
+	
+	        // Add method to list by function name
+	        List<FunctionMethod> knownMethods = functionsByName.get(nameKey);
+	        if(knownMethods == null) {
+	            knownMethods = new ArrayList<FunctionMethod>();
+	            functionsByName.put(nameKey, knownMethods);
+	        }
+	        knownMethods.add(method);
+	        
+	        // if the function is "." delimited, then add all possible forms
+	        index = nameKey.indexOf(AbstractMetadataRecord.NAME_DELIM_CHAR, index+1);
+	        if (index != -1) {
+	        	nameKey = nameKey.substring(index+1);
+	        }
+	        else {
+	        	break;
+	        }
+        } 
+        allFunctions.add(method);
+    }
+
+    /**
+     * Get collection of category names.
+     * @return Category names
+     */
+    Collection<String> getCategories() {
+        return categories.keySet();
+    }
+
+    /**
+     * Get collection of function forms in a category
+     * @param category Category to get (case-insensitive)
+     * @return Collection of {@link FunctionForm}s
+     */
+    Collection<FunctionForm> getFunctionForms(String category) {
+        Set<FunctionForm> functionForms = new HashSet<FunctionForm>();
+
+        Set<String> functions = categories.get(category.toUpperCase());
+        if(functions != null) {
+        	for (String functionName : functions) {
+        		for (FunctionMethod functionMethod : this.functionsByName.get(functionName)) {
+                    functionForms.add(new FunctionForm(functionMethod));
+                }
+            }
+        }
+
+        return functionForms;
+    }
+
+    /**
+     * Find function form based on function name and # of arguments.
+     * @param name Function name, case insensitive
+     * @param args Number of arguments
+     * @return Corresponding form or null if not found
+     */
+    FunctionForm findFunctionForm(String name, int args) {
+    	List<FunctionMethod> results = findFunctionMethods(name, args);
+    	if (results.size() > 0) {
+    		return new FunctionForm(results.get(0));
+    	}
+    	return null;
+    }
+    
+    /**
+     * Find all function methods with the given name and arg length
+     * @param name Function name, case insensitive
+     * @param args Number of arguments
+     * @return Corresponding form or null if not found
+     */
+    List<FunctionMethod> findFunctionMethods(String name, int args) {
+        final List<FunctionMethod> allMatches = new ArrayList<FunctionMethod>();
+        List<FunctionMethod> methods = functionsByName.get(name.toUpperCase());
+        if(methods == null || methods.size() == 0) {
+            return allMatches;
+        }
+
+        for (FunctionMethod functionMethod : methods) {
+            if(functionMethod.getInputParameterCount() == args || functionMethod.isVarArgs() && args >= functionMethod.getInputParameterCount() - 1) {
+                allMatches.add(functionMethod);
+            }
+        }
+
+        return allMatches;
+    }    
+
+	// ---------------------- FUNCTION INVOCATION USE METHODS ----------------------
+
+    /**
+     * Store the method for function resolution and invocation.
+     * @param source The function metadata source, which knows how to obtain the invocation class
+     * @param method The function metadata for a particular method signature
+     */
+    private void addFunction(FunctionMetadataSource source, FunctionMethod method) {
+        // Get method name
+        String methodName = method.getName();
+
+        // Get input types for path
+        FunctionParameter[] inputParams = method.getInputParameters();
+        List<Class> inputTypes = new LinkedList<Class>();
+        if(inputParams != null) {
+            for(int i=0; i<inputParams.length; i++) {
+                String typeName = inputParams[i].getType();
+                inputTypes.add(DataTypeManager.getDataTypeClass(typeName));
+            }
+        }
+        Class[] types = inputTypes.toArray(new Class[inputTypes.size()]);
+
+        if (method.isVarArgs()) {
+        	inputTypes.set(inputTypes.size() - 1, Array.newInstance(inputTypes.get(inputTypes.size() - 1), 0).getClass());
+        }
+
+        // Get return type
+        FunctionParameter outputParam = method.getOutputParameter();
+        Class outputType = null;
+        if(outputParam != null) {
+            outputType = DataTypeManager.getDataTypeClass(outputParam.getType());
+        }
+
+        Method invocationMethod = null;
+        boolean requiresContext = false;
+        // Defect 20007 - Ignore the invocation method if pushdown is not required.
+        if (method.getPushdown() == PushDown.CAN_PUSHDOWN || method.getPushdown() == PushDown.CANNOT_PUSHDOWN) {
+            try {
+                Class<?> methodClass = source.getInvocationClass(method.getInvocationClass());
+                ReflectionHelper helper = new ReflectionHelper(methodClass);
+                try {
+                	invocationMethod = helper.findBestMethodWithSignature(method.getInvocationMethod(), inputTypes);
+                } catch (NoSuchMethodException e) {
+                    inputTypes.add(0, CommandContext.class);
+                	invocationMethod = helper.findBestMethodWithSignature(method.getInvocationMethod(), inputTypes);
+                	requiresContext = true;
+                }
+            } catch (ClassNotFoundException e) {
+            	if (validateClass) {
+            		throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.no_class", method.getName(), method.getInvocationClass())); //$NON-NLS-1$ //$NON-NLS-2$
+            	}
+            } catch (NoSuchMethodException e) {
+            	throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.no_method", method, method.getInvocationClass(), method.getInvocationMethod())); //$NON-NLS-1$ //$NON-NLS-2$
+            } catch (Exception e) {                
+                throw new TeiidRuntimeException(e, "ERR.015.001.0047", QueryPlugin.Util.getString("ERR.015.001.0047", method, method.getInvocationClass(), method.getInvocationMethod())); //$NON-NLS-1$ //$NON-NLS-2$
+            } 
+            if (invocationMethod != null) {
+            	// Check return type is non void
+        		Class<?> methodReturn = invocationMethod.getReturnType();
+        		if(methodReturn.equals(Void.TYPE)) {
+        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_void", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
+        		}
+
+        		// Check that method is public
+        		int modifiers = invocationMethod.getModifiers();
+        		if(! Modifier.isPublic(modifiers)) {
+        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_public", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
+        		}
+
+        		// Check that method is static
+        		if(! Modifier.isStatic(modifiers)) {
+        			throw new TeiidRuntimeException("ERR.015.001.0047", QueryPlugin.Util.getString("FunctionTree.not_static", method.getName(), invocationMethod)); //$NON-NLS-1$ //$NON-NLS-2$
+        		}
+            }
+        } else {
+            inputTypes.add(0, CommandContext.class);
+        }
+
+        FunctionDescriptor descriptor = new FunctionDescriptor(method.getName(), method.getPushdown(), types, outputType, invocationMethod, requiresContext, !method.isNullOnNull(), method.getDeterminism());
+        // Store this path in the function tree
+        
+        int index = -1;
+        while(true) {
+        	Map node = treeRoot;
+	        Object[] path = buildPath(methodName, types);
+	        for(int pathIndex = 0; pathIndex < path.length; pathIndex++) {
+	            Object pathPart = path[pathIndex];
+	            Map children = (Map) node.get(pathPart);
+	            if(children == null) {
+	                children = new HashMap();
+	                node.put(pathPart, children);
+	            }
+	            if (method.isVarArgs() && pathIndex == path.length - 1) {
+	        		node.put(DESCRIPTOR_KEY, descriptor);
+	            }
+	            node = children;
+	        }
+	
+	        if (method.isVarArgs()) {
+	        	node.put(types[types.length - 1], node);
+	        }
+	        // Store the leaf descriptor in the tree
+	        node.put(DESCRIPTOR_KEY, descriptor);
+	        
+	        index = methodName.indexOf(AbstractMetadataRecord.NAME_DELIM_CHAR, index+1);
+	        if (index == -1) {
+	        	break;
+	        }
+	        methodName = methodName.substring(index+1);
+        }
+    }
+    
+    /**
+     * Look up a function descriptor by signature in the tree.  If none is
+     * found, null is returned.
+     * @param name Name of the function, case is not important
+     * @param argTypes Types of each argument in the function
+     * @return Descriptor which can be used to invoke the function
+     */
+    FunctionDescriptor getFunction(String name, Class[] argTypes) {
+        // Build search path
+        Object[] path = buildPath(name, argTypes);
+
+        // Walk path in tree
+        Map node = treeRoot;
+        for(int i=0; i<path.length; i++) {
+        	node = (Map)node.get(path[i]);
+        	if (node == null) {
+        		return null;
+            }
+        }
+
+        // Look for key at the end
+        if(node.containsKey(DESCRIPTOR_KEY)) {
+            // This is the end - return descriptor
+            return (FunctionDescriptor) node.get(DESCRIPTOR_KEY);
+        }
+        // No descriptor at this location in tree
+        return null;
+    }
+
+    /**
+     * Build the path in the function storage tree.  The path for a function consists
+     * of it's name (uppercased) and each of the argument classes.
+     * @param name Name of function
+     * @param argTypes Types of each arguments
+     * @return Path in function storage tree
+     */
+    private Object[] buildPath(String name, Class[] argTypes) {
+        Object[] path = new Object[argTypes.length + 1];
+        path[0] = name.toUpperCase();
+        System.arraycopy(argTypes, 0, path, 1, argTypes.length);
+        return path;
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,99 +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.function.metadata;
-
-import org.teiid.metadata.FunctionParameter;
-
-
-/**
- * @see FunctionMetadataValidator
- * @see FunctionCategoryConstants
- */
-public class FunctionMethod extends org.teiid.metadata.FunctionMethod {
-	private static final long serialVersionUID = -2380536393719646754L;
-
-	/**
-     * Construct a function method with default pushdown and null dependent attributes.
-     * @param name Function name
-     * @param description Function description
-     * @param category Function category
-     * @param invocationClass Invocation class
-     * @param invocationMethod Invocation method
-     * @param inputParams Input parameters
-     * @param outputParam Output parameter (return parameter)
-     */
-    public FunctionMethod(String name, String description, String category, 
-        String invocationClass, String invocationMethod, 
-        FunctionParameter[] inputParams, FunctionParameter outputParam) {
-        this(name, description, category, invocationClass, invocationMethod, inputParams, outputParam, Determinism.DETERMINISTIC);
-    }
-    
-    /**
-     * Construct a function method with default pushdown and null dependent attributes.
-     * @param name Function name
-     * @param description Function description
-     * @param category Function category
-     * @param invocationClass Invocation class
-     * @param invocationMethod Invocation method
-     * @param inputParams Input parameters
-     * @param outputParam Output parameter (return parameter)
-     */
-    public FunctionMethod(String name, String description, String category, 
-        String invocationClass, String invocationMethod, 
-        FunctionParameter[] inputParams, FunctionParameter outputParam, Determinism deterministic) {
-        super(name, description, category, PushDown.CAN_PUSHDOWN, invocationClass, invocationMethod, inputParams, outputParam, false, deterministic);
-    }
-
-    /**
-     * Construct a function method with all parameters assuming null dependent and non-deterministic.
-     * @param name Function name
-     * @param description Function description
-     * @param category Function category
-     * @param invocationClass Invocation class
-     * @param invocationMethod Invocation method
-     * @param inputParams Input parameters
-     * @param outputParam Output parameter (return parameter)
-     */
-    public FunctionMethod(String name, String description, String category, 
-        PushDown pushdown, String invocationClass, String invocationMethod, 
-        FunctionParameter[] inputParams, FunctionParameter outputParam) {
-        super(name, description, category, pushdown, invocationClass, invocationMethod, inputParams, outputParam, true,Determinism.NONDETERMINISTIC);
-    }
-    
-    public FunctionMethod(String name, String description, String category, FunctionParameter[] inputParams, FunctionParameter outputParam) {
-    	super(name, description, category, PushDown.MUST_PUSHDOWN, null, null, inputParams, outputParam, false, Determinism.DETERMINISTIC);
-    } 
-    
-    public FunctionMethod(String name,
-            String description,
-            String category,
-            PushDown pushdown,
-            String invocationClass,
-            String invocationMethod,
-            FunctionParameter[] inputParams,
-            FunctionParameter outputParam,
-            boolean nullDependent,
-            Determinism deterministic) {
-    	super(name, description, category, pushdown, invocationClass, invocationMethod, inputParams, outputParam, nullDependent, deterministic);
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java (from rev 2764, trunk/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/metadata/FunctionMethod.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,79 @@
+/*
+ * 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.function.metadata;
+
+import org.teiid.metadata.FunctionParameter;
+
+
+/**
+ * @see FunctionMetadataValidator
+ * @see FunctionCategoryConstants
+ */
+public class FunctionMethod extends org.teiid.metadata.FunctionMethod {
+	private static final long serialVersionUID = -2380536393719646754L;
+
+	/**
+     * Construct a function method with default pushdown and null dependent attributes.
+     * @param name Function name
+     * @param description Function description
+     * @param category Function category
+     * @param invocationClass Invocation class
+     * @param invocationMethod Invocation method
+     * @param inputParams Input parameters
+     * @param outputParam Output parameter (return parameter)
+     */
+    public FunctionMethod(String name, String description, String category, 
+        String invocationClass, String invocationMethod, 
+        FunctionParameter[] inputParams, FunctionParameter outputParam) {
+        super(name, description, category, PushDown.CAN_PUSHDOWN, invocationClass, invocationMethod, inputParams, outputParam, true, Determinism.DETERMINISTIC);
+    }
+
+    /**
+     * Construct a function method with all parameters assuming null dependent and non-deterministic.
+     * @param name Function name
+     * @param description Function description
+     * @param category Function category
+     * @param invocationClass Invocation class
+     * @param invocationMethod Invocation method
+     * @param inputParams Input parameters
+     * @param outputParam Output parameter (return parameter)
+     */
+    public FunctionMethod(String name, String description, String category, 
+        PushDown pushdown, String invocationClass, String invocationMethod, 
+        FunctionParameter[] inputParams, FunctionParameter outputParam) {
+        super(name, description, category, pushdown, invocationClass, invocationMethod, inputParams, outputParam, false,Determinism.NONDETERMINISTIC);
+    }
+    
+    public FunctionMethod(String name,
+            String description,
+            String category,
+            PushDown pushdown,
+            String invocationClass,
+            String invocationMethod,
+            FunctionParameter[] inputParams,
+            FunctionParameter outputParam,
+            boolean nullDependent,
+            Determinism deterministic) {
+    	super(name, description, category, pushdown, invocationClass, invocationMethod, inputParams, outputParam, !nullDependent, deterministic);
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1057 +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.function.source;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionMetadataSource;
-import org.teiid.query.function.FunctionMethods;
-import org.teiid.query.function.metadata.FunctionCategoryConstants;
-import org.teiid.query.function.metadata.FunctionMethod;
-import org.teiid.translator.SourceSystemFunctions;
-
-
-/**
- * This metadata source has metadata for the hard-coded system functions.  All
- * system functions are described by this metadata.
- */
-public class SystemSource implements FunctionMetadataSource, FunctionCategoryConstants {
-
-    /** The name of the invocation class for all of the system functions. */
-    private static final String FUNCTION_CLASS = FunctionMethods.class.getName(); 
-    private static final String XML_FUNCTION_CLASS = XMLSystemFunctions.class.getName(); 
-    private static final String SECURITY_FUNCTION_CLASS = SecuritySystemFunctions.class.getName(); 
-    
-    /** Cached list of system function metadata, created in constructor */
-    private List<org.teiid.metadata.FunctionMethod> functions = new ArrayList<org.teiid.metadata.FunctionMethod>();
-    
-    /**
-     * Construct a source of system metadata.
-     */
-    public SystemSource(boolean allowEnvFunction) {
-		// +, -, *, /
-        addArithmeticFunction(SourceSystemFunctions.ADD_OP, QueryPlugin.Util.getString("SystemSource.Add_desc"), "plus", QueryPlugin.Util.getString("SystemSource.Add_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addArithmeticFunction(SourceSystemFunctions.SUBTRACT_OP, QueryPlugin.Util.getString("SystemSource.Subtract_desc"), "minus", QueryPlugin.Util.getString("SystemSource.Subtract_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addArithmeticFunction(SourceSystemFunctions.MULTIPLY_OP, QueryPlugin.Util.getString("SystemSource.Multiply_desc"), "multiply", QueryPlugin.Util.getString("SystemSource.Multiply_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addArithmeticFunction(SourceSystemFunctions.DIVIDE_OP, QueryPlugin.Util.getString("SystemSource.Divide_desc"), "divide", QueryPlugin.Util.getString("SystemSource.Divide_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addArithmeticFunction(SourceSystemFunctions.MOD, QueryPlugin.Util.getString("SystemSource.Mod_desc"), "mod", QueryPlugin.Util.getString("SystemSource.Mod_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        
-        // numeric
-        addAbsFunction();
-        addRandFunction();
-        addPowerFunction();
-        addRoundFunction();
-        addSignFunction();
-        addSqrtFunction();        
-		addDoubleFunction(SourceSystemFunctions.ACOS, QueryPlugin.Util.getString("SystemSource.Acos_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.ASIN, QueryPlugin.Util.getString("SystemSource.Asin_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.ATAN, QueryPlugin.Util.getString("SystemSource.Atan_desc")); //$NON-NLS-1$ 
-		addAtan2Function(SourceSystemFunctions.ATAN2, QueryPlugin.Util.getString("SystemSource.Atan2_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.COS, QueryPlugin.Util.getString("SystemSource.Cos_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.COT, QueryPlugin.Util.getString("SystemSource.Cot_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.DEGREES, QueryPlugin.Util.getString("SystemSource.Degrees_desc")); //$NON-NLS-1$ 
-		addPiFunction(SourceSystemFunctions.PI, QueryPlugin.Util.getString("SystemSource.Pi_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.RADIANS, QueryPlugin.Util.getString("SystemSource.Radians_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.SIN, QueryPlugin.Util.getString("SystemSource.Sin_desc")); //$NON-NLS-1$ 
-		addDoubleFunction(SourceSystemFunctions.TAN, QueryPlugin.Util.getString("SystemSource.Tan_desc")); //$NON-NLS-1$ 
-        addDoubleFunction(SourceSystemFunctions.LOG, QueryPlugin.Util.getString("SystemSource.Log_desc")); //$NON-NLS-1$ 
-        addDoubleFunction(SourceSystemFunctions.LOG10, QueryPlugin.Util.getString("SystemSource.Log10_desc")); //$NON-NLS-1$ 
-        addDoubleFunction(SourceSystemFunctions.CEILING, QueryPlugin.Util.getString("SystemSource.Ceiling_desc")); //$NON-NLS-1$ 
-        addDoubleFunction(SourceSystemFunctions.EXP, QueryPlugin.Util.getString("SystemSource.Exp_desc")); //$NON-NLS-1$ 
-        addDoubleFunction(SourceSystemFunctions.FLOOR, QueryPlugin.Util.getString("SystemSource.Floor_desc")); //$NON-NLS-1$ 
-        
-        // bit
-        addBitFunction(SourceSystemFunctions.BITAND, QueryPlugin.Util.getString("SystemSource.Bitand_desc"), "bitand", 2, QueryPlugin.Util.getString("SystemSource.Bitand_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addBitFunction(SourceSystemFunctions.BITOR, QueryPlugin.Util.getString("SystemSource.Bitor_desc"), "bitor", 2, QueryPlugin.Util.getString("SystemSource.Bitor_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addBitFunction(SourceSystemFunctions.BITXOR, QueryPlugin.Util.getString("SystemSource.Bitxor_desc"), "bitxor", 2, QueryPlugin.Util.getString("SystemSource.Bitxor_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addBitFunction(SourceSystemFunctions.BITNOT, QueryPlugin.Util.getString("SystemSource.Bitnot_desc"), "bitnot", 1, QueryPlugin.Util.getString("SystemSource.Bitnot_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-
-        // date
-        addConstantDateFunction(SourceSystemFunctions.CURDATE, QueryPlugin.Util.getString("SystemSource.Curdate_desc"), "currentDate", DataTypeManager.DefaultDataTypes.DATE); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addConstantDateFunction(SourceSystemFunctions.CURTIME, QueryPlugin.Util.getString("SystemSource.Curtime_desc"), "currentTime", DataTypeManager.DefaultDataTypes.TIME); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addConstantDateFunction(SourceSystemFunctions.NOW, QueryPlugin.Util.getString("SystemSource.Now_desc"), "currentTimestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addDateFunction(SourceSystemFunctions.DAYNAME, "dayName", QueryPlugin.Util.getString("SystemSource.Dayname_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayname_result_ts_desc"), DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.DAYOFMONTH, "dayOfMonth", QueryPlugin.Util.getString("SystemSource.Dayofmonth_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofmonth_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.DAYOFWEEK, "dayOfWeek", QueryPlugin.Util.getString("SystemSource.Dayofweek_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofweek_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.DAYOFYEAR, "dayOfYear", QueryPlugin.Util.getString("SystemSource.Dayofyear_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofyear_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.MONTH, "month", QueryPlugin.Util.getString("SystemSource.Month_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Month_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.MONTHNAME, "monthName", QueryPlugin.Util.getString("SystemSource.Monthname_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Monthname_result_ts_desc"), DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.WEEK, "week", QueryPlugin.Util.getString("SystemSource.Week_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Week_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addDateFunction(SourceSystemFunctions.YEAR, "year", QueryPlugin.Util.getString("SystemSource.Year_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Year_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addTimeFunction(SourceSystemFunctions.HOUR, "hour", QueryPlugin.Util.getString("SystemSource.Hour_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Hour_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addTimeFunction(SourceSystemFunctions.MINUTE, "minute", QueryPlugin.Util.getString("SystemSource.Minute_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Minute_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        addTimeFunction(SourceSystemFunctions.SECOND, "second", QueryPlugin.Util.getString("SystemSource.Second_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Second_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-		addQuarterFunction(SourceSystemFunctions.QUARTER, "quarter", QueryPlugin.Util.getString("SystemSource.Quarter_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Quarter_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-		addTimestampAddFunction();
-        addTimestampDiffFunction();
-        addTimeZoneFunctions();
-        addTimestampCreateFunction();
-        addUnixTimeFunctions();
-		                  
-        // string
-        addStringFunction(SourceSystemFunctions.LENGTH, QueryPlugin.Util.getString("SystemSource.Length_result"), "length", DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addStringFunction(SourceSystemFunctions.UCASE, QueryPlugin.Util.getString("SystemSource.Ucase_result"), "upperCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addStringFunction(SourceSystemFunctions.LCASE, QueryPlugin.Util.getString("SystemSource.Lcase_result"), "lowerCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
-		addStringFunction("lower", QueryPlugin.Util.getString("SystemSource.Lower_result"), "lowerCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		addStringFunction("upper", QueryPlugin.Util.getString("SystemSource.Upper_result"), "upperCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        addStringFunction(SourceSystemFunctions.LTRIM, QueryPlugin.Util.getString("SystemSource.Left_result"), "leftTrim", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addStringFunction(SourceSystemFunctions.RTRIM, QueryPlugin.Util.getString("SystemSource.Right_result"), "rightTrim", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addConcatFunction();    
-        addSubstringFunction(); 
-        addLeftRightFunctions();
-        addLocateFunction();
-        addReplaceFunction();
-        addAsciiFunction();
-        addCharFunction();
-        addInitCapFunction();
-        addLpadFunction();
-        addRpadFunction();
-        addTranslateFunction();
-        addRepeatFunction();
-		addSpaceFunction();
-		addInsertFunction();
-		
-        // clob
-        addClobFunction(SourceSystemFunctions.UCASE, QueryPlugin.Util.getString("SystemSource.UcaseClob_result"), "upperCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addClobFunction(SourceSystemFunctions.LCASE, QueryPlugin.Util.getString("SystemSource.LcaseClob_result"), "lowerCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ 
-        addClobFunction("lower", QueryPlugin.Util.getString("SystemSource.LowerClob_result"), "lowerCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        addClobFunction("upper", QueryPlugin.Util.getString("SystemSource.UpperClob_result"), "upperCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        
-        addToCharsFunction();
-        addToBytesFunction();
-        
-        // conversion
-        addConversionFunctions();   
-        
-        // miscellaneous functions
-        addContextFunctions(); 
-        addRowLimitFunctions();                        
-        addRowLimitExceptionFunctions();                        
-        addDecodeFunctions();
-        addLookupFunctions();
-        addUserFunction();
-        addCurrentDatabaseFunction();
-        if (allowEnvFunction) {
-        	addEnvFunction();
-        }
-        addSessionIdFunction();
-        addCommandPayloadFunctions();
-		addIfNullFunctions();
-        
-		// format 
-		addFormatTimestampFunction();  
-		addFormatNumberFunctions();
-		
-		// parse
-		addParseTimestampFunction();
-		addParseNumberFunctions();
-        
-        // xml functions
-        addXpathValueFunction();
-        addXslTransformFunction();
-        addXmlConcat();
-        addXmlComment();
-        addXmlPi();
-        addJsonToXml();
-        
-        addSecurityFunctions();
-        
-        for (String type : DataTypeManager.getAllDataTypeNames()) {
-        	if (!DataTypeManager.isNonComparable(type)) {
-        		addTypedNullIfFunction(type);
-        	}
-        	addTypedCoalesceFunction(type);
-        }
-    }
-
-    private void addSecurityFunctions() {
-        functions.add(new FunctionMethod("hasRole", QueryPlugin.Util.getString("SystemSource.hasRole_description"), SECURITY, PushDown.CANNOT_PUSHDOWN, SECURITY_FUNCTION_CLASS, "hasRole", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                                        new FunctionParameter[] { 
-                                            new FunctionParameter("roleType", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                            new FunctionParameter("roleName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, QueryPlugin.Util.getString("SystemSource.hasRole_result")), false, Determinism.USER_DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
-        
-        functions.add(new FunctionMethod("hasRole", QueryPlugin.Util.getString("SystemSource.hasRole_description"), SECURITY, PushDown.CANNOT_PUSHDOWN, SECURITY_FUNCTION_CLASS, "hasRole", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter[] { 
-                    new FunctionParameter("roleName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, QueryPlugin.Util.getString("SystemSource.hasRole_result")), false, Determinism.USER_DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addFormatNumberFunctions() {
-		addFormatNumberFunction(SourceSystemFunctions.FORMATINTEGER, QueryPlugin.Util.getString("SystemSource.Formatinteger_desc"), "format", "integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Formatinteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addFormatNumberFunction(SourceSystemFunctions.FORMATLONG, QueryPlugin.Util.getString("SystemSource.Formatlong_desc"), "format", "long", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Formatlong_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addFormatNumberFunction(SourceSystemFunctions.FORMATDOUBLE, QueryPlugin.Util.getString("SystemSource.Formatdouble_desc"), "format", "double", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Formatdouble_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addFormatNumberFunction(SourceSystemFunctions.FORMATFLOAT, QueryPlugin.Util.getString("SystemSource.Formatfloat_desc"), "format", "float", DataTypeManager.DefaultDataTypes.FLOAT, QueryPlugin.Util.getString("SystemSource.Formatfloat_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addFormatNumberFunction(SourceSystemFunctions.FORMATBIGINTEGER, QueryPlugin.Util.getString("SystemSource.Formatbiginteger_desc"), "format", "biginteger", DataTypeManager.DefaultDataTypes.BIG_INTEGER, QueryPlugin.Util.getString("SystemSource.Formatbiginteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addFormatNumberFunction(SourceSystemFunctions.FORMATBIGDECIMAL, QueryPlugin.Util.getString("SystemSource.Formatbigdecimal_desc"), "format", "bigdecimal", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Formatbigdecimal_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-	}
-	
-	private void addParseNumberFunctions() {
-		addParseNumberFunction(SourceSystemFunctions.PARSEINTEGER, QueryPlugin.Util.getString("SystemSource.Parseinteger_desc"), "parseInteger", "integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Parseinteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addParseNumberFunction(SourceSystemFunctions.PARSELONG, QueryPlugin.Util.getString("SystemSource.Parselong_desc"), "parseLong", "long", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Parselong_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addParseNumberFunction(SourceSystemFunctions.PARSEDOUBLE, QueryPlugin.Util.getString("SystemSource.Parsedouble_desc"), "parseDouble", "double", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Parsedouble_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addParseNumberFunction(SourceSystemFunctions.PARSEFLOAT, QueryPlugin.Util.getString("SystemSource.Parsefloat_desc"), "parseFloat", "float", DataTypeManager.DefaultDataTypes.FLOAT, QueryPlugin.Util.getString("SystemSource.Parsefloat_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addParseNumberFunction(SourceSystemFunctions.PARSEBIGINTEGER, QueryPlugin.Util.getString("SystemSource.Parsebiginteger_desc"), "parseBigInteger", "biginteger", DataTypeManager.DefaultDataTypes.BIG_INTEGER, QueryPlugin.Util.getString("SystemSource.Parsebiginteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-		addParseNumberFunction(SourceSystemFunctions.PARSEBIGDECIMAL, QueryPlugin.Util.getString("SystemSource.Parsebigdecimal_desc"), "parseBigDecimal", "bigdecimal", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Parsebigdecimal_result_desc"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-	}
-	
-    private void addArithmeticFunction(String functionName, String description, String methodName, String resultsDescription) {
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.INTEGER);
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.LONG);
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.FLOAT);
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.BIG_INTEGER);
-        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
-    }
-    
-    private void addTypedArithmeticFunction(String functionName, String description, String methodName, String resultsDescription, String type) {
-        functions.add(
-            new FunctionMethod(functionName, description, NUMERIC, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] { 
-                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.Arith_left_op")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.Arith_right_op")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", type, resultsDescription) ) );                 //$NON-NLS-1$
-    }
-    
-    private void addAbsFunction() {
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.INTEGER);
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.LONG);
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.FLOAT);
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER);
-        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
-    }
-
-    private void addTypedAbsFunction(String type) {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.ABS, QueryPlugin.Util.getString("SystemSource.Abs_desc"), NUMERIC, FUNCTION_CLASS, "abs", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Abs_arg")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.Abs_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addRandFunction() {
-        // With Seed
-        FunctionMethod rand = new FunctionMethod(SourceSystemFunctions.RAND, QueryPlugin.Util.getString("SystemSource.Rand_desc"), NUMERIC, FUNCTION_CLASS, "rand", //$NON-NLS-1$ //$NON-NLS-2$ 
-                                          new FunctionParameter[] {new FunctionParameter("seed", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rand_arg")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                                          new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Rand_result_desc")), Determinism.NONDETERMINISTIC );                 //$NON-NLS-1$ //$NON-NLS-2$
-        rand.setNullOnNull(true);
-        functions.add(rand);
-        // Without Seed
-        functions.add( new FunctionMethod(SourceSystemFunctions.RAND, QueryPlugin.Util.getString("SystemSource.Rand_desc"), NUMERIC, FUNCTION_CLASS, "rand", //$NON-NLS-1$ //$NON-NLS-2$ 
-                                          new FunctionParameter[] {}, 
-                                          new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Rand_result_desc")), Determinism.NONDETERMINISTIC ) ); //$NON-NLS-1$ //$NON-NLS-2$                
-    }
-
-	private void addDoubleFunction(String name, String description) {
-		functions.add(
-			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
-				new FunctionParameter[] { 
-					new FunctionParameter("number", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Double_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
-		functions.add(
-				new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
-					new FunctionParameter[] { 
-						new FunctionParameter("number", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Double_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
-	}
-
-	private void addAtan2Function(String name, String description) {
-		functions.add(
-			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
-				new FunctionParameter[] { 
-					new FunctionParameter("number1", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Atan_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("number2", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Atan_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
-		functions.add(
-				new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
-					new FunctionParameter[] { 
-						new FunctionParameter("number1", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Atan_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-						new FunctionParameter("number2", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Atan_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
-	}
-
-	private void addPiFunction(String name, String description) {
-		functions.add(
-			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
-				new FunctionParameter[] { },
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
-	}
-			
-    private void addPowerFunction() {
-        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.INTEGER);        
-        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.INTEGER);
-    }
-
-    private void addTypedPowerFunction(String baseType, String powerType) { 
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.POWER, QueryPlugin.Util.getString("SystemSource.Power_desc"), NUMERIC, FUNCTION_CLASS, "power", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("base", baseType, QueryPlugin.Util.getString("SystemSource.Power_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("power", powerType, QueryPlugin.Util.getString("SystemSource.Power_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", baseType, QueryPlugin.Util.getString("SystemSource.Power_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-
-    private void addRoundFunction() {
-        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.INTEGER);
-        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.FLOAT);
-        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);        
-    }
-
-    private void addTypedRoundFunction(String roundType) { 
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.ROUND, QueryPlugin.Util.getString("SystemSource.Round_desc"), NUMERIC, FUNCTION_CLASS, "round", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("number", roundType, QueryPlugin.Util.getString("SystemSource.Round_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("places", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Round_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", roundType, QueryPlugin.Util.getString("SystemSource.Round_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-
-    private void addSignFunction() {
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.INTEGER);
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.LONG);
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.FLOAT);
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER);
-        addTypedSignFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
-    }
-    
-    private void addTypedSignFunction(String type) {        
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.SIGN, QueryPlugin.Util.getString("SystemSource.Sign_desc"), NUMERIC, FUNCTION_CLASS, "sign", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Sign_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Sign_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    private void addSqrtFunction() {
-        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.LONG);
-        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
-        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
-    }
-    
-    private void addTypedSqrtFunction(String type) {        
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.SQRT, QueryPlugin.Util.getString("SystemSource.Sqrt_desc"), NUMERIC, FUNCTION_CLASS, "sqrt", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Sqrt_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Sqrt_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    /**
-     * Date functions a marked as command deterministic, since we prefer pre-evaluation rather than row-by-row
-     * evaluation.
-     */
-    private void addConstantDateFunction(String name, String description, String methodName, String returnType) {
-        functions.add(
-            new FunctionMethod(name, description, DATETIME, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {},
-                new FunctionParameter("result", returnType, description), Determinism.COMMAND_DETERMINISTIC ) );                 //$NON-NLS-1$
-    }
-
-    private void addDateFunction(String name, String methodName, String dateDesc, String timestampDesc, String returnType) {
-        functions.add(
-            new FunctionMethod(name, dateDesc, DATETIME, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, dateDesc) }, //$NON-NLS-1$
-                new FunctionParameter("result", returnType, dateDesc) ) );                 //$NON-NLS-1$
-        functions.add(
-            new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
-                new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
-    }
-
-	private void addQuarterFunction(String name, String methodName, String dateDesc, String timestampDesc, String returnType) {
-		functions.add(
-			new FunctionMethod(name, dateDesc, DATETIME, FUNCTION_CLASS, methodName,
-				new FunctionParameter[] {
-					new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, dateDesc) }, //$NON-NLS-1$
-				new FunctionParameter("result", returnType, dateDesc) ) );                 //$NON-NLS-1$
-		functions.add(
-			new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
-				new FunctionParameter[] {
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
-				new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
-	}
-
-	private void addTimestampAddFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_desc"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
-				new FunctionParameter[] {
-					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_desc"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$  
-				new FunctionParameter[] {
-					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_desc"), DATETIME, FUNCTION_CLASS, "timestampAdd", //$NON-NLS-1$ //$NON-NLS-2$ 
-				new FunctionParameter[] {
-					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_result")) ) );			                //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-    private void addTimestampDiffFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.TIMESTAMPDIFF, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_desc"), DATETIME, FUNCTION_CLASS, "timestampDiff", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("timestamp1", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("timestamp2", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addTimestampCreateFunction() {
-        functions.add(
-              new FunctionMethod(SourceSystemFunctions.TIMESTAMPCREATE, QueryPlugin.Util.getString("SystemSource.TimestampCreate_desc"), DATETIME, FUNCTION_CLASS, "timestampCreate", //$NON-NLS-1$ //$NON-NLS-2$ 
-                  new FunctionParameter[] {
-                      new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.TimestampCreate_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
-                      new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.TimestampCreate_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-                  new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.TimestampCreate_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-   
-    private void addTimeFunction(String name, String methodName, String timeDesc, String timestampDesc, String returnType) {
-        functions.add(
-            new FunctionMethod(name, timeDesc, DATETIME, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, timeDesc) }, //$NON-NLS-1$
-                new FunctionParameter("result", returnType, timeDesc) ) );                 //$NON-NLS-1$
-        functions.add(
-            new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
-                new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
-    }
-    
-    private void addStringFunction(String name, String description, String methodName, String returnType) {
-        functions.add(
-            new FunctionMethod(name, description, STRING, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Stringfunc_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", returnType, description) ) );                 //$NON-NLS-1$
-    }
-    
-    private void addClobFunction(String name, String description, String methodName, String returnType) {
-        functions.add(
-            new FunctionMethod(name, description, STRING, PushDown.MUST_PUSHDOWN, FUNCTION_CLASS, methodName,
-                new FunctionParameter[] {
-                    new FunctionParameter("clob", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.Clobfunc_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", returnType, description), false, Determinism.DETERMINISTIC ) );                 //$NON-NLS-1$
-    }
-
-    private void addConcatFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.CONCAT, QueryPlugin.Util.getString("SystemSource.Concat_desc"), STRING, FUNCTION_CLASS, "concat", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod("||", QueryPlugin.Util.getString("SystemSource.Concatop_desc"), STRING, FUNCTION_CLASS, "concat", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter[] {
-                    new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-        
-        FunctionMethod concat2 = new FunctionMethod("concat2", QueryPlugin.Util.getString("SystemSource.Concat_desc"), STRING, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ //$NON-NLS-2$ 
-                           new FunctionParameter[] {
-                               new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                               new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                           new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_result_desc")), true, Determinism.DETERMINISTIC ); //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(concat2);                         
-    }
-
-    private void addSubstringFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.SUBSTRING, QueryPlugin.Util.getString("SystemSource.Substring_desc"), STRING, FUNCTION_CLASS, "substring", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.SUBSTRING, QueryPlugin.Util.getString("SystemSource.Susbstring2_desc"), STRING, FUNCTION_CLASS, "substring", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring2_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addLeftRightFunctions() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.LEFT, QueryPlugin.Util.getString("SystemSource.Left_desc"), STRING, FUNCTION_CLASS, "left", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Left_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Left_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Left2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.RIGHT, QueryPlugin.Util.getString("SystemSource.Right_desc"), STRING, FUNCTION_CLASS, "right", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Right_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Right_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Right2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-           
-    private void addLocateFunction() {
-        FunctionMethod func =
-            new FunctionMethod(SourceSystemFunctions.LOCATE, QueryPlugin.Util.getString("SystemSource.Locate_desc"), STRING, FUNCTION_CLASS, "locate", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate_result")) );                 //$NON-NLS-1$ //$NON-NLS-2$
-        func.setNullOnNull(true);
-        functions.add(func);
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.LOCATE, QueryPlugin.Util.getString("SystemSource.Locate2_desc"), STRING, FUNCTION_CLASS, "locate", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate2_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addReplaceFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.REPLACE, QueryPlugin.Util.getString("SystemSource.Replace_desc"), STRING, FUNCTION_CLASS, "replace", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("replacement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-	private void addRepeatFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.REPEAT, QueryPlugin.Util.getString("SystemSource.Repeat_desc"), STRING, FUNCTION_CLASS, "repeat", //$NON-NLS-1$ //$NON-NLS-2$ 
-				new FunctionParameter[] {
-					new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Repeat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Repeat_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Repeat_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	private void addSpaceFunction() {
-		functions.add(
-			new FunctionMethod(FunctionLibrary.SPACE, QueryPlugin.Util.getString("SystemSource.Space_desc"), STRING, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
-				new FunctionParameter[] {
-					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Space_arg1"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Space_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	private void addInsertFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.INSERT, QueryPlugin.Util.getString("SystemSource.Insert_desc"), STRING, FUNCTION_CLASS, "insert", //$NON-NLS-1$ //$NON-NLS-2$ 
-				new FunctionParameter[] {
-					new FunctionParameter("str1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("start", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Insert_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Insert_arg3")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("str2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_arg4")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	private void addToCharsFunction() {
-		functions.add(
-			new FunctionMethod("to_chars", QueryPlugin.Util.getString("SystemSource.encode_desc"), CONVERSION, FUNCTION_CLASS, "toChars", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$  
-				new FunctionParameter[] {
-					new FunctionParameter("value", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.encode_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("encoding", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.encode_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.encode_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	private void addToBytesFunction() {
-		functions.add(
-			new FunctionMethod("to_bytes", QueryPlugin.Util.getString("SystemSource.decode_desc"), CONVERSION, FUNCTION_CLASS, "toBytes", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$  
-				new FunctionParameter[] {
-					new FunctionParameter("value", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.decode_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("encoding", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.decode_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.decode_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-    private void addAsciiFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.ASCII, QueryPlugin.Util.getString("SystemSource.Ascii_desc"), STRING, FUNCTION_CLASS, "ascii", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Ascii_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Ascii_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.ASCII, QueryPlugin.Util.getString("SystemSource.Ascii2_desc"), STRING, FUNCTION_CLASS, "ascii", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Ascii2_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Ascii2_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-	private void addCharFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.CHAR, QueryPlugin.Util.getString("SystemSource.Char_desc"), STRING, FUNCTION_CLASS, "chr", //$NON-NLS-1$ //$NON-NLS-2$ 
-				new FunctionParameter[] {
-					new FunctionParameter("code", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Char_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Char_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-                new FunctionMethod("chr", QueryPlugin.Util.getString("SystemSource.Chr_desc"), STRING, FUNCTION_CLASS, "chr", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    new FunctionParameter[] {
-                        new FunctionParameter("code", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Chr_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Chr_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-    private void addInitCapFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.INITCAP, QueryPlugin.Util.getString("SystemSource.Initcap_desc"), STRING, FUNCTION_CLASS, "initCap", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Initcap_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Initcap_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addLpadFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.LPAD, QueryPlugin.Util.getString("SystemSource.Lpad_desc"), STRING, FUNCTION_CLASS, "lpad", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Lpad_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.LPAD, QueryPlugin.Util.getString("SystemSource.Lpad3_desc"), STRING, FUNCTION_CLASS, "lpad", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Lpad3_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addRpadFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.RPAD, QueryPlugin.Util.getString("SystemSource.Rpad1_desc"), STRING, FUNCTION_CLASS, "rpad", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad1_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rpad1_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad1_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.RPAD, QueryPlugin.Util.getString("SystemSource.Rpad3_desc"), STRING, FUNCTION_CLASS, "rpad", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rpad3_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addTranslateFunction() {
-        functions.add(
-            new FunctionMethod(SourceSystemFunctions.TRANSLATE, QueryPlugin.Util.getString("SystemSource.Translate_desc"), STRING, FUNCTION_CLASS, "translate", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("source", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("destination", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addConversionFunctions() {
-    	for (String type : DataTypeManager.getAllDataTypeNames()) {
-            addTypedConversionFunction(SourceSystemFunctions.CONVERT, type); 
-            addTypedConversionFunction("cast", type); //$NON-NLS-1$
-    	}
-    }
-    
-    private void addTypedConversionFunction(String name, String sourceType) {
-        functions.add(
-            new FunctionMethod(name, QueryPlugin.Util.getString("SystemSource.Convert_desc", sourceType), CONVERSION, FUNCTION_CLASS, "convert", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] {
-                    new FunctionParameter("value", sourceType, QueryPlugin.Util.getString("SystemSource.Convert_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("target", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Convert_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.OBJECT, QueryPlugin.Util.getString("SystemSource.Convert_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
-    
-    }    
-
-    private void addContextFunctions() {
-    	for (String contextType : DataTypeManager.getAllDataTypeNames()) {
-    		for (String exprType : DataTypeManager.getAllDataTypeNames()) {
-                addTypedContextFunction(contextType, exprType);
-        	}
-    	}
-    }
-    
-    private void addTypedContextFunction(String contextType, String exprType) {
-        functions.add(
-            new FunctionMethod("context", QueryPlugin.Util.getString("SystemSource.Context_desc"), MISCELLANEOUS, FUNCTION_CLASS, "context", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter[] {
-                    new FunctionParameter("context", contextType, QueryPlugin.Util.getString("SystemSource.Context_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Context_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", exprType, QueryPlugin.Util.getString("SystemSource.Context_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    } 
-    
-    private void addRowLimitFunctions() {
-    	for (String exprType : DataTypeManager.getAllDataTypeNames()) {
-            functions.add(
-                    new FunctionMethod("rowlimit", QueryPlugin.Util.getString("SystemSource.Rowlimit_desc"), MISCELLANEOUS, FUNCTION_CLASS, "rowlimit", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                        new FunctionParameter[] {
-                            new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Rowlimit_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rowlimit_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-    }
-    
-    private void addRowLimitExceptionFunctions() {
-    	for (String exprType : DataTypeManager.getAllDataTypeNames()) {
-            functions.add(
-                    new FunctionMethod("rowlimitexception", QueryPlugin.Util.getString("SystemSource.RowlimitException_desc"), MISCELLANEOUS, FUNCTION_CLASS, "rowlimitexception", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                        new FunctionParameter[] {
-                            new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Rowlimit_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rowlimit_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-    }    
-    
-    private void addDecodeFunctions(){
-        addDecodeFunction("decodeInteger", DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        addDecodeFunction("decodeString", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
-    }
-        
-    private void addDecodeFunction(String functionName, String resultType) {
-        functions.add(
-            new FunctionMethod(functionName, QueryPlugin.Util.getString("SystemSource.Decode1_desc"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-                new FunctionParameter[] { 
-                    new FunctionParameter("input", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode1_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("decodeString", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode1_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", resultType, QueryPlugin.Util.getString("SystemSource.Decode1_result") ) ) );    //$NON-NLS-1$ //$NON-NLS-2$
-                     
-        functions.add(
-            new FunctionMethod(functionName, QueryPlugin.Util.getString("SystemSource.Decode2_desc"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-                new FunctionParameter[] { 
-                    new FunctionParameter("input", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("decodeString", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("delimiter", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", resultType, QueryPlugin.Util.getString("SystemSource.Decode2_result") ) ) );    //$NON-NLS-1$ //$NON-NLS-2$
-
-    }
-
-    private void addLookupFunctions() {
-    	for (String keyValueType : DataTypeManager.getAllDataTypeNames()) {
-            functions.add(
-                    new FunctionMethod("lookup", QueryPlugin.Util.getString("SystemSource.Lookup_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "lookup", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                        new FunctionParameter[] {
-                            new FunctionParameter("codetable", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                            new FunctionParameter("returnelement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
-                            new FunctionParameter("keyelement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg3")), //$NON-NLS-1$ //$NON-NLS-2$
-                            new FunctionParameter("keyvalue", keyValueType, QueryPlugin.Util.getString("SystemSource.Lookup_arg4")), //$NON-NLS-1$ //$NON-NLS-2$
-                             },
-                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.OBJECT, QueryPlugin.Util.getString("SystemSource.Lookup_result")), true, Determinism.VDB_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    	}
-    }
-
-    private void addUserFunction() {
-        functions.add(
-            new FunctionMethod("user", QueryPlugin.Util.getString("SystemSource.User_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "user", null, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.User_result")), false, Determinism.USER_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addCurrentDatabaseFunction() {
-        functions.add(
-            new FunctionMethod("current_database", QueryPlugin.Util.getString("SystemSource.current_database_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "current_database", null, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("current_database_result")), false, Determinism.VDB_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    private void addEnvFunction() {
-        functions.add(
-            new FunctionMethod("env", QueryPlugin.Util.getString("SystemSource.Env_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "env", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter[] {
-                    new FunctionParameter("variablename", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Env_varname")) //$NON-NLS-1$ //$NON-NLS-2$
-                     },
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Env_result")), false, Determinism.SESSION_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addSessionIdFunction() {
-        functions.add(
-            new FunctionMethod(FunctionLibrary.SESSION_ID, QueryPlugin.Util.getString("SystemSource.session_id_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "session_id", null, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.session_id_result")), false, Determinism.SESSION_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    private void addCommandPayloadFunctions() {
-        functions.add(
-            new FunctionMethod("commandpayload", QueryPlugin.Util.getString("SystemSource.CommandPayload_desc0"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "commandPayload", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                 new FunctionParameter[] {},
-                 new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_result")), false, Determinism.COMMAND_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(
-            new FunctionMethod("commandpayload", QueryPlugin.Util.getString("SystemSource.CommandPayload_desc1"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "commandPayload", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                 new FunctionParameter[] {
-                     new FunctionParameter("property", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_property")) //$NON-NLS-1$ //$NON-NLS-2$
-                      },
-                 new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_result")), false, Determinism.COMMAND_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addIfNullFunctions() {
-    	for (String type : DataTypeManager.getAllDataTypeNames()) {
-            addNvlFunction(type);
-            addIfNullFunction(type);
-    	}
-    }
-	
-    private void addNvlFunction(String valueType) {
-        FunctionMethod nvl = 
-            new FunctionMethod("nvl", QueryPlugin.Util.getString("SystemSource.Nvl_desc"), MISCELLANEOUS, FUNCTION_CLASS, "ifnull", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                new FunctionParameter[] {
-                    new FunctionParameter("value", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("valueIfNull", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_result")) ); //$NON-NLS-1$ //$NON-NLS-2$
-        nvl.setNullOnNull(true);
-        functions.add(nvl); 
-    }
-
-	private void addIfNullFunction(String valueType) {
-		FunctionMethod nvl = 
-			new FunctionMethod("ifnull", QueryPlugin.Util.getString("SystemSource.Ifnull_desc"), MISCELLANEOUS, FUNCTION_CLASS, "ifnull", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-				new FunctionParameter[] {
-					new FunctionParameter("value", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("valueIfNull", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_result")) ); //$NON-NLS-1$ //$NON-NLS-2$
-        nvl.setNullOnNull(true);
-        functions.add(nvl); 
-	}
-			
-	private void addFormatTimestampFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.FORMATTIMESTAMP, QueryPlugin.Util.getString("SystemSource.Formattimestamp_desc"),CONVERSION, FUNCTION_CLASS, "format", //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter[] { 
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Formattimestamp_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattimestamp_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattimestamp_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-				new FunctionMethod(FunctionLibrary.FORMATDATE, QueryPlugin.Util.getString("SystemSource.Formatdate_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-					new FunctionParameter[] { 
-						new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Formatdate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatdate_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatdate_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-				new FunctionMethod(FunctionLibrary.FORMATTIME, QueryPlugin.Util.getString("SystemSource.Formattime_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-					new FunctionParameter[] { 
-						new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Formattime_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattime_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattime_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-	}
-					
-	private void addParseTimestampFunction() {
-		functions.add(
-			new FunctionMethod(SourceSystemFunctions.PARSETIMESTAMP, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_desc"),CONVERSION, FUNCTION_CLASS, "parseTimestamp", //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter[] { 
-					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-				new FunctionMethod(FunctionLibrary.PARSETIME, QueryPlugin.Util.getString("SystemSource.Parsetime_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-					new FunctionParameter[] { 
-						new FunctionParameter("time", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetime_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetime_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Parsetime_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-		functions.add(
-				new FunctionMethod(FunctionLibrary.PARSEDATE, QueryPlugin.Util.getString("SystemSource.Parsedate_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
-					new FunctionParameter[] { 
-						new FunctionParameter("date", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsedate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsedate_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Parsedate_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	private void addFormatNumberFunction(String functionName, String description, String methodName, String inputParam, String dataType,  String resultDesc) {
-		functions.add(
-			new FunctionMethod(functionName, description, CONVERSION, FUNCTION_CLASS, methodName,
-				new FunctionParameter[] { 
-					new FunctionParameter(inputParam, dataType, QueryPlugin.Util.getString("SystemSource.Formatnumber_arg1")), //$NON-NLS-1$
-					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatnumber_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, resultDesc) ) );       //$NON-NLS-1$
-	}
-		
-	private void addParseNumberFunction(String functionName, String description, String methodName, String inputParam, String dataType,  String resultDesc) {
-			functions.add(
-				new FunctionMethod(functionName, description, CONVERSION, FUNCTION_CLASS, methodName,
-					new FunctionParameter[] { 
-						new FunctionParameter(inputParam, DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsenumber_arg1")), //$NON-NLS-1$
-						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsenumber_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
-					new FunctionParameter("result", dataType, resultDesc) ) );       //$NON-NLS-1$
-	}
-    
-    private void addBitFunction(String functionName, String description, String methodName, int parameters, String resultDescription) {
-        FunctionParameter[] paramArray = null;
-        if (parameters == 1) {
-            paramArray = new FunctionParameter[] {
-                new FunctionParameter("integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc_arg1")) //$NON-NLS-1$ //$NON-NLS-2$
-            };
-        } else if (parameters == 2) {
-            paramArray = new FunctionParameter[] {
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer2", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc2_arg2")) //$NON-NLS-1$ //$NON-NLS-2$
-            };
-        }
-        functions.add(
-            new FunctionMethod(functionName, description, NUMERIC, FUNCTION_CLASS, methodName,
-                paramArray,
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, resultDescription) //$NON-NLS-1$
-            )
-        );
-    }
-    
-    private void addXpathValueFunction() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter[] { 
-                                new FunctionParameter("document", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-
-        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("document", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-        
-        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
-                                         new FunctionParameter[] { 
-                                             new FunctionParameter("document", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                             new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                                         new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addXslTransformFunction() {
-    	for (String type1 : Arrays.asList(DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.XML, DataTypeManager.DefaultDataTypes.CLOB)) {
-    		for (String type2 : Arrays.asList(DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.XML, DataTypeManager.DefaultDataTypes.CLOB)) {
-    	        functions.add(new FunctionMethod(SourceSystemFunctions.XSLTRANSFORM, QueryPlugin.Util.getString("SystemSource.xsltransform_description"), XML, XML_FUNCTION_CLASS, "xslTransform", //$NON-NLS-1$ //$NON-NLS-2$  
-                        new FunctionParameter[] { 
-                            new FunctionParameter("document", type1, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                            new FunctionParameter("xsl", type2, QueryPlugin.Util.getString("SystemSource.xsltransform_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.xsltransform_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    		}
-    	}
-    }
-    
-    private void addXmlComment() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.XMLCOMMENT, QueryPlugin.Util.getString("SystemSource.xmlcomment_description"), XML, XML_FUNCTION_CLASS, "xmlComment", //$NON-NLS-1$ //$NON-NLS-2$  
-                            new FunctionParameter[] { 
-                                new FunctionParameter("value", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlcomment_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlcomment_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    private void addXmlPi() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.XMLPI, QueryPlugin.Util.getString("SystemSource.xmlpi_description"), XML, XML_FUNCTION_CLASS, "xmlPi", //$NON-NLS-1$ //$NON-NLS-2$  
-                            new FunctionParameter[] { 
-					            new FunctionParameter("name", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param1"))}, //$NON-NLS-1$ //$NON-NLS-2$
-                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlpi_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-        
-        functions.add(new FunctionMethod(SourceSystemFunctions.XMLPI, QueryPlugin.Util.getString("SystemSource.xmlpi_description"), XML, XML_FUNCTION_CLASS, "xmlPi", //$NON-NLS-1$ //$NON-NLS-2$  
-                new FunctionParameter[] { 
-		            new FunctionParameter("name", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-		            new FunctionParameter("value", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlpi_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addJsonToXml() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.JSONTOXML, QueryPlugin.Util.getString("SystemSource.jsonToXml_description"), XML, XML_FUNCTION_CLASS, "jsonToXml", //$NON-NLS-1$ //$NON-NLS-2$  
-                new FunctionParameter[] { 
-        	new FunctionParameter("rootElementName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.jsonToXml_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-        	new FunctionParameter("json", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.jsonToXml_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.jsonToXml_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-        functions.add(new FunctionMethod(SourceSystemFunctions.JSONTOXML, QueryPlugin.Util.getString("SystemSource.jsonToXml_description"), XML, XML_FUNCTION_CLASS, "jsonToXml", //$NON-NLS-1$ //$NON-NLS-2$  
-                new FunctionParameter[] { 
-        	new FunctionParameter("rootElementName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.jsonToXml_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-        	new FunctionParameter("json", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.jsonToXml_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.jsonToXml_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addXmlConcat() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.XMLCONCAT, QueryPlugin.Util.getString("SystemSource.xmlconcat_description"), XML, PushDown.CAN_PUSHDOWN, XML_FUNCTION_CLASS, "xmlConcat", //$NON-NLS-1$ //$NON-NLS-2$  
-                            new FunctionParameter[] { 
-                                new FunctionParameter("param1", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                new FunctionParameter("param2", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_param2"), true)}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_result")), true, Determinism.DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addTimeZoneFunctions() {
-        functions.add(new FunctionMethod(SourceSystemFunctions.MODIFYTIMEZONE, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_description"), DATETIME, FUNCTION_CLASS, "modifyTimeZone", //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter[] { 
-                                new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                new FunctionParameter("startTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param2")), //$NON-NLS-1$ //$NON-NLS-2$
-                                new FunctionParameter("endTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param3"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-
-        functions.add(new FunctionMethod(SourceSystemFunctions.MODIFYTIMEZONE, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_description"), DATETIME, FUNCTION_CLASS, "modifyTimeZone", //$NON-NLS-1$ //$NON-NLS-2$ 
-                                         new FunctionParameter[] { 
-                                             new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                                             new FunctionParameter("endTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param3"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
-                                         new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
-
-    }
-    
-    private void addUnixTimeFunctions() {
-    	functions.add(new FunctionMethod(FunctionLibrary.FROM_UNIXTIME, QueryPlugin.Util.getString("SystemSource.from_unixtime_description"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
-    			new FunctionParameter[] {
-    				new FunctionParameter("unix_timestamp", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.from_unixtime_param1")) //$NON-NLS-1$ //$NON-NLS-2$
-    			},
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.from_unixtime_result")), false, Determinism.DETERMINISTIC )); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addTypedNullIfFunction(String type) {
-        functions.add(
-            new FunctionMethod(FunctionLibrary.NULLIF, QueryPlugin.Util.getString("SystemSource.nullif_description"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
-                new FunctionParameter[] { 
-                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.nullif_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.nullif_param1")) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.nullif_result")), true, Determinism.DETERMINISTIC)); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    private void addTypedCoalesceFunction(String type) {
-        functions.add(
-            new FunctionMethod(FunctionLibrary.COALESCE, QueryPlugin.Util.getString("SystemSource.coalesce_description"), MISCELLANEOUS, PushDown.CAN_PUSHDOWN, FUNCTION_CLASS, "coalesce", //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter[] { 
-                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1")), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("op3", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1"), true) }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.coalesce_result")), true, Determinism.DETERMINISTIC)); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-		
-    /**
-     * Get all function signatures for this metadata source.
-     * @return Unordered collection of {@link FunctionMethod}s
-     */
-    public Collection<org.teiid.metadata.FunctionMethod> getFunctionMethods() {
-        return this.functions;
-	}
-    
-    /**
-     * Sources are returned from the system classpath.
-     * @param className Name of class
-     * @return Class reference  
-     * @throws ClassNotFoundException If class could not be found
-     */
-    public Class<?> getInvocationClass(String className) throws ClassNotFoundException {
-        return Class.forName(className);    
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java (from rev 2765, trunk/engine/src/main/java/org/teiid/query/function/source/SystemSource.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1071 @@
+/*
+ * 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.function.source;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionMetadataSource;
+import org.teiid.query.function.FunctionMethods;
+import org.teiid.query.function.metadata.FunctionCategoryConstants;
+import org.teiid.query.function.metadata.FunctionMethod;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+/**
+ * This metadata source has metadata for the hard-coded system functions.  All
+ * system functions are described by this metadata.
+ */
+public class SystemSource implements FunctionMetadataSource, FunctionCategoryConstants {
+
+    /** The name of the invocation class for all of the system functions. */
+    private static final String FUNCTION_CLASS = FunctionMethods.class.getName(); 
+    private static final String XML_FUNCTION_CLASS = XMLSystemFunctions.class.getName(); 
+    private static final String SECURITY_FUNCTION_CLASS = SecuritySystemFunctions.class.getName(); 
+    
+    /** Cached list of system function metadata, created in constructor */
+    private List<org.teiid.metadata.FunctionMethod> functions = new ArrayList<org.teiid.metadata.FunctionMethod>();
+    
+    /**
+     * Construct a source of system metadata.
+     */
+    public SystemSource(boolean allowEnvFunction) {
+		// +, -, *, /
+        addArithmeticFunction(SourceSystemFunctions.ADD_OP, QueryPlugin.Util.getString("SystemSource.Add_desc"), "plus", QueryPlugin.Util.getString("SystemSource.Add_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addArithmeticFunction(SourceSystemFunctions.SUBTRACT_OP, QueryPlugin.Util.getString("SystemSource.Subtract_desc"), "minus", QueryPlugin.Util.getString("SystemSource.Subtract_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addArithmeticFunction(SourceSystemFunctions.MULTIPLY_OP, QueryPlugin.Util.getString("SystemSource.Multiply_desc"), "multiply", QueryPlugin.Util.getString("SystemSource.Multiply_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addArithmeticFunction(SourceSystemFunctions.DIVIDE_OP, QueryPlugin.Util.getString("SystemSource.Divide_desc"), "divide", QueryPlugin.Util.getString("SystemSource.Divide_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addArithmeticFunction(SourceSystemFunctions.MOD, QueryPlugin.Util.getString("SystemSource.Mod_desc"), "mod", QueryPlugin.Util.getString("SystemSource.Mod_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        
+        // numeric
+        addAbsFunction();
+        addRandFunction();
+        addPowerFunction();
+        addRoundFunction();
+        addSignFunction();
+        addSqrtFunction();        
+		addDoubleFunction(SourceSystemFunctions.ACOS, QueryPlugin.Util.getString("SystemSource.Acos_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.ASIN, QueryPlugin.Util.getString("SystemSource.Asin_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.ATAN, QueryPlugin.Util.getString("SystemSource.Atan_desc")); //$NON-NLS-1$ 
+		addAtan2Function(SourceSystemFunctions.ATAN2, QueryPlugin.Util.getString("SystemSource.Atan2_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.COS, QueryPlugin.Util.getString("SystemSource.Cos_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.COT, QueryPlugin.Util.getString("SystemSource.Cot_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.DEGREES, QueryPlugin.Util.getString("SystemSource.Degrees_desc")); //$NON-NLS-1$ 
+		addPiFunction(SourceSystemFunctions.PI, QueryPlugin.Util.getString("SystemSource.Pi_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.RADIANS, QueryPlugin.Util.getString("SystemSource.Radians_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.SIN, QueryPlugin.Util.getString("SystemSource.Sin_desc")); //$NON-NLS-1$ 
+		addDoubleFunction(SourceSystemFunctions.TAN, QueryPlugin.Util.getString("SystemSource.Tan_desc")); //$NON-NLS-1$ 
+        addDoubleFunction(SourceSystemFunctions.LOG, QueryPlugin.Util.getString("SystemSource.Log_desc")); //$NON-NLS-1$ 
+        addDoubleFunction(SourceSystemFunctions.LOG10, QueryPlugin.Util.getString("SystemSource.Log10_desc")); //$NON-NLS-1$ 
+        addDoubleFunction(SourceSystemFunctions.CEILING, QueryPlugin.Util.getString("SystemSource.Ceiling_desc")); //$NON-NLS-1$ 
+        addDoubleFunction(SourceSystemFunctions.EXP, QueryPlugin.Util.getString("SystemSource.Exp_desc")); //$NON-NLS-1$ 
+        addDoubleFunction(SourceSystemFunctions.FLOOR, QueryPlugin.Util.getString("SystemSource.Floor_desc")); //$NON-NLS-1$ 
+        
+        // bit
+        addBitFunction(SourceSystemFunctions.BITAND, QueryPlugin.Util.getString("SystemSource.Bitand_desc"), "bitand", 2, QueryPlugin.Util.getString("SystemSource.Bitand_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addBitFunction(SourceSystemFunctions.BITOR, QueryPlugin.Util.getString("SystemSource.Bitor_desc"), "bitor", 2, QueryPlugin.Util.getString("SystemSource.Bitor_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addBitFunction(SourceSystemFunctions.BITXOR, QueryPlugin.Util.getString("SystemSource.Bitxor_desc"), "bitxor", 2, QueryPlugin.Util.getString("SystemSource.Bitxor_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addBitFunction(SourceSystemFunctions.BITNOT, QueryPlugin.Util.getString("SystemSource.Bitnot_desc"), "bitnot", 1, QueryPlugin.Util.getString("SystemSource.Bitnot_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+
+        // date
+        addConstantDateFunction(SourceSystemFunctions.CURDATE, QueryPlugin.Util.getString("SystemSource.Curdate_desc"), "currentDate", DataTypeManager.DefaultDataTypes.DATE); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addConstantDateFunction(SourceSystemFunctions.CURTIME, QueryPlugin.Util.getString("SystemSource.Curtime_desc"), "currentTime", DataTypeManager.DefaultDataTypes.TIME); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addConstantDateFunction(SourceSystemFunctions.NOW, QueryPlugin.Util.getString("SystemSource.Now_desc"), "currentTimestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addDateFunction(SourceSystemFunctions.DAYNAME, "dayName", QueryPlugin.Util.getString("SystemSource.Dayname_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayname_result_ts_desc"), DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.DAYOFMONTH, "dayOfMonth", QueryPlugin.Util.getString("SystemSource.Dayofmonth_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofmonth_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.DAYOFWEEK, "dayOfWeek", QueryPlugin.Util.getString("SystemSource.Dayofweek_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofweek_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.DAYOFYEAR, "dayOfYear", QueryPlugin.Util.getString("SystemSource.Dayofyear_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Dayofyear_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.MONTH, "month", QueryPlugin.Util.getString("SystemSource.Month_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Month_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.MONTHNAME, "monthName", QueryPlugin.Util.getString("SystemSource.Monthname_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Monthname_result_ts_desc"), DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.WEEK, "week", QueryPlugin.Util.getString("SystemSource.Week_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Week_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addDateFunction(SourceSystemFunctions.YEAR, "year", QueryPlugin.Util.getString("SystemSource.Year_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Year_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addTimeFunction(SourceSystemFunctions.HOUR, "hour", QueryPlugin.Util.getString("SystemSource.Hour_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Hour_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addTimeFunction(SourceSystemFunctions.MINUTE, "minute", QueryPlugin.Util.getString("SystemSource.Minute_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Minute_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        addTimeFunction(SourceSystemFunctions.SECOND, "second", QueryPlugin.Util.getString("SystemSource.Second_result_t_desc"), QueryPlugin.Util.getString("SystemSource.Second_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+		addQuarterFunction(SourceSystemFunctions.QUARTER, "quarter", QueryPlugin.Util.getString("SystemSource.Quarter_result_d_desc"), QueryPlugin.Util.getString("SystemSource.Quarter_result_ts_desc"), DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+		addTimestampAddFunction();
+        addTimestampDiffFunction();
+        addTimeZoneFunctions();
+        addTimestampCreateFunction();
+        addUnixTimeFunctions();
+		                  
+        // string
+        addStringFunction(SourceSystemFunctions.LENGTH, QueryPlugin.Util.getString("SystemSource.Length_result"), "length", DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addStringFunction(SourceSystemFunctions.UCASE, QueryPlugin.Util.getString("SystemSource.Ucase_result"), "upperCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addStringFunction(SourceSystemFunctions.LCASE, QueryPlugin.Util.getString("SystemSource.Lcase_result"), "lowerCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+		addStringFunction("lower", QueryPlugin.Util.getString("SystemSource.Lower_result"), "lowerCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		addStringFunction("upper", QueryPlugin.Util.getString("SystemSource.Upper_result"), "upperCase", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        addStringFunction(SourceSystemFunctions.LTRIM, QueryPlugin.Util.getString("SystemSource.Left_result"), "leftTrim", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addStringFunction(SourceSystemFunctions.RTRIM, QueryPlugin.Util.getString("SystemSource.Right_result"), "rightTrim", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addConcatFunction();    
+        addSubstringFunction(); 
+        addLeftRightFunctions();
+        addLocateFunction();
+        addReplaceFunction();
+        addAsciiFunction();
+        addCharFunction();
+        addInitCapFunction();
+        addLpadFunction();
+        addRpadFunction();
+        addTranslateFunction();
+        addRepeatFunction();
+		addSpaceFunction();
+		addInsertFunction();
+		
+        // clob
+        addClobFunction(SourceSystemFunctions.UCASE, QueryPlugin.Util.getString("SystemSource.UcaseClob_result"), "upperCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addClobFunction(SourceSystemFunctions.LCASE, QueryPlugin.Util.getString("SystemSource.LcaseClob_result"), "lowerCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ 
+        addClobFunction("lower", QueryPlugin.Util.getString("SystemSource.LowerClob_result"), "lowerCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        addClobFunction("upper", QueryPlugin.Util.getString("SystemSource.UpperClob_result"), "upperCase", DataTypeManager.DefaultDataTypes.CLOB); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        
+        addToCharsFunction();
+        addToBytesFunction();
+        
+        // conversion
+        addConversionFunctions();   
+        
+        // miscellaneous functions
+        addContextFunctions(); 
+        addRowLimitFunctions();                        
+        addRowLimitExceptionFunctions();                        
+        addDecodeFunctions();
+        addLookupFunctions();
+        addUserFunction();
+        addCurrentDatabaseFunction();
+        if (allowEnvFunction) {
+        	addEnvFunction();
+        }
+        addSessionIdFunction();
+        addCommandPayloadFunctions();
+		addIfNullFunctions();
+        
+		// format 
+		addFormatTimestampFunction();  
+		addFormatNumberFunctions();
+		
+		// parse
+		addParseTimestampFunction();
+		addParseNumberFunctions();
+        
+        // xml functions
+        addXpathValueFunction();
+        addXslTransformFunction();
+        addXmlConcat();
+        addXmlComment();
+        addXmlPi();
+        addJsonToXml();
+        
+        addSecurityFunctions();
+        
+        for (String type : DataTypeManager.getAllDataTypeNames()) {
+        	if (!DataTypeManager.isNonComparable(type)) {
+        		addTypedNullIfFunction(type);
+        	}
+        	addTypedCoalesceFunction(type);
+        }
+        
+        addUnescape();
+    }
+
+    private void addUnescape() {
+    	functions.add(new FunctionMethod(SourceSystemFunctions.UNESCAPE, QueryPlugin.Util.getString("SystemSource.unescape_desc"), STRING, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, SourceSystemFunctions.UNESCAPE, //$NON-NLS-1$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.unescape_param1"))}, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.unescape_result")), false, Determinism.DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
+
+	}
+
+	private void addSecurityFunctions() {
+        functions.add(new FunctionMethod("hasRole", QueryPlugin.Util.getString("SystemSource.hasRole_description"), SECURITY, PushDown.CANNOT_PUSHDOWN, SECURITY_FUNCTION_CLASS, "hasRole", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                                        new FunctionParameter[] { 
+                                            new FunctionParameter("roleType", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                            new FunctionParameter("roleName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, QueryPlugin.Util.getString("SystemSource.hasRole_result")), false, Determinism.USER_DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
+        
+        functions.add(new FunctionMethod("hasRole", QueryPlugin.Util.getString("SystemSource.hasRole_description"), SECURITY, PushDown.CANNOT_PUSHDOWN, SECURITY_FUNCTION_CLASS, "hasRole", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter[] { 
+                    new FunctionParameter("roleName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.hasRole_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, QueryPlugin.Util.getString("SystemSource.hasRole_result")), false, Determinism.USER_DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addFormatNumberFunctions() {
+		addFormatNumberFunction(SourceSystemFunctions.FORMATINTEGER, QueryPlugin.Util.getString("SystemSource.Formatinteger_desc"), "format", "integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Formatinteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addFormatNumberFunction(SourceSystemFunctions.FORMATLONG, QueryPlugin.Util.getString("SystemSource.Formatlong_desc"), "format", "long", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Formatlong_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addFormatNumberFunction(SourceSystemFunctions.FORMATDOUBLE, QueryPlugin.Util.getString("SystemSource.Formatdouble_desc"), "format", "double", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Formatdouble_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addFormatNumberFunction(SourceSystemFunctions.FORMATFLOAT, QueryPlugin.Util.getString("SystemSource.Formatfloat_desc"), "format", "float", DataTypeManager.DefaultDataTypes.FLOAT, QueryPlugin.Util.getString("SystemSource.Formatfloat_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addFormatNumberFunction(SourceSystemFunctions.FORMATBIGINTEGER, QueryPlugin.Util.getString("SystemSource.Formatbiginteger_desc"), "format", "biginteger", DataTypeManager.DefaultDataTypes.BIG_INTEGER, QueryPlugin.Util.getString("SystemSource.Formatbiginteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addFormatNumberFunction(SourceSystemFunctions.FORMATBIGDECIMAL, QueryPlugin.Util.getString("SystemSource.Formatbigdecimal_desc"), "format", "bigdecimal", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Formatbigdecimal_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+	}
+	
+	private void addParseNumberFunctions() {
+		addParseNumberFunction(SourceSystemFunctions.PARSEINTEGER, QueryPlugin.Util.getString("SystemSource.Parseinteger_desc"), "parseInteger", "integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Parseinteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addParseNumberFunction(SourceSystemFunctions.PARSELONG, QueryPlugin.Util.getString("SystemSource.Parselong_desc"), "parseLong", "long", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Parselong_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addParseNumberFunction(SourceSystemFunctions.PARSEDOUBLE, QueryPlugin.Util.getString("SystemSource.Parsedouble_desc"), "parseDouble", "double", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Parsedouble_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addParseNumberFunction(SourceSystemFunctions.PARSEFLOAT, QueryPlugin.Util.getString("SystemSource.Parsefloat_desc"), "parseFloat", "float", DataTypeManager.DefaultDataTypes.FLOAT, QueryPlugin.Util.getString("SystemSource.Parsefloat_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addParseNumberFunction(SourceSystemFunctions.PARSEBIGINTEGER, QueryPlugin.Util.getString("SystemSource.Parsebiginteger_desc"), "parseBigInteger", "biginteger", DataTypeManager.DefaultDataTypes.BIG_INTEGER, QueryPlugin.Util.getString("SystemSource.Parsebiginteger_result_desc")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+		addParseNumberFunction(SourceSystemFunctions.PARSEBIGDECIMAL, QueryPlugin.Util.getString("SystemSource.Parsebigdecimal_desc"), "parseBigDecimal", "bigdecimal", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Parsebigdecimal_result_desc"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+	}
+	
+    private void addArithmeticFunction(String functionName, String description, String methodName, String resultsDescription) {
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.INTEGER);
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.LONG);
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.FLOAT);
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.BIG_INTEGER);
+        addTypedArithmeticFunction(functionName, description, methodName, resultsDescription, DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
+    }
+    
+    private void addTypedArithmeticFunction(String functionName, String description, String methodName, String resultsDescription, String type) {
+        functions.add(
+            new FunctionMethod(functionName, description, NUMERIC, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] { 
+                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.Arith_left_op")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.Arith_right_op")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", type, resultsDescription) ) );                 //$NON-NLS-1$
+    }
+    
+    private void addAbsFunction() {
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.INTEGER);
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.LONG);
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.FLOAT);
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER);
+        addTypedAbsFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
+    }
+
+    private void addTypedAbsFunction(String type) {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.ABS, QueryPlugin.Util.getString("SystemSource.Abs_desc"), NUMERIC, FUNCTION_CLASS, "abs", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Abs_arg")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.Abs_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addRandFunction() {
+        // With Seed
+        FunctionMethod rand = new FunctionMethod(SourceSystemFunctions.RAND, QueryPlugin.Util.getString("SystemSource.Rand_desc"), NUMERIC, FUNCTION_CLASS, "rand", //$NON-NLS-1$ //$NON-NLS-2$ 
+                                          new FunctionParameter[] {new FunctionParameter("seed", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rand_arg")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                                          new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Rand_result_desc")) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        rand.setNullOnNull(false);
+        rand.setDeterminism(Determinism.NONDETERMINISTIC);
+        functions.add(rand);
+        // Without Seed
+        rand = new FunctionMethod(SourceSystemFunctions.RAND, QueryPlugin.Util.getString("SystemSource.Rand_desc"), NUMERIC, FUNCTION_CLASS, "rand", //$NON-NLS-1$ //$NON-NLS-2$ 
+                                          new FunctionParameter[] {}, 
+                                          new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Rand_result_desc")) ); //$NON-NLS-1$ //$NON-NLS-2$
+        rand.setDeterminism(Determinism.NONDETERMINISTIC);
+        functions.add(rand);
+    }
+
+	private void addDoubleFunction(String name, String description) {
+		functions.add(
+			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
+				new FunctionParameter[] { 
+					new FunctionParameter("number", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Double_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
+		functions.add(
+				new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
+					new FunctionParameter[] { 
+						new FunctionParameter("number", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Double_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
+	}
+
+	private void addAtan2Function(String name, String description) {
+		functions.add(
+			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
+				new FunctionParameter[] { 
+					new FunctionParameter("number1", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Atan_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("number2", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Atan_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
+		functions.add(
+				new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
+					new FunctionParameter[] { 
+						new FunctionParameter("number1", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Atan_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+						new FunctionParameter("number2", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, QueryPlugin.Util.getString("SystemSource.Atan_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
+	}
+
+	private void addPiFunction(String name, String description) {
+		functions.add(
+			new FunctionMethod(name, description, NUMERIC, FUNCTION_CLASS, name,
+				new FunctionParameter[] { },
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, description) ) );                 //$NON-NLS-1$
+	}
+			
+    private void addPowerFunction() {
+        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.INTEGER);        
+        addTypedPowerFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.INTEGER);
+    }
+
+    private void addTypedPowerFunction(String baseType, String powerType) { 
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.POWER, QueryPlugin.Util.getString("SystemSource.Power_desc"), NUMERIC, FUNCTION_CLASS, "power", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("base", baseType, QueryPlugin.Util.getString("SystemSource.Power_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("power", powerType, QueryPlugin.Util.getString("SystemSource.Power_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", baseType, QueryPlugin.Util.getString("SystemSource.Power_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+
+    private void addRoundFunction() {
+        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.INTEGER);
+        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.FLOAT);
+        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedRoundFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);        
+    }
+
+    private void addTypedRoundFunction(String roundType) { 
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.ROUND, QueryPlugin.Util.getString("SystemSource.Round_desc"), NUMERIC, FUNCTION_CLASS, "round", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("number", roundType, QueryPlugin.Util.getString("SystemSource.Round_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("places", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Round_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", roundType, QueryPlugin.Util.getString("SystemSource.Round_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+
+    private void addSignFunction() {
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.INTEGER);
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.LONG);
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.FLOAT);
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.BIG_INTEGER);
+        addTypedSignFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
+    }
+    
+    private void addTypedSignFunction(String type) {        
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.SIGN, QueryPlugin.Util.getString("SystemSource.Sign_desc"), NUMERIC, FUNCTION_CLASS, "sign", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Sign_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Sign_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    private void addSqrtFunction() {
+        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.LONG);
+        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.DOUBLE);
+        addTypedSqrtFunction(DataTypeManager.DefaultDataTypes.BIG_DECIMAL);
+    }
+    
+    private void addTypedSqrtFunction(String type) {        
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.SQRT, QueryPlugin.Util.getString("SystemSource.Sqrt_desc"), NUMERIC, FUNCTION_CLASS, "sqrt", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("number", type, QueryPlugin.Util.getString("SystemSource.Sqrt_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, QueryPlugin.Util.getString("SystemSource.Sqrt_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    /**
+     * Date functions a marked as command deterministic, since we prefer pre-evaluation rather than row-by-row
+     * evaluation.
+     */
+    private void addConstantDateFunction(String name, String description, String methodName, String returnType) {
+        FunctionMethod method = new FunctionMethod(name, description, DATETIME, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {},
+                new FunctionParameter("result", returnType, description));                 //$NON-NLS-1$
+        method.setDeterminism(Determinism.COMMAND_DETERMINISTIC);
+        functions.add(method);
+    }
+
+    private void addDateFunction(String name, String methodName, String dateDesc, String timestampDesc, String returnType) {
+        functions.add(
+            new FunctionMethod(name, dateDesc, DATETIME, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, dateDesc) }, //$NON-NLS-1$
+                new FunctionParameter("result", returnType, dateDesc) ) );                 //$NON-NLS-1$
+        functions.add(
+            new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
+                new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
+    }
+
+	private void addQuarterFunction(String name, String methodName, String dateDesc, String timestampDesc, String returnType) {
+		functions.add(
+			new FunctionMethod(name, dateDesc, DATETIME, FUNCTION_CLASS, methodName,
+				new FunctionParameter[] {
+					new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, dateDesc) }, //$NON-NLS-1$
+				new FunctionParameter("result", returnType, dateDesc) ) );                 //$NON-NLS-1$
+		functions.add(
+			new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
+				new FunctionParameter[] {
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
+				new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
+	}
+
+	private void addTimestampAddFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_desc"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
+				new FunctionParameter[] {
+					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Timestampadd_d_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_desc"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$  
+				new FunctionParameter[] {
+					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Timestampadd_t_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.TIMESTAMPADD, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_desc"), DATETIME, FUNCTION_CLASS, "timestampAdd", //$NON-NLS-1$ //$NON-NLS-2$ 
+				new FunctionParameter[] {
+					new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg2")),  //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampadd_ts_result")) ) );			                //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+    private void addTimestampDiffFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.TIMESTAMPDIFF, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_desc"), DATETIME, FUNCTION_CLASS, "timestampDiff", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("interval", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("timestamp1", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("timestamp2", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_arg3"))}, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.LONG, QueryPlugin.Util.getString("SystemSource.Timestampdiff_ts_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addTimestampCreateFunction() {
+        functions.add(
+              new FunctionMethod(SourceSystemFunctions.TIMESTAMPCREATE, QueryPlugin.Util.getString("SystemSource.TimestampCreate_desc"), DATETIME, FUNCTION_CLASS, "timestampCreate", //$NON-NLS-1$ //$NON-NLS-2$ 
+                  new FunctionParameter[] {
+                      new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.TimestampCreate_arg1")),  //$NON-NLS-1$ //$NON-NLS-2$
+                      new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.TimestampCreate_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+                  new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.TimestampCreate_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+   
+    private void addTimeFunction(String name, String methodName, String timeDesc, String timestampDesc, String returnType) {
+        functions.add(
+            new FunctionMethod(name, timeDesc, DATETIME, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, timeDesc) }, //$NON-NLS-1$
+                new FunctionParameter("result", returnType, timeDesc) ) );                 //$NON-NLS-1$
+        functions.add(
+            new FunctionMethod(name, timestampDesc, DATETIME, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, timestampDesc) }, //$NON-NLS-1$
+                new FunctionParameter("result", returnType, timestampDesc) ) );                 //$NON-NLS-1$
+    }
+    
+    private void addStringFunction(String name, String description, String methodName, String returnType) {
+        functions.add(
+            new FunctionMethod(name, description, STRING, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Stringfunc_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", returnType, description) ) );                 //$NON-NLS-1$
+    }
+    
+    private void addClobFunction(String name, String description, String methodName, String returnType) {
+        functions.add(
+            new FunctionMethod(name, description, STRING, PushDown.MUST_PUSHDOWN, FUNCTION_CLASS, methodName,
+                new FunctionParameter[] {
+                    new FunctionParameter("clob", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.Clobfunc_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", returnType, description), false, Determinism.DETERMINISTIC ) );                 //$NON-NLS-1$
+    }
+
+    private void addConcatFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.CONCAT, QueryPlugin.Util.getString("SystemSource.Concat_desc"), STRING, FUNCTION_CLASS, "concat", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod("||", QueryPlugin.Util.getString("SystemSource.Concatop_desc"), STRING, FUNCTION_CLASS, "concat", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter[] {
+                    new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concatop_result_desc")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        
+        FunctionMethod concat2 = new FunctionMethod("concat2", QueryPlugin.Util.getString("SystemSource.Concat_desc"), STRING, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ //$NON-NLS-2$ 
+                           new FunctionParameter[] {
+                               new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                               new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                           new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Concat_result_desc")), true, Determinism.DETERMINISTIC ); //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(concat2);                         
+    }
+
+    private void addSubstringFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.SUBSTRING, QueryPlugin.Util.getString("SystemSource.Substring_desc"), STRING, FUNCTION_CLASS, "substring", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.SUBSTRING, QueryPlugin.Util.getString("SystemSource.Susbstring2_desc"), STRING, FUNCTION_CLASS, "substring", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Substring2_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Substring2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addLeftRightFunctions() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.LEFT, QueryPlugin.Util.getString("SystemSource.Left_desc"), STRING, FUNCTION_CLASS, "left", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Left_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Left_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Left2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.RIGHT, QueryPlugin.Util.getString("SystemSource.Right_desc"), STRING, FUNCTION_CLASS, "right", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Right_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Right_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Right2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+           
+    private void addLocateFunction() {
+        FunctionMethod func =
+            new FunctionMethod(SourceSystemFunctions.LOCATE, QueryPlugin.Util.getString("SystemSource.Locate_desc"), STRING, FUNCTION_CLASS, "locate", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("index", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate_result")) );                 //$NON-NLS-1$ //$NON-NLS-2$
+        func.setNullOnNull(false);
+        functions.add(func);
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.LOCATE, QueryPlugin.Util.getString("SystemSource.Locate2_desc"), STRING, FUNCTION_CLASS, "locate", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Locate2_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Locate2_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addReplaceFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.REPLACE, QueryPlugin.Util.getString("SystemSource.Replace_desc"), STRING, FUNCTION_CLASS, "replace", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("substring", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("replacement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Replace_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+	private void addRepeatFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.REPEAT, QueryPlugin.Util.getString("SystemSource.Repeat_desc"), STRING, FUNCTION_CLASS, "repeat", //$NON-NLS-1$ //$NON-NLS-2$ 
+				new FunctionParameter[] {
+					new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Repeat_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Repeat_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Repeat_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	private void addSpaceFunction() {
+		functions.add(
+			new FunctionMethod(FunctionLibrary.SPACE, QueryPlugin.Util.getString("SystemSource.Space_desc"), STRING, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
+				new FunctionParameter[] {
+					new FunctionParameter("count", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Space_arg1"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Space_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	private void addInsertFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.INSERT, QueryPlugin.Util.getString("SystemSource.Insert_desc"), STRING, FUNCTION_CLASS, "insert", //$NON-NLS-1$ //$NON-NLS-2$ 
+				new FunctionParameter[] {
+					new FunctionParameter("str1", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("start", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Insert_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Insert_arg3")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("str2", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_arg4")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Insert_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	private void addToCharsFunction() {
+		functions.add(
+			new FunctionMethod("to_chars", QueryPlugin.Util.getString("SystemSource.encode_desc"), CONVERSION, FUNCTION_CLASS, "toChars", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$  
+				new FunctionParameter[] {
+					new FunctionParameter("value", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.encode_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("encoding", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.encode_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.encode_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	private void addToBytesFunction() {
+		functions.add(
+			new FunctionMethod("to_bytes", QueryPlugin.Util.getString("SystemSource.decode_desc"), CONVERSION, FUNCTION_CLASS, "toBytes", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$  
+				new FunctionParameter[] {
+					new FunctionParameter("value", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.decode_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("encoding", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.decode_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.decode_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+    private void addAsciiFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.ASCII, QueryPlugin.Util.getString("SystemSource.Ascii_desc"), STRING, FUNCTION_CLASS, "ascii", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Ascii_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Ascii_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.ASCII, QueryPlugin.Util.getString("SystemSource.Ascii2_desc"), STRING, FUNCTION_CLASS, "ascii", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Ascii2_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Ascii2_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+	private void addCharFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.CHAR, QueryPlugin.Util.getString("SystemSource.Char_desc"), STRING, FUNCTION_CLASS, "chr", //$NON-NLS-1$ //$NON-NLS-2$ 
+				new FunctionParameter[] {
+					new FunctionParameter("code", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Char_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Char_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+                new FunctionMethod("chr", QueryPlugin.Util.getString("SystemSource.Chr_desc"), STRING, FUNCTION_CLASS, "chr", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    new FunctionParameter[] {
+                        new FunctionParameter("code", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Chr_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CHAR, QueryPlugin.Util.getString("SystemSource.Chr_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+    private void addInitCapFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.INITCAP, QueryPlugin.Util.getString("SystemSource.Initcap_desc"), STRING, FUNCTION_CLASS, "initCap", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Initcap_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Initcap_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addLpadFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.LPAD, QueryPlugin.Util.getString("SystemSource.Lpad_desc"), STRING, FUNCTION_CLASS, "lpad", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Lpad_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.LPAD, QueryPlugin.Util.getString("SystemSource.Lpad3_desc"), STRING, FUNCTION_CLASS, "lpad", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Lpad3_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lpad3_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addRpadFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.RPAD, QueryPlugin.Util.getString("SystemSource.Rpad1_desc"), STRING, FUNCTION_CLASS, "rpad", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad1_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rpad1_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad1_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.RPAD, QueryPlugin.Util.getString("SystemSource.Rpad3_desc"), STRING, FUNCTION_CLASS, "rpad", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("length", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rpad3_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("char", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Rpad3_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addTranslateFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.TRANSLATE, QueryPlugin.Util.getString("SystemSource.Translate_desc"), STRING, FUNCTION_CLASS, "translate", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("source", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("destination", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Translate_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addConversionFunctions() {
+    	for (String type : DataTypeManager.getAllDataTypeNames()) {
+            addTypedConversionFunction(SourceSystemFunctions.CONVERT, type); 
+            addTypedConversionFunction("cast", type); //$NON-NLS-1$
+    	}
+    }
+    
+    private void addTypedConversionFunction(String name, String sourceType) {
+        functions.add(
+            new FunctionMethod(name, QueryPlugin.Util.getString("SystemSource.Convert_desc", sourceType), CONVERSION, FUNCTION_CLASS, "convert", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] {
+                    new FunctionParameter("value", sourceType, QueryPlugin.Util.getString("SystemSource.Convert_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("target", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Convert_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.OBJECT, QueryPlugin.Util.getString("SystemSource.Convert_result")) ) );                 //$NON-NLS-1$ //$NON-NLS-2$
+    
+    }    
+
+    private void addContextFunctions() {
+    	for (String contextType : DataTypeManager.getAllDataTypeNames()) {
+    		for (String exprType : DataTypeManager.getAllDataTypeNames()) {
+                addTypedContextFunction(contextType, exprType);
+        	}
+    	}
+    }
+    
+    private void addTypedContextFunction(String contextType, String exprType) {
+        functions.add(
+            new FunctionMethod("context", QueryPlugin.Util.getString("SystemSource.Context_desc"), MISCELLANEOUS, FUNCTION_CLASS, "context", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter[] {
+                    new FunctionParameter("context", contextType, QueryPlugin.Util.getString("SystemSource.Context_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Context_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", exprType, QueryPlugin.Util.getString("SystemSource.Context_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    } 
+    
+    private void addRowLimitFunctions() {
+    	for (String exprType : DataTypeManager.getAllDataTypeNames()) {
+            functions.add(
+                    new FunctionMethod("rowlimit", QueryPlugin.Util.getString("SystemSource.Rowlimit_desc"), MISCELLANEOUS, FUNCTION_CLASS, "rowlimit", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                        new FunctionParameter[] {
+                            new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Rowlimit_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rowlimit_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+    }
+    
+    private void addRowLimitExceptionFunctions() {
+    	for (String exprType : DataTypeManager.getAllDataTypeNames()) {
+            functions.add(
+                    new FunctionMethod("rowlimitexception", QueryPlugin.Util.getString("SystemSource.RowlimitException_desc"), MISCELLANEOUS, FUNCTION_CLASS, "rowlimitexception", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                        new FunctionParameter[] {
+                            new FunctionParameter("element", exprType, QueryPlugin.Util.getString("SystemSource.Rowlimit_arg1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Rowlimit_result")) ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+    }    
+    
+    private void addDecodeFunctions(){
+        addDecodeFunction("decodeInteger", DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        addDecodeFunction("decodeString", DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+    }
+        
+    private void addDecodeFunction(String functionName, String resultType) {
+        functions.add(
+            new FunctionMethod(functionName, QueryPlugin.Util.getString("SystemSource.Decode1_desc"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+                new FunctionParameter[] { 
+                    new FunctionParameter("input", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode1_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("decodeString", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode1_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", resultType, QueryPlugin.Util.getString("SystemSource.Decode1_result") ) ) );    //$NON-NLS-1$ //$NON-NLS-2$
+                     
+        functions.add(
+            new FunctionMethod(functionName, QueryPlugin.Util.getString("SystemSource.Decode2_desc"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+                new FunctionParameter[] { 
+                    new FunctionParameter("input", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("decodeString", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("delimiter", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Decode2_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", resultType, QueryPlugin.Util.getString("SystemSource.Decode2_result") ) ) );    //$NON-NLS-1$ //$NON-NLS-2$
+
+    }
+
+    private void addLookupFunctions() {
+    	for (String keyValueType : DataTypeManager.getAllDataTypeNames()) {
+            functions.add(
+                    new FunctionMethod("lookup", QueryPlugin.Util.getString("SystemSource.Lookup_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "lookup", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                        new FunctionParameter[] {
+                            new FunctionParameter("codetable", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                            new FunctionParameter("returnelement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg2")), //$NON-NLS-1$ //$NON-NLS-2$
+                            new FunctionParameter("keyelement", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Lookup_arg3")), //$NON-NLS-1$ //$NON-NLS-2$
+                            new FunctionParameter("keyvalue", keyValueType, QueryPlugin.Util.getString("SystemSource.Lookup_arg4")), //$NON-NLS-1$ //$NON-NLS-2$
+                             },
+                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.OBJECT, QueryPlugin.Util.getString("SystemSource.Lookup_result")), true, Determinism.VDB_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    	}
+    }
+
+    private void addUserFunction() {
+        functions.add(
+            new FunctionMethod("user", QueryPlugin.Util.getString("SystemSource.User_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "user", null, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.User_result")), false, Determinism.USER_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addCurrentDatabaseFunction() {
+        functions.add(
+            new FunctionMethod("current_database", QueryPlugin.Util.getString("SystemSource.current_database_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "current_database", null, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("current_database_result")), false, Determinism.VDB_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    private void addEnvFunction() {
+        functions.add(
+            new FunctionMethod("env", QueryPlugin.Util.getString("SystemSource.Env_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "env", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter[] {
+                    new FunctionParameter("variablename", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Env_varname")) //$NON-NLS-1$ //$NON-NLS-2$
+                     },
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Env_result")), false, Determinism.SESSION_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addSessionIdFunction() {
+        functions.add(
+            new FunctionMethod(FunctionLibrary.SESSION_ID, QueryPlugin.Util.getString("SystemSource.session_id_desc"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "session_id", null, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.session_id_result")), false, Determinism.SESSION_DETERMINISTIC) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    private void addCommandPayloadFunctions() {
+        functions.add(
+            new FunctionMethod("commandpayload", QueryPlugin.Util.getString("SystemSource.CommandPayload_desc0"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "commandPayload", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                 new FunctionParameter[] {},
+                 new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_result")), false, Determinism.COMMAND_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(
+            new FunctionMethod("commandpayload", QueryPlugin.Util.getString("SystemSource.CommandPayload_desc1"), MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, FUNCTION_CLASS, "commandPayload", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                 new FunctionParameter[] {
+                     new FunctionParameter("property", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_property")) //$NON-NLS-1$ //$NON-NLS-2$
+                      },
+                 new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.CommandPayload_result")), false, Determinism.COMMAND_DETERMINISTIC ) );                     //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addIfNullFunctions() {
+    	for (String type : DataTypeManager.getAllDataTypeNames()) {
+            addNvlFunction(type);
+            addIfNullFunction(type);
+    	}
+    }
+	
+    private void addNvlFunction(String valueType) {
+        FunctionMethod nvl = 
+            new FunctionMethod("nvl", QueryPlugin.Util.getString("SystemSource.Nvl_desc"), MISCELLANEOUS, FUNCTION_CLASS, "ifnull", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                new FunctionParameter[] {
+                    new FunctionParameter("value", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("valueIfNull", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", valueType, QueryPlugin.Util.getString("SystemSource.Nvl_result")) ); //$NON-NLS-1$ //$NON-NLS-2$
+        nvl.setNullOnNull(false);
+        functions.add(nvl); 
+    }
+
+	private void addIfNullFunction(String valueType) {
+		FunctionMethod nvl = 
+			new FunctionMethod("ifnull", QueryPlugin.Util.getString("SystemSource.Ifnull_desc"), MISCELLANEOUS, FUNCTION_CLASS, "ifnull", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				new FunctionParameter[] {
+					new FunctionParameter("value", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("valueIfNull", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", valueType, QueryPlugin.Util.getString("SystemSource.Ifnull_result")) ); //$NON-NLS-1$ //$NON-NLS-2$
+        nvl.setNullOnNull(false);
+        functions.add(nvl); 
+	}
+			
+	private void addFormatTimestampFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.FORMATTIMESTAMP, QueryPlugin.Util.getString("SystemSource.Formattimestamp_desc"),CONVERSION, FUNCTION_CLASS, "format", //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter[] { 
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Formattimestamp_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattimestamp_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattimestamp_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+				new FunctionMethod(FunctionLibrary.FORMATDATE, QueryPlugin.Util.getString("SystemSource.Formatdate_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+					new FunctionParameter[] { 
+						new FunctionParameter("date", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Formatdate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatdate_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatdate_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+				new FunctionMethod(FunctionLibrary.FORMATTIME, QueryPlugin.Util.getString("SystemSource.Formattime_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+					new FunctionParameter[] { 
+						new FunctionParameter("time", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Formattime_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattime_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formattime_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+	}
+					
+	private void addParseTimestampFunction() {
+		functions.add(
+			new FunctionMethod(SourceSystemFunctions.PARSETIMESTAMP, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_desc"),CONVERSION, FUNCTION_CLASS, "parseTimestamp", //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter[] { 
+					new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.Parsetimestamp_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+				new FunctionMethod(FunctionLibrary.PARSETIME, QueryPlugin.Util.getString("SystemSource.Parsetime_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+					new FunctionParameter[] { 
+						new FunctionParameter("time", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetime_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsetime_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIME, QueryPlugin.Util.getString("SystemSource.Parsetime_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+		functions.add(
+				new FunctionMethod(FunctionLibrary.PARSEDATE, QueryPlugin.Util.getString("SystemSource.Parsedate_desc"),CONVERSION, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$
+					new FunctionParameter[] { 
+						new FunctionParameter("date", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsedate_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsedate_arg2")) }, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DATE, QueryPlugin.Util.getString("SystemSource.Parsedate_result_desc")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	private void addFormatNumberFunction(String functionName, String description, String methodName, String inputParam, String dataType,  String resultDesc) {
+		functions.add(
+			new FunctionMethod(functionName, description, CONVERSION, FUNCTION_CLASS, methodName,
+				new FunctionParameter[] { 
+					new FunctionParameter(inputParam, dataType, QueryPlugin.Util.getString("SystemSource.Formatnumber_arg1")), //$NON-NLS-1$
+					new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Formatnumber_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+				new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, resultDesc) ) );       //$NON-NLS-1$
+	}
+		
+	private void addParseNumberFunction(String functionName, String description, String methodName, String inputParam, String dataType,  String resultDesc) {
+			functions.add(
+				new FunctionMethod(functionName, description, CONVERSION, FUNCTION_CLASS, methodName,
+					new FunctionParameter[] { 
+						new FunctionParameter(inputParam, DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsenumber_arg1")), //$NON-NLS-1$
+						new FunctionParameter("format", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.Parsenumber_arg2"))}, //$NON-NLS-1$ //$NON-NLS-2$
+					new FunctionParameter("result", dataType, resultDesc) ) );       //$NON-NLS-1$
+	}
+    
+    private void addBitFunction(String functionName, String description, String methodName, int parameters, String resultDescription) {
+        FunctionParameter[] paramArray = null;
+        if (parameters == 1) {
+            paramArray = new FunctionParameter[] {
+                new FunctionParameter("integer", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc_arg1")) //$NON-NLS-1$ //$NON-NLS-2$
+            };
+        } else if (parameters == 2) {
+            paramArray = new FunctionParameter[] {
+                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc2_arg1")), //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("integer2", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.Bitfunc2_arg2")) //$NON-NLS-1$ //$NON-NLS-2$
+            };
+        }
+        functions.add(
+            new FunctionMethod(functionName, description, NUMERIC, FUNCTION_CLASS, methodName,
+                paramArray,
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, resultDescription) //$NON-NLS-1$
+            )
+        );
+    }
+    
+    private void addXpathValueFunction() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter[] { 
+                                new FunctionParameter("document", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+
+        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("document", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+        
+        functions.add(new FunctionMethod(SourceSystemFunctions.XPATHVALUE, QueryPlugin.Util.getString("SystemSource.xpathvalue_description"), XML, XML_FUNCTION_CLASS, "xpathValue", //$NON-NLS-1$ //$NON-NLS-2$ 
+                                         new FunctionParameter[] { 
+                                             new FunctionParameter("document", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xpath_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                             new FunctionParameter("xpath", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpath_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                                         new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xpathvalue_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addXslTransformFunction() {
+    	for (String type1 : Arrays.asList(DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.XML, DataTypeManager.DefaultDataTypes.CLOB)) {
+    		for (String type2 : Arrays.asList(DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.XML, DataTypeManager.DefaultDataTypes.CLOB)) {
+    	        functions.add(new FunctionMethod(SourceSystemFunctions.XSLTRANSFORM, QueryPlugin.Util.getString("SystemSource.xsltransform_description"), XML, XML_FUNCTION_CLASS, "xslTransform", //$NON-NLS-1$ //$NON-NLS-2$  
+                        new FunctionParameter[] { 
+                            new FunctionParameter("document", type1, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                            new FunctionParameter("xsl", type2, QueryPlugin.Util.getString("SystemSource.xsltransform_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                        new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.xsltransform_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    		}
+    	}
+    }
+    
+    private void addXmlComment() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.XMLCOMMENT, QueryPlugin.Util.getString("SystemSource.xmlcomment_description"), XML, XML_FUNCTION_CLASS, "xmlComment", //$NON-NLS-1$ //$NON-NLS-2$  
+                            new FunctionParameter[] { 
+                                new FunctionParameter("value", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlcomment_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlcomment_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    private void addXmlPi() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.XMLPI, QueryPlugin.Util.getString("SystemSource.xmlpi_description"), XML, XML_FUNCTION_CLASS, "xmlPi", //$NON-NLS-1$ //$NON-NLS-2$  
+                            new FunctionParameter[] { 
+					            new FunctionParameter("name", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param1"))}, //$NON-NLS-1$ //$NON-NLS-2$
+                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlpi_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+        
+        functions.add(new FunctionMethod(SourceSystemFunctions.XMLPI, QueryPlugin.Util.getString("SystemSource.xmlpi_description"), XML, XML_FUNCTION_CLASS, "xmlPi", //$NON-NLS-1$ //$NON-NLS-2$  
+                new FunctionParameter[] { 
+		            new FunctionParameter("name", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+		            new FunctionParameter("value", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlpi_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlpi_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addJsonToXml() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.JSONTOXML, QueryPlugin.Util.getString("SystemSource.jsonToXml_description"), XML, XML_FUNCTION_CLASS, "jsonToXml", //$NON-NLS-1$ //$NON-NLS-2$  
+                new FunctionParameter[] { 
+        	new FunctionParameter("rootElementName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.jsonToXml_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+        	new FunctionParameter("json", DataTypeManager.DefaultDataTypes.CLOB, QueryPlugin.Util.getString("SystemSource.jsonToXml_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.jsonToXml_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+        functions.add(new FunctionMethod(SourceSystemFunctions.JSONTOXML, QueryPlugin.Util.getString("SystemSource.jsonToXml_description"), XML, XML_FUNCTION_CLASS, "jsonToXml", //$NON-NLS-1$ //$NON-NLS-2$  
+                new FunctionParameter[] { 
+        	new FunctionParameter("rootElementName", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.jsonToXml_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+        	new FunctionParameter("json", DataTypeManager.DefaultDataTypes.BLOB, QueryPlugin.Util.getString("SystemSource.jsonToXml_param2"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.jsonToXml_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addXmlConcat() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.XMLCONCAT, QueryPlugin.Util.getString("SystemSource.xmlconcat_description"), XML, PushDown.CAN_PUSHDOWN, XML_FUNCTION_CLASS, "xmlConcat", //$NON-NLS-1$ //$NON-NLS-2$  
+                            new FunctionParameter[] { 
+                                new FunctionParameter("param1", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                new FunctionParameter("param2", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_param2"), true)}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlconcat_result")), true, Determinism.DETERMINISTIC ) );       //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addTimeZoneFunctions() {
+        functions.add(new FunctionMethod(SourceSystemFunctions.MODIFYTIMEZONE, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_description"), DATETIME, FUNCTION_CLASS, "modifyTimeZone", //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter[] { 
+                                new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                new FunctionParameter("startTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param2")), //$NON-NLS-1$ //$NON-NLS-2$
+                                new FunctionParameter("endTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param3"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+
+        functions.add(new FunctionMethod(SourceSystemFunctions.MODIFYTIMEZONE, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_description"), DATETIME, FUNCTION_CLASS, "modifyTimeZone", //$NON-NLS-1$ //$NON-NLS-2$ 
+                                         new FunctionParameter[] { 
+                                             new FunctionParameter("timestamp", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                                             new FunctionParameter("endTimeZone", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_param3"))}, //$NON-NLS-1$ //$NON-NLS-2$ 
+                                         new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.modifyTimeZone_result")) ) );       //$NON-NLS-1$ //$NON-NLS-2$
+
+    }
+    
+    private void addUnixTimeFunctions() {
+    	functions.add(new FunctionMethod(FunctionLibrary.FROM_UNIXTIME, QueryPlugin.Util.getString("SystemSource.from_unixtime_description"), DATETIME, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
+    			new FunctionParameter[] {
+    				new FunctionParameter("unix_timestamp", DataTypeManager.DefaultDataTypes.INTEGER, QueryPlugin.Util.getString("SystemSource.from_unixtime_param1")) //$NON-NLS-1$ //$NON-NLS-2$
+    			},
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.TIMESTAMP, QueryPlugin.Util.getString("SystemSource.from_unixtime_result")), false, Determinism.DETERMINISTIC )); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addTypedNullIfFunction(String type) {
+        functions.add(
+            new FunctionMethod(FunctionLibrary.NULLIF, QueryPlugin.Util.getString("SystemSource.nullif_description"), MISCELLANEOUS, PushDown.SYNTHETIC, null, null, //$NON-NLS-1$ 
+                new FunctionParameter[] { 
+                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.nullif_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.nullif_param1")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.nullif_result")), true, Determinism.DETERMINISTIC)); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    private void addTypedCoalesceFunction(String type) {
+        functions.add(
+            new FunctionMethod(FunctionLibrary.COALESCE, QueryPlugin.Util.getString("SystemSource.coalesce_description"), MISCELLANEOUS, PushDown.CAN_PUSHDOWN, FUNCTION_CLASS, "coalesce", //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter[] { 
+                    new FunctionParameter("op1", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("op2", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("op3", type, QueryPlugin.Util.getString("SystemSource.coalesce_param1"), true) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", type, QueryPlugin.Util.getString("SystemSource.coalesce_result")), true, Determinism.DETERMINISTIC)); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+		
+    /**
+     * Get all function signatures for this metadata source.
+     * @return Unordered collection of {@link FunctionMethod}s
+     */
+    public Collection<org.teiid.metadata.FunctionMethod> getFunctionMethods() {
+        return this.functions;
+	}
+    
+    /**
+     * Sources are returned from the system classpath.
+     * @param className Name of class
+     * @return Class reference  
+     * @throws ClassNotFoundException If class could not be found
+     */
+    public Class<?> getInvocationClass(String className) throws ClassNotFoundException {
+        return Class.forName(className);    
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,394 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.relational.OptimizerRule;
-import org.teiid.query.optimizer.relational.RuleStack;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.NodeEditor;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.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.SingleElementSymbol;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.util.CommandContext;
-
-
-public final class RuleMergeVirtual implements
-                                   OptimizerRule {
-
-    public PlanNode execute(PlanNode plan,
-                            QueryMetadataInterface metadata,
-                            CapabilitiesFinder capFinder,
-                            RuleStack rules,
-                            AnalysisRecord analysisRecord,
-                            CommandContext context) throws QueryPlannerException,
-                                                   QueryMetadataException,
-                                                   TeiidComponentException {
-
-        for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
-            if (sourceNode.getChildCount() > 0) {
-                plan = doMerge(sourceNode, plan, metadata);
-            }
-        }
-
-        return plan;
-    }
-
-    static PlanNode doMerge(PlanNode frame,
-                            PlanNode root,
-                            QueryMetadataInterface metadata) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
-
-        GroupSymbol virtualGroup = frame.getGroups().iterator().next();
-
-        // check to see if frame represents a proc relational query.
-        if (virtualGroup.isProcedure()) {
-            return root;
-        }
-        
-        SymbolMap references = (SymbolMap)frame.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
-        if (references != null) {
-        	return root; //correlated nested table commands should not be merged
-        }
-
-        PlanNode parentProject = NodeEditor.findParent(frame, NodeConstants.Types.PROJECT);
-
-        // Check whether the upper frame is a SELECT INTO
-        if (parentProject.getProperty(NodeConstants.Info.INTO_GROUP) != null) {
-            return root;
-        }
-
-        if (!FrameUtil.canConvertAccessPatterns(frame)) {
-            return root;
-        }
-
-        PlanNode projectNode = frame.getFirstChild();
-
-        // Check if lower frame has only a stored procedure execution - this cannot be merged to parent frame
-        if (FrameUtil.isProcedure(projectNode)) {
-            return root;
-        }
-        
-        SymbolMap symbolMap = (SymbolMap)frame.getProperty(NodeConstants.Info.SYMBOL_MAP);
-        
-        PlanNode sortNode = NodeEditor.findParent(parentProject, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
-        
-        if (sortNode != null && sortNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT)) {
-        	OrderBy sortOrder = (OrderBy)sortNode.getProperty(NodeConstants.Info.SORT_ORDER);
-        	boolean unrelated = false;
-        	for (OrderByItem item : sortOrder.getOrderByItems()) {
-        		if (!item.isUnrelated()) {
-        			continue;
-        		}
-        		Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(item.getSymbol(), true);
-        		for (ElementSymbol elementSymbol : elements) {
-					if (virtualGroup.equals(elementSymbol.getGroupSymbol())) {
-						unrelated = true;
-						if (!(symbolMap.getMappedExpression(elementSymbol) instanceof ElementSymbol)) {
-							return root;
-						}
-					}
-				}
-			}
-        	// the lower frame cannot contain DUP_REMOVE, GROUP, UNION if unrelated
-        	if (unrelated && NodeEditor.findNodePreOrder(frame, NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT) != null
-        			|| NodeEditor.findNodePreOrder(frame, NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE) != null
-        			|| NodeEditor.findNodePreOrder(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE) != null) {
-        		return root;
-        	}
-        }
-
-        //try to remove the virtual layer if we are only doing a simple projection in the following cases:
-        // 1. if the frame root is something other than a project (SET_OP, SORT, LIMIT, etc.)
-        // 2. if the frame has a grouping node
-        // 3. if the frame has no sources
-        if (projectNode.getType() != NodeConstants.Types.PROJECT
-            || NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE
-                                                                                             | NodeConstants.Types.JOIN) != null
-            || NodeEditor.findAllNodes(frame.getFirstChild(), NodeConstants.Types.SOURCE, NodeConstants.Types.SOURCE).isEmpty()) {
-            return checkForSimpleProjection(frame, root, parentProject, metadata);
-        }
-
-        PlanNode parentJoin = NodeEditor.findParent(frame, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
-
-        if (!checkJoinCriteria(frame, virtualGroup, parentJoin)) {
-            return root;
-        }
-        
-        PlanNode parentGroup = NodeEditor.findParent(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE);
-        List<SingleElementSymbol> groupCols = null;
-        if (parentGroup != null) {
-        	groupCols = (List<SingleElementSymbol>)parentGroup.getProperty(NodeConstants.Info.GROUP_COLS);
-        }
-
-        if (!checkProjectedSymbols(projectNode, virtualGroup, parentJoin, groupCols, symbolMap, metadata)) {
-            return root;
-        }
-
-        // Otherwise merge should work
-
-        // Convert parent frame before merge
-        FrameUtil.convertFrame(frame, virtualGroup, FrameUtil.findJoinSourceNode(projectNode).getGroups(), symbolMap.asMap(), metadata);
-
-        PlanNode parentBottom = frame.getParent();
-        prepareFrame(frame);
-
-        // Remove top 2 nodes (SOURCE, PROJECT) of virtual group - they're no longer needed
-        NodeEditor.removeChildNode(parentBottom, frame);
-        NodeEditor.removeChildNode(parentBottom, projectNode);
-
-        return root;
-    }
-
-    private static void prepareFrame(PlanNode frame) {
-        // find the new root of the frame so that access patterns can be propagated
-        PlanNode newRoot = FrameUtil.findJoinSourceNode(frame.getFirstChild());
-        if (newRoot != null) {
-            Collection ap = (Collection)frame.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
-            if (ap != null) {
-                Collection newAp = (Collection)newRoot.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
-                if (newAp == null) {
-                    newRoot.setProperty(NodeConstants.Info.ACCESS_PATTERNS, ap);
-                } else {
-                    newAp.addAll(ap);
-                }
-            }
-            RulePlaceAccess.copyDependentHints(frame, newRoot);
-        }
-    }
-
-    /**
-     * Removes source layers that only do a simple projection of the elements below.
-     * @throws TeiidComponentException 
-     * @throws QueryMetadataException 
-     */
-    private static PlanNode checkForSimpleProjection(PlanNode frame,
-                                                     PlanNode root,
-                                                     PlanNode parentProject,
-                                                     QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-        // check that the parent only performs projection
-        PlanNode nodeToCheck = parentProject.getFirstChild();
-        while (nodeToCheck != frame) {
-            if (nodeToCheck.getType() != NodeConstants.Types.SELECT
-                || !nodeToCheck.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
-                return root;
-            }
-            nodeToCheck = nodeToCheck.getFirstChild();
-        }
-        
-        if (frame.getFirstChild().getType() == NodeConstants.Types.TUPLE_LIMIT
-            && NodeEditor.findParent(parentProject,
-                                     NodeConstants.Types.SORT | NodeConstants.Types.DUP_REMOVE,
-                                     NodeConstants.Types.SOURCE) != null) {
-            return root;
-        }
-        
-        List<? extends SingleElementSymbol> requiredElements = RuleAssignOutputElements.determineSourceOutput(frame, new ArrayList<SingleElementSymbol>(), metadata, null);
-        List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)parentProject.getProperty(NodeConstants.Info.PROJECT_COLS);
-
-        // check that it only performs simple projection and that all required symbols are projected
-        LinkedHashSet<ElementSymbol> symbols = new LinkedHashSet<ElementSymbol>(); //ensuring there are no duplicates prevents problems with subqueries  
-        for (SingleElementSymbol symbol : selectSymbols) {
-            Expression expr = SymbolMap.getExpression(symbol);
-            if (!(expr instanceof ElementSymbol)) {
-                return root;
-            }
-            requiredElements.remove(expr);
-            if (!symbols.add((ElementSymbol)expr)) {
-                return root;
-            }
-        }
-        if (!requiredElements.isEmpty()) {
-            return root;
-        }
-        
-        // re-order the lower projects
-        RuleAssignOutputElements.filterVirtualElements(frame, new ArrayList<SingleElementSymbol>(symbols), metadata);
-
-        // remove phantom select nodes
-        nodeToCheck = parentProject.getFirstChild();
-        while (nodeToCheck != frame) {
-            PlanNode current = nodeToCheck;
-            nodeToCheck = nodeToCheck.getFirstChild();
-            NodeEditor.removeChildNode(current.getParent(), current);
-        }
-        
-        if (NodeEditor.findParent(parentProject, NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.SOURCE) != null) {
-            PlanNode lowerDup = NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT);
-            if (lowerDup != null) {
-                NodeEditor.removeChildNode(lowerDup.getParent(), lowerDup);
-            }
-
-            PlanNode setOp = NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE);
-            if (setOp != null) {
-                setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
-                if (parentProject.getParent().getParent() != null) {
-                    NodeEditor.removeChildNode(parentProject.getParent().getParent(), parentProject.getParent());
-                } else {
-                    parentProject.removeFromParent();
-                    root = parentProject;
-                }
-            }
-        }
-        
-        PlanNode sort = NodeEditor.findParent(parentProject, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
-        if (sort != null) { //special handling is needed since we are retaining the child aliases
-        	List<SingleElementSymbol> childProject = (List<SingleElementSymbol>)NodeEditor.findNodePreOrder(frame, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS);
-        	OrderBy elements = (OrderBy)sort.getProperty(NodeConstants.Info.SORT_ORDER);
-        	for (OrderByItem item : elements.getOrderByItems()) {
-				item.setSymbol(childProject.get(selectSymbols.indexOf(item.getSymbol())));
-			}
-            sort.getGroups().clear();
-            sort.addGroups(GroupsUsedByElementsVisitor.getGroups(elements));
-        }
-        
-        prepareFrame(frame);
-        
-        //remove the parent project and the source node
-        NodeEditor.removeChildNode(parentProject, frame);
-        if (parentProject.getParent() == null) {
-            root = parentProject.getFirstChild();
-            parentProject.removeChild(root);
-            return root;
-        } 
-        NodeEditor.removeChildNode(parentProject.getParent(), parentProject);
-                 
-        return root;
-    }
-    
-    /**
-     * Check to ensure that we are not projecting a subquery or null dependent expressions
-     */
-    private static boolean checkProjectedSymbols(PlanNode projectNode,
-                                                 GroupSymbol virtualGroup,
-                                                 PlanNode parentJoin,
-                                                 List<SingleElementSymbol> parentGroupingCols,
-                                                 SymbolMap symbolMap,
-                                                 QueryMetadataInterface metadata) {
-        List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)projectNode.getProperty(NodeConstants.Info.PROJECT_COLS);
-        
-        HashSet<GroupSymbol> groups = new HashSet<GroupSymbol>();
-        for (PlanNode sourceNode : NodeEditor.findAllNodes(projectNode, NodeConstants.Types.SOURCE, NodeConstants.Types.SOURCE)) {
-            groups.addAll(sourceNode.getGroups());
-        }
-
-        boolean checkForNullDependent = false;
-        // check to see if there are projected literal on the inner side of an outer join that needs to be preserved
-        if (parentJoin != null) {
-            PlanNode joinToTest = parentJoin;
-            while (joinToTest != null) {
-                JoinType joinType = (JoinType)joinToTest.getProperty(NodeConstants.Info.JOIN_TYPE);
-                if (joinType == JoinType.JOIN_FULL_OUTER) {
-                    checkForNullDependent = true;
-                    break;
-                } else if (joinType == JoinType.JOIN_LEFT_OUTER
-                           && FrameUtil.findJoinSourceNode(joinToTest.getLastChild()).getGroups().contains(virtualGroup)) {
-                    checkForNullDependent = true;
-                    break;
-                }
-                joinToTest = NodeEditor.findParent(joinToTest.getParent(), NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
-            }
-        }
-
-        //TODO: in each of the cases below, check to see if the offending projected symbol is actually used in the upper frame
-        List<ElementSymbol> virtualElements = symbolMap.getKeys();
-        for (int i = 0; i < selectSymbols.size(); i++) {
-        	SingleElementSymbol symbol = selectSymbols.get(i);
-            Collection scalarSubqueries = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(symbol);
-            if (!scalarSubqueries.isEmpty()) {
-                return false;
-            }
-            if (checkForNullDependent && JoinUtil.isNullDependent(metadata, groups, SymbolMap.getExpression(symbol))) {
-                return false;
-            }
-            if (parentGroupingCols != null && !(SymbolMap.getExpression(symbol) instanceof SingleElementSymbol) && parentGroupingCols.contains(virtualElements.get(i))) {
-                return false;
-            }
-            // TEIID-16: We do not want to merge a non-deterministic scalar function
-            Collection<Function> functions = FunctionCollectorVisitor.getFunctions(symbol, true, true);
-           	for (Function function : functions) {
-           		if ( function.getFunctionDescriptor().getDeterministic().isRestrictiveThanOrEqual(Determinism.NONDETERMINISTIC )) {
-           			return false;
-           		}
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * check to see if criteria is used in a full outer join or has no groups and is on the inner side of an outer join. if this
-     * is the case then the layers cannot be merged, since merging would possibly force the criteria to change it's position (into
-     * the on clause or above the join).
-     */
-    private static boolean checkJoinCriteria(PlanNode frame,
-                                             GroupSymbol virtualGroup,
-                                             PlanNode parentJoin) {
-        if (parentJoin != null) {
-            List<PlanNode> selectNodes = NodeEditor.findAllNodes(frame.getFirstChild(),
-                                                                 NodeConstants.Types.SELECT,
-                                                                 NodeConstants.Types.SOURCE);
-            Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
-            groups.add(virtualGroup);
-            for (PlanNode selectNode : selectNodes) {
-                if (selectNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
-                    continue;
-                }
-                JoinType jt = JoinUtil.getJoinTypePreventingCriteriaOptimization(parentJoin, groups);
-
-                if (jt != null && (jt == JoinType.JOIN_FULL_OUTER || selectNode.getGroups().size() == 0)) {
-                    return false;
-                }
-            }
-        }
-        return true;
-    }
-
-    public String toString() {
-        return "MergeVirtual"; //$NON-NLS-1$
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java (from rev 2762, trunk/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,394 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.relational.OptimizerRule;
+import org.teiid.query.optimizer.relational.RuleStack;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.NodeEditor;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.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.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.util.CommandContext;
+
+
+public final class RuleMergeVirtual implements
+                                   OptimizerRule {
+
+    public PlanNode execute(PlanNode plan,
+                            QueryMetadataInterface metadata,
+                            CapabilitiesFinder capFinder,
+                            RuleStack rules,
+                            AnalysisRecord analysisRecord,
+                            CommandContext context) throws QueryPlannerException,
+                                                   QueryMetadataException,
+                                                   TeiidComponentException {
+
+        for (PlanNode sourceNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.SOURCE)) {
+            if (sourceNode.getChildCount() > 0) {
+                plan = doMerge(sourceNode, plan, metadata);
+            }
+        }
+
+        return plan;
+    }
+
+    static PlanNode doMerge(PlanNode frame,
+                            PlanNode root,
+                            QueryMetadataInterface metadata) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+
+        GroupSymbol virtualGroup = frame.getGroups().iterator().next();
+
+        // check to see if frame represents a proc relational query.
+        if (virtualGroup.isProcedure()) {
+            return root;
+        }
+        
+        SymbolMap references = (SymbolMap)frame.getProperty(NodeConstants.Info.CORRELATED_REFERENCES);
+        if (references != null) {
+        	return root; //correlated nested table commands should not be merged
+        }
+
+        PlanNode parentProject = NodeEditor.findParent(frame, NodeConstants.Types.PROJECT);
+
+        // Check whether the upper frame is a SELECT INTO
+        if (parentProject.getProperty(NodeConstants.Info.INTO_GROUP) != null) {
+            return root;
+        }
+
+        if (!FrameUtil.canConvertAccessPatterns(frame)) {
+            return root;
+        }
+
+        PlanNode projectNode = frame.getFirstChild();
+
+        // Check if lower frame has only a stored procedure execution - this cannot be merged to parent frame
+        if (FrameUtil.isProcedure(projectNode)) {
+            return root;
+        }
+        
+        SymbolMap symbolMap = (SymbolMap)frame.getProperty(NodeConstants.Info.SYMBOL_MAP);
+        
+        PlanNode sortNode = NodeEditor.findParent(parentProject, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
+        
+        if (sortNode != null && sortNode.hasBooleanProperty(NodeConstants.Info.UNRELATED_SORT)) {
+        	OrderBy sortOrder = (OrderBy)sortNode.getProperty(NodeConstants.Info.SORT_ORDER);
+        	boolean unrelated = false;
+        	for (OrderByItem item : sortOrder.getOrderByItems()) {
+        		if (!item.isUnrelated()) {
+        			continue;
+        		}
+        		Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(item.getSymbol(), true);
+        		for (ElementSymbol elementSymbol : elements) {
+					if (virtualGroup.equals(elementSymbol.getGroupSymbol())) {
+						unrelated = true;
+						if (!(symbolMap.getMappedExpression(elementSymbol) instanceof ElementSymbol)) {
+							return root;
+						}
+					}
+				}
+			}
+        	// the lower frame cannot contain DUP_REMOVE, GROUP, UNION if unrelated
+        	if (unrelated && NodeEditor.findNodePreOrder(frame, NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT) != null
+        			|| NodeEditor.findNodePreOrder(frame, NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE) != null
+        			|| NodeEditor.findNodePreOrder(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE) != null) {
+        		return root;
+        	}
+        }
+
+        //try to remove the virtual layer if we are only doing a simple projection in the following cases:
+        // 1. if the frame root is something other than a project (SET_OP, SORT, LIMIT, etc.)
+        // 2. if the frame has a grouping node
+        // 3. if the frame has no sources
+        if (projectNode.getType() != NodeConstants.Types.PROJECT
+            || NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE
+                                                                                             | NodeConstants.Types.JOIN) != null
+            || NodeEditor.findAllNodes(frame.getFirstChild(), NodeConstants.Types.SOURCE, NodeConstants.Types.SOURCE).isEmpty()) {
+            return checkForSimpleProjection(frame, root, parentProject, metadata);
+        }
+
+        PlanNode parentJoin = NodeEditor.findParent(frame, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
+
+        if (!checkJoinCriteria(frame, virtualGroup, parentJoin)) {
+            return root;
+        }
+        
+        PlanNode parentGroup = NodeEditor.findParent(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE);
+        List<SingleElementSymbol> groupCols = null;
+        if (parentGroup != null) {
+        	groupCols = (List<SingleElementSymbol>)parentGroup.getProperty(NodeConstants.Info.GROUP_COLS);
+        }
+
+        if (!checkProjectedSymbols(projectNode, virtualGroup, parentJoin, groupCols, symbolMap, metadata)) {
+            return root;
+        }
+
+        // Otherwise merge should work
+
+        // Convert parent frame before merge
+        FrameUtil.convertFrame(frame, virtualGroup, FrameUtil.findJoinSourceNode(projectNode).getGroups(), symbolMap.asMap(), metadata);
+
+        PlanNode parentBottom = frame.getParent();
+        prepareFrame(frame);
+
+        // Remove top 2 nodes (SOURCE, PROJECT) of virtual group - they're no longer needed
+        NodeEditor.removeChildNode(parentBottom, frame);
+        NodeEditor.removeChildNode(parentBottom, projectNode);
+
+        return root;
+    }
+
+    private static void prepareFrame(PlanNode frame) {
+        // find the new root of the frame so that access patterns can be propagated
+        PlanNode newRoot = FrameUtil.findJoinSourceNode(frame.getFirstChild());
+        if (newRoot != null) {
+            Collection ap = (Collection)frame.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+            if (ap != null) {
+                Collection newAp = (Collection)newRoot.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+                if (newAp == null) {
+                    newRoot.setProperty(NodeConstants.Info.ACCESS_PATTERNS, ap);
+                } else {
+                    newAp.addAll(ap);
+                }
+            }
+            RulePlaceAccess.copyDependentHints(frame, newRoot);
+        }
+    }
+
+    /**
+     * Removes source layers that only do a simple projection of the elements below.
+     * @throws TeiidComponentException 
+     * @throws QueryMetadataException 
+     */
+    private static PlanNode checkForSimpleProjection(PlanNode frame,
+                                                     PlanNode root,
+                                                     PlanNode parentProject,
+                                                     QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+        // check that the parent only performs projection
+        PlanNode nodeToCheck = parentProject.getFirstChild();
+        while (nodeToCheck != frame) {
+            if (nodeToCheck.getType() != NodeConstants.Types.SELECT
+                || !nodeToCheck.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
+                return root;
+            }
+            nodeToCheck = nodeToCheck.getFirstChild();
+        }
+        
+        if (frame.getFirstChild().getType() == NodeConstants.Types.TUPLE_LIMIT
+            && NodeEditor.findParent(parentProject,
+                                     NodeConstants.Types.SORT | NodeConstants.Types.DUP_REMOVE,
+                                     NodeConstants.Types.SOURCE) != null) {
+            return root;
+        }
+        
+        List<? extends SingleElementSymbol> requiredElements = RuleAssignOutputElements.determineSourceOutput(frame, new ArrayList<SingleElementSymbol>(), metadata, null);
+        List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)parentProject.getProperty(NodeConstants.Info.PROJECT_COLS);
+
+        // check that it only performs simple projection and that all required symbols are projected
+        LinkedHashSet<ElementSymbol> symbols = new LinkedHashSet<ElementSymbol>(); //ensuring there are no duplicates prevents problems with subqueries  
+        for (SingleElementSymbol symbol : selectSymbols) {
+            Expression expr = SymbolMap.getExpression(symbol);
+            if (!(expr instanceof ElementSymbol)) {
+                return root;
+            }
+            requiredElements.remove(expr);
+            if (!symbols.add((ElementSymbol)expr)) {
+                return root;
+            }
+        }
+        if (!requiredElements.isEmpty()) {
+            return root;
+        }
+        
+        // re-order the lower projects
+        RuleAssignOutputElements.filterVirtualElements(frame, new ArrayList<SingleElementSymbol>(symbols), metadata);
+
+        // remove phantom select nodes
+        nodeToCheck = parentProject.getFirstChild();
+        while (nodeToCheck != frame) {
+            PlanNode current = nodeToCheck;
+            nodeToCheck = nodeToCheck.getFirstChild();
+            NodeEditor.removeChildNode(current.getParent(), current);
+        }
+        
+        if (NodeEditor.findParent(parentProject, NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.SOURCE) != null) {
+            PlanNode lowerDup = NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT);
+            if (lowerDup != null) {
+                NodeEditor.removeChildNode(lowerDup.getParent(), lowerDup);
+            }
+
+            PlanNode setOp = NodeEditor.findNodePreOrder(frame.getFirstChild(), NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE);
+            if (setOp != null) {
+                setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
+                if (parentProject.getParent().getParent() != null) {
+                    NodeEditor.removeChildNode(parentProject.getParent().getParent(), parentProject.getParent());
+                } else {
+                    parentProject.removeFromParent();
+                    root = parentProject;
+                }
+            }
+        }
+        
+        PlanNode sort = NodeEditor.findParent(parentProject, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
+        if (sort != null) { //special handling is needed since we are retaining the child aliases
+        	List<SingleElementSymbol> childProject = (List<SingleElementSymbol>)NodeEditor.findNodePreOrder(frame, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS);
+        	OrderBy elements = (OrderBy)sort.getProperty(NodeConstants.Info.SORT_ORDER);
+        	for (OrderByItem item : elements.getOrderByItems()) {
+				item.setSymbol(childProject.get(selectSymbols.indexOf(item.getSymbol())));
+			}
+            sort.getGroups().clear();
+            sort.addGroups(GroupsUsedByElementsVisitor.getGroups(elements));
+        }
+        
+        prepareFrame(frame);
+        
+        //remove the parent project and the source node
+        NodeEditor.removeChildNode(parentProject, frame);
+        if (parentProject.getParent() == null) {
+            root = parentProject.getFirstChild();
+            parentProject.removeChild(root);
+            return root;
+        } 
+        NodeEditor.removeChildNode(parentProject.getParent(), parentProject);
+                 
+        return root;
+    }
+    
+    /**
+     * Check to ensure that we are not projecting a subquery or null dependent expressions
+     */
+    private static boolean checkProjectedSymbols(PlanNode projectNode,
+                                                 GroupSymbol virtualGroup,
+                                                 PlanNode parentJoin,
+                                                 List<SingleElementSymbol> parentGroupingCols,
+                                                 SymbolMap symbolMap,
+                                                 QueryMetadataInterface metadata) {
+        List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)projectNode.getProperty(NodeConstants.Info.PROJECT_COLS);
+        
+        HashSet<GroupSymbol> groups = new HashSet<GroupSymbol>();
+        for (PlanNode sourceNode : NodeEditor.findAllNodes(projectNode, NodeConstants.Types.SOURCE, NodeConstants.Types.SOURCE)) {
+            groups.addAll(sourceNode.getGroups());
+        }
+
+        boolean checkForNullDependent = false;
+        // check to see if there are projected literal on the inner side of an outer join that needs to be preserved
+        if (parentJoin != null) {
+            PlanNode joinToTest = parentJoin;
+            while (joinToTest != null) {
+                JoinType joinType = (JoinType)joinToTest.getProperty(NodeConstants.Info.JOIN_TYPE);
+                if (joinType == JoinType.JOIN_FULL_OUTER) {
+                    checkForNullDependent = true;
+                    break;
+                } else if (joinType == JoinType.JOIN_LEFT_OUTER
+                           && FrameUtil.findJoinSourceNode(joinToTest.getLastChild()).getGroups().contains(virtualGroup)) {
+                    checkForNullDependent = true;
+                    break;
+                }
+                joinToTest = NodeEditor.findParent(joinToTest.getParent(), NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE);
+            }
+        }
+
+        //TODO: in each of the cases below, check to see if the offending projected symbol is actually used in the upper frame
+        List<ElementSymbol> virtualElements = symbolMap.getKeys();
+        for (int i = 0; i < selectSymbols.size(); i++) {
+        	SingleElementSymbol symbol = selectSymbols.get(i);
+            Collection scalarSubqueries = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(symbol);
+            if (!scalarSubqueries.isEmpty()) {
+                return false;
+            }
+            if (checkForNullDependent && JoinUtil.isNullDependent(metadata, groups, SymbolMap.getExpression(symbol))) {
+                return false;
+            }
+            if (parentGroupingCols != null && !(SymbolMap.getExpression(symbol) instanceof SingleElementSymbol) && parentGroupingCols.contains(virtualElements.get(i))) {
+                return false;
+            }
+            // TEIID-16: We do not want to merge a non-deterministic scalar function
+            Collection<Function> functions = FunctionCollectorVisitor.getFunctions(symbol, true, true);
+           	for (Function function : functions) {
+           		if ( function.getFunctionDescriptor().getDeterministic() == Determinism.NONDETERMINISTIC) {
+           			return false;
+           		}
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * check to see if criteria is used in a full outer join or has no groups and is on the inner side of an outer join. if this
+     * is the case then the layers cannot be merged, since merging would possibly force the criteria to change it's position (into
+     * the on clause or above the join).
+     */
+    private static boolean checkJoinCriteria(PlanNode frame,
+                                             GroupSymbol virtualGroup,
+                                             PlanNode parentJoin) {
+        if (parentJoin != null) {
+            List<PlanNode> selectNodes = NodeEditor.findAllNodes(frame.getFirstChild(),
+                                                                 NodeConstants.Types.SELECT,
+                                                                 NodeConstants.Types.SOURCE);
+            Set<GroupSymbol> groups = new HashSet<GroupSymbol>();
+            groups.add(virtualGroup);
+            for (PlanNode selectNode : selectNodes) {
+                if (selectNode.hasBooleanProperty(NodeConstants.Info.IS_PHANTOM)) {
+                    continue;
+                }
+                JoinType jt = JoinUtil.getJoinTypePreventingCriteriaOptimization(parentJoin, groups);
+
+                if (jt != null && (jt == JoinType.JOIN_FULL_OUTER || selectNode.getGroups().size() == 0)) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    public String toString() {
+        return "MergeVirtual"; //$NON-NLS-1$
+    }
+
+}

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/lang/Insert.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,302 +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.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.teiid.common.buffer.TupleSource;
-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.ProcedureReservedWords;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-
-/**
- * Represents a SQL Insert statement of the form:
- * "INSERT INTO <group> (<variables>) VALUES <values>".
- */
-public class Insert extends ProcedureContainer {
-
-    /** Identifies the group to be udpdated. */
-    private GroupSymbol group;
-
-    private List<ElementSymbol> variables = new LinkedList<ElementSymbol>();
-    private List<Expression> values = new LinkedList<Expression>();
-    
-    private QueryCommand queryExpression;
-    
-    private TupleSource tupleSource;
-
-    // =========================================================================
-    //                         C O N S T R U C T O R S
-    // =========================================================================
-
-    /**
-     * Constructs a default instance of this class.
-     */
-    public Insert() {
-    }
-
-	/**
-	 * Return type of command.
-	 * @return TYPE_INSERT
-	 */
-	public int getType() {
-		return Command.TYPE_INSERT;
-	}
-
-    /**
-     * Construct an instance with group, variable list (may be null), and values
-     * @param group Group associated with this insert
-     * @param variables List of ElementSymbols that represent columns for the values, null implies all columns
-     * @param values List of Expression values to be inserted
-     */
-    public Insert(GroupSymbol group, List variables, List values) {
-        this.group = group;
-        this.variables = variables;
-        this.values = values;
-    }
-
-    // =========================================================================
-    //                             M E T H O D S
-    // =========================================================================
-
-    /**
-     * Returns the group being inserted into
-     * @return Group being inserted into
-     */
-    public GroupSymbol getGroup() {
-        return group;
-    }
-
-    /**
-     * Set the group for this insert statement
-     * @param group Group to be inserted into
-     */
-    public void setGroup(GroupSymbol group) {
-        this.group = group;
-    }
-    
-    public boolean isBulk() {
-    	if (this.values == null) {
-    		return false;
-    	}
-    	if (!(this.values.get(0) instanceof Constant)) {
-    		return false;
-    	}
-    	return ((Constant)this.values.get(0)).isMultiValued();
-    }
-
-    /**
-     * Return an ordered List of variables, may be null if no columns were specified
-     * @return List of {@link org.teiid.query.sql.symbol.ElementSymbol}
-     */
-    public List getVariables() {
-        return variables;
-    }
-
-    /**
-     * Add a variable to end of list
-     * @param var Variable to add to the list
-     */
-    public void addVariable(ElementSymbol var) {
-        variables.add(var);
-    }
-
-    /**
-     * Add a collection of variables to end of list
-     * @param vars Variables to add to the list - collection of ElementSymbol
-     */
-    public void addVariables(Collection vars) {
-        variables.addAll(vars);
-    }
-
-    /**
-     * Returns a list of values to insert
-     * to be inserted.
-     * @return List of {@link org.teiid.query.sql.symbol.Expression}s
-     */
-    public List getValues() {
-        return this.values;
-    }
-
-    /**
-     * Sets the values to be inserted.
-     * @param values List of {@link org.teiid.query.sql.symbol.Expression}s
-     */
-    public void setValues(List values) {
-        this.values.clear();
-        this.values.addAll(values);
-    }
-    
-    /**
-     * Set a collection of variables that replace the existing variables
-     * @param vars Variables to be set on this object (ElementSymbols)
-     */
-    public void setVariables(Collection<ElementSymbol> vars) {
-        this.variables.clear();        
-        this.variables.addAll(vars);
-    }
-
-    /**
-     * Adds a value to the list of values
-     * @param value Expression to be added to the list of values
-     */
-    public void addValue(Expression value) {
-        values.add(value);
-    }
-
-    public void setQueryExpression( QueryCommand query ) {
-        this.queryExpression = query;        
-    }
-    
-    public QueryCommand getQueryExpression() {
-        return this.queryExpression;        
-    }
-
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-		
-    /**
-     * Get hashcode for command.  WARNING: This hash code relies on the hash codes of the
-     * Group, variables.  If the command changes, it's hash code will change and
-     * it can be lost from collections.  Hash code is only valid after command has been
-     * completely constructed.
-     * @return Hash code for object
-     */
-    public int hashCode() {
-    	int myHash = 0;
-    	myHash = HashCodeUtil.hashCode(myHash, this.group);
-		myHash = HashCodeUtil.hashCode(myHash, this.variables);
-		return myHash;
-	}
-
-    /**
-     * Compare two Insert commands for equality.  Will only evaluate to equal if
-     * they are IDENTICAL: group is equal, value is equal and variables are equal.
-     * @param obj Other object
-     * @return True if equal
-     */
-    public boolean equals(Object obj) {
-    	// Quick same object test
-    	if(this == obj) {
-    		return true;
-		}
-        
-		// Quick fail tests
-    	if(!(obj instanceof Insert)) {
-    		return false;
-		}
-
-		Insert other = (Insert) obj;
-        
-        return EquivalenceUtil.areEqual(getGroup(), other.getGroup()) &&
-               EquivalenceUtil.areEqual(getValues(), other.getValues()) &&
-               EquivalenceUtil.areEqual(getVariables(), other.getVariables()) &&
-               EquivalenceUtil.areEqual(getQueryExpression(), other.getQueryExpression());
-    }
-    
-    /** 
-     * @see org.teiid.query.sql.lang.ProcedureContainer#getParameters()
-     * @since 5.0
-     */
-    public LinkedHashMap<ElementSymbol, Expression> getProcedureParameters() {
-        
-        int iSize = getVariables().size();
-        LinkedHashMap<ElementSymbol, Expression> map = new LinkedHashMap<ElementSymbol, Expression>();
-        
-        for (int j = 0; j < iSize; j++) {
-            ElementSymbol symbol = (ElementSymbol)variables.get( j ).clone();
-            symbol.setName(ProcedureReservedWords.INPUTS + SingleElementSymbol.SEPARATOR + symbol.getShortCanonicalName());
-            map.put(symbol, values.get( j ) );
-        } // for 
-        return map;
-    }
-
-	/**
-	 * Return a deep copy of this Insert.
-	 * @return Deep copy of Insert
-	 */
-	public Object clone() {
-	    GroupSymbol copyGroup = null;
-	    if(group != null) { 
-	    	copyGroup = group.clone();    
-	    }
-	    
-	    List<ElementSymbol> copyVars = LanguageObject.Util.deepClone(getVariables(), ElementSymbol.class);
-
-        List copyVals = new LinkedList();
-
-        if ( getValues() != null && getValues().size() > 0 ) {
-        	Iterator iter = getValues().iterator();
-        	while(iter.hasNext()) { 
-        		Expression expression = (Expression) iter.next();
-        		copyVals.add( expression.clone() );    
-        	}    
-        }
-        
-	    Insert copy = new Insert(copyGroup, copyVars, copyVals);
-	    if (this.queryExpression != null) {
-	    	copy.setQueryExpression((QueryCommand)this.queryExpression.clone());
-	    }
-        this.copyMetadataState(copy);
-		return copy;
-	}
-	
-	/**
-	 * 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 getProjectedSymbols(){
-        return Command.getUpdateCommandSymbol();
-	}
-	
-	/**
-	 * @see org.teiid.query.sql.lang.Command#areResultsCachable()
-	 */
-	public boolean areResultsCachable() {
-		return false;
-	}
-	
-	public void setTupleSource(TupleSource tupleSource) {
-		this.tupleSource = tupleSource;
-	}
-	
-	public TupleSource getTupleSource() {
-		return tupleSource;
-	}
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java (from rev 2765, trunk/engine/src/main/java/org/teiid/query/sql/lang/Insert.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/lang/Insert.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,297 @@
+/*
+ * 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.Collection;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.teiid.common.buffer.TupleSource;
+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.ProcedureReservedWords;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+
+/**
+ * Represents a SQL Insert statement of the form:
+ * "INSERT INTO <group> (<variables>) VALUES <values>".
+ */
+public class Insert extends ProcedureContainer {
+
+    /** Identifies the group to be udpdated. */
+    private GroupSymbol group;
+
+    private List<ElementSymbol> variables = new LinkedList<ElementSymbol>();
+    private List<Expression> values = new LinkedList<Expression>();
+    
+    private QueryCommand queryExpression;
+    
+    private TupleSource tupleSource;
+
+    // =========================================================================
+    //                         C O N S T R U C T O R S
+    // =========================================================================
+
+    /**
+     * Constructs a default instance of this class.
+     */
+    public Insert() {
+    }
+
+	/**
+	 * Return type of command.
+	 * @return TYPE_INSERT
+	 */
+	public int getType() {
+		return Command.TYPE_INSERT;
+	}
+
+    /**
+     * Construct an instance with group, variable list (may be null), and values
+     * @param group Group associated with this insert
+     * @param variables List of ElementSymbols that represent columns for the values, null implies all columns
+     * @param values List of Expression values to be inserted
+     */
+    public Insert(GroupSymbol group, List<ElementSymbol> variables, List values) {
+        this.group = group;
+        this.variables = variables;
+        this.values = values;
+    }
+
+    // =========================================================================
+    //                             M E T H O D S
+    // =========================================================================
+
+    /**
+     * Returns the group being inserted into
+     * @return Group being inserted into
+     */
+    public GroupSymbol getGroup() {
+        return group;
+    }
+
+    /**
+     * Set the group for this insert statement
+     * @param group Group to be inserted into
+     */
+    public void setGroup(GroupSymbol group) {
+        this.group = group;
+    }
+    
+    public boolean isBulk() {
+    	if (this.values == null) {
+    		return false;
+    	}
+    	if (!(this.values.get(0) instanceof Constant)) {
+    		return false;
+    	}
+    	return ((Constant)this.values.get(0)).isMultiValued();
+    }
+
+    /**
+     * Return an ordered List of variables, may be null if no columns were specified
+     * @return List of {@link org.teiid.query.sql.symbol.ElementSymbol}
+     */
+    public List<ElementSymbol> getVariables() {
+        return variables;
+    }
+
+    /**
+     * Add a variable to end of list
+     * @param var Variable to add to the list
+     */
+    public void addVariable(ElementSymbol var) {
+        variables.add(var);
+    }
+
+    /**
+     * Add a collection of variables to end of list
+     * @param vars Variables to add to the list - collection of ElementSymbol
+     */
+    public void addVariables(Collection<ElementSymbol> vars) {
+        variables.addAll(vars);
+    }
+
+    /**
+     * Returns a list of values to insert
+     * to be inserted.
+     * @return List of {@link org.teiid.query.sql.symbol.Expression}s
+     */
+    public List getValues() {
+        return this.values;
+    }
+
+    /**
+     * Sets the values to be inserted.
+     * @param values List of {@link org.teiid.query.sql.symbol.Expression}s
+     */
+    public void setValues(List values) {
+        this.values.clear();
+        this.values.addAll(values);
+    }
+    
+    /**
+     * Set a collection of variables that replace the existing variables
+     * @param vars Variables to be set on this object (ElementSymbols)
+     */
+    public void setVariables(Collection<ElementSymbol> vars) {
+        this.variables.clear();        
+        this.variables.addAll(vars);
+    }
+
+    /**
+     * Adds a value to the list of values
+     * @param value Expression to be added to the list of values
+     */
+    public void addValue(Expression value) {
+        values.add(value);
+    }
+
+    public void setQueryExpression( QueryCommand query ) {
+        this.queryExpression = query;        
+    }
+    
+    public QueryCommand getQueryExpression() {
+        return this.queryExpression;        
+    }
+
+    public void acceptVisitor(LanguageVisitor visitor) {
+        visitor.visit(this);
+    }
+		
+    /**
+     * Get hashcode for command.  WARNING: This hash code relies on the hash codes of the
+     * Group, variables.  If the command changes, it's hash code will change and
+     * it can be lost from collections.  Hash code is only valid after command has been
+     * completely constructed.
+     * @return Hash code for object
+     */
+    public int hashCode() {
+    	int myHash = 0;
+    	myHash = HashCodeUtil.hashCode(myHash, this.group);
+		myHash = HashCodeUtil.hashCode(myHash, this.variables);
+		return myHash;
+	}
+
+    /**
+     * Compare two Insert commands for equality.  Will only evaluate to equal if
+     * they are IDENTICAL: group is equal, value is equal and variables are equal.
+     * @param obj Other object
+     * @return True if equal
+     */
+    public boolean equals(Object obj) {
+    	// Quick same object test
+    	if(this == obj) {
+    		return true;
+		}
+        
+		// Quick fail tests
+    	if(!(obj instanceof Insert)) {
+    		return false;
+		}
+
+		Insert other = (Insert) obj;
+        
+        return EquivalenceUtil.areEqual(getGroup(), other.getGroup()) &&
+               EquivalenceUtil.areEqual(getValues(), other.getValues()) &&
+               EquivalenceUtil.areEqual(getVariables(), other.getVariables()) &&
+               EquivalenceUtil.areEqual(getQueryExpression(), other.getQueryExpression());
+    }
+    
+    /** 
+     * @see org.teiid.query.sql.lang.ProcedureContainer#getParameters()
+     * @since 5.0
+     */
+    public LinkedHashMap<ElementSymbol, Expression> getProcedureParameters() {
+        
+        int iSize = getVariables().size();
+        LinkedHashMap<ElementSymbol, Expression> map = new LinkedHashMap<ElementSymbol, Expression>();
+        
+        for (int j = 0; j < iSize; j++) {
+            ElementSymbol symbol = (ElementSymbol)variables.get( j ).clone();
+            symbol.setName(ProcedureReservedWords.INPUTS + SingleElementSymbol.SEPARATOR + symbol.getShortCanonicalName());
+            map.put(symbol, values.get( j ) );
+        } // for 
+        return map;
+    }
+
+	/**
+	 * Return a deep copy of this Insert.
+	 * @return Deep copy of Insert
+	 */
+	public Object clone() {
+	    GroupSymbol copyGroup = null;
+	    if(group != null) { 
+	    	copyGroup = group.clone();    
+	    }
+	    
+	    List<ElementSymbol> copyVars = LanguageObject.Util.deepClone(getVariables(), ElementSymbol.class);
+
+        List<Expression> copyVals = null;
+
+        if ( getValues() != null) {
+        	copyVals = LanguageObject.Util.deepClone(getValues(), Expression.class);    
+        }
+        
+	    Insert copy = new Insert(copyGroup, copyVars, copyVals);
+	    if (this.queryExpression != null) {
+	    	copy.setQueryExpression((QueryCommand)this.queryExpression.clone());
+	    }
+        this.copyMetadataState(copy);
+		return copy;
+	}
+	
+	/**
+	 * 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(){
+        return Command.getUpdateCommandSymbol();
+	}
+	
+	/**
+	 * @see org.teiid.query.sql.lang.Command#areResultsCachable()
+	 */
+	public boolean areResultsCachable() {
+		return false;
+	}
+	
+	public void setTupleSource(TupleSource tupleSource) {
+		this.tupleSource = tupleSource;
+	}
+	
+	public TupleSource getTupleSource() {
+		return tupleSource;
+	}
+    
+}

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

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java (from rev 2774, trunk/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/CriteriaTranslatorVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,187 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.sql.visitor;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+
+import net.sf.saxon.query.QueryReader;
+
+import org.teiid.core.util.Assertion;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.AbstractSetCriteria;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.Reference;
+
+
+/**
+ * <p> This class is used to translate criteria specified on the user's update command against
+ * the virtual group, the elements on this criteria are replaced by elements on the query
+ * transformation that defines the virtual group. Parts of the criteria are selectively translated
+ * if a CriteriaSelector is specified, also if the user explicitly defines translations for some
+ * of the elements those translations override any symbol mappings.</p>
+ */
+public class CriteriaTranslatorVisitor extends ExpressionMappingVisitor {
+	
+	// criteria selector specified on the TranslateCriteria obj
+	private CriteriaSelector selector;
+
+	// translation in for of CompareCriteria objs on the TranslateCriteria obj
+	private Collection translations;
+
+	private Map<ElementSymbol, Reference> implicitParams = new HashMap<ElementSymbol, Reference>();
+
+    /**
+     * <p> This constructor initializes this object by setting the symbolMap.</p>
+     * @param symbolMap A map of virtual elements to their counterparts in transform
+     * defining the virtual group
+     */
+    public CriteriaTranslatorVisitor(Map symbolMap) {
+        super(symbolMap);
+        Assertion.isNotNull(symbolMap);
+    }
+
+	/**
+	 * <p>Set the criteria selector used to restrict the part of the criteria that needs to be
+	 * translated.</p>
+	 * @param selector The <code>CriteriaSelector</code> on the <code>TranslateCriteria</code>
+	 * object
+	 */
+    public void setCriteriaSelector(CriteriaSelector selector) {
+    	this.selector = selector;
+    }
+
+	/**
+	 * <p> Set the translations to be used to replace elements on the user's command against
+	 * the virtual group.</p>
+     * @param translations Collection of <code>ComapreCriteria</code> objects used to
+     * specify translations
+     */
+    public void setTranslations(Collection translations) {
+    	this.translations = translations;
+    }
+
+    /* ############### Helper Methods ##################   */    
+    
+    private boolean selectorContainsCriteriaElements(Criteria criteria, int criteriaType) {
+        int selectorType = selector.getSelectorType();
+        if(selectorType!= CriteriaSelector.NO_TYPE && selectorType != criteriaType) {
+            return false;
+        } else if(selector.hasElements()) {                
+            Iterator selectElmnIter = selector.getElements().iterator();
+            Collection<ElementSymbol> critElmnts = ElementCollectorVisitor.getElements(criteria, true);
+            while(selectElmnIter.hasNext()) {
+                ElementSymbol selectElmnt = (ElementSymbol) selectElmnIter.next();
+                if(critElmnts.contains(selectElmnt)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        return true;
+    }
+    
+    @Override
+    public Expression replaceExpression(Expression obj) {
+    	if (this.translations != null && obj instanceof ElementSymbol) {
+			Iterator transIter = this.translations.iterator();
+			while(transIter.hasNext()) {
+				CompareCriteria compCrit = (CompareCriteria) transIter.next();
+				Collection<ElementSymbol> leftElmnts = ElementCollectorVisitor.getElements(compCrit.getLeftExpression(), true);
+				// there is always only one element
+				ElementSymbol element = leftElmnts.iterator().next();
+				if(obj.equals(element)) {
+					return compCrit.getRightExpression();
+				}
+			}
+     	}
+    	/*
+    	 * Special handling for references in translated criteria.
+    	 * We need to create a locally valid reference name.
+    	 */
+    	if (obj instanceof Reference) {
+    		Reference implicit = (Reference)obj;
+    		ElementSymbol key = null;
+    		if (implicit.isPositional()) {
+    			key = new ElementSymbol("$INPUT." + implicit.getContextSymbol()); //$NON-NLS-1$
+    		} else {
+    			key = new ElementSymbol("$INPUT." + implicit.getExpression().getName()); //$NON-NLS-1$
+    		}
+    		key.setType(implicit.getType());
+    		this.implicitParams.put(key, implicit);
+    		return new Reference(key);
+    	}
+    	return super.replaceExpression(obj);
+    }
+
+    public Map<ElementSymbol, Reference> getImplicitParams() {
+		return implicitParams;
+	}
+    
+    public Criteria translate(Criteria crit) {
+    	LinkedList<Criteria> crits = new LinkedList<Criteria>();
+    	for (Criteria conjunct : Criteria.separateCriteriaByAnd(crit)) {
+			if (conjunct instanceof BetweenCriteria) {
+				if (!selectorContainsCriteriaElements(conjunct, CriteriaSelector.BETWEEN)) {
+					continue;
+		        }
+			} else if (conjunct instanceof CompareCriteria) {
+		        if (!selectorContainsCriteriaElements(conjunct, ((CompareCriteria)conjunct).getOperator())) {
+		        	continue; 
+		        }
+			} else if (conjunct instanceof IsNullCriteria) {
+		        if (!selectorContainsCriteriaElements(conjunct, CriteriaSelector.IS_NULL)) {
+		        	continue; 
+		        }
+			} else if (conjunct instanceof MatchCriteria) {
+		        if (!selectorContainsCriteriaElements(conjunct, CriteriaSelector.LIKE)) {
+		        	continue; 
+		        }
+			} else if (conjunct instanceof AbstractSetCriteria) {
+		        if (!selectorContainsCriteriaElements(conjunct, CriteriaSelector.IN)) {
+		        	continue;
+		        }
+			} else if (!selectorContainsCriteriaElements(conjunct, CriteriaSelector.NO_TYPE)) {
+	        	continue;
+			}
+			DeepPostOrderNavigator.doVisit(conjunct, this);
+			crits.add(conjunct);
+		}
+    	if (crits.isEmpty()) {
+    		return QueryRewriter.TRUE_CRITERIA;
+    	}
+    	return Criteria.combineCriteria(crits);
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,211 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-/**
- * 
- */
-package org.teiid.query.sql.visitor;
-
-import java.util.TreeSet;
-
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.metadata.TempMetadataID;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-
-
-/**
- * <p>This visitor class will traverse a language object tree, and determine
- * if the current expression can be evaluated</p>
- */
-public class EvaluatableVisitor extends LanguageVisitor {
-	
-	public enum EvaluationLevel {
-		PLANNING,
-		PROCESSING,
-		PUSH_DOWN,
-	}
-
-	private TreeSet<EvaluationLevel> levels = new TreeSet<EvaluationLevel>();
-	private EvaluationLevel targetLevel;
-	private Determinism determinismLevel = Determinism.DETERMINISTIC;
-	private boolean hasCorrelatedReferences;
-	    
-    public void visit(Function obj) {
-        this.setDeterminismLevel(obj.getFunctionDescriptor().getDeterministic());
-        if (obj.getFunctionDescriptor().getPushdown() == PushDown.MUST_PUSHDOWN) {
-            evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-        } else if (obj.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)
-        		//TODO: if we had the context here we could plan better for non-prepared requests
-        		|| obj.getFunctionDescriptor().getDeterministic().isRestrictiveThanOrEqual(Determinism.COMMAND_DETERMINISTIC)) {
-            evaluationNotPossible(EvaluationLevel.PROCESSING);
-        }
-    }
-    
-    @Override
-    public void visit(Constant obj) {
-    	if (obj.isMultiValued()) {
-            evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    	}
-    }
-    
-    private void setDeterminismLevel(Determinism value) {
-    	determinismLevel =  Determinism.restrictiveOf(determinismLevel, value);
-    }
-    
-    private void evaluationNotPossible(EvaluationLevel newLevel) {
-    	levels.add(newLevel);
-    	EvaluationLevel level = levels.last();
-    	if (targetLevel != null && level.compareTo(targetLevel) > 0) {
-    		setAbort(true);
-    	}
-    }
-        
-    public void visit(ElementSymbol obj) {
-    	//if the element is a variable, or an element that will have a value, it will be evaluatable at runtime
-		//begin hack for not having the metadata passed in
-		if (obj.getGroupSymbol().getMetadataID() instanceof TempMetadataID) {
-			TempMetadataID tid = (TempMetadataID)obj.getGroupSymbol().getMetadataID();
-			if (tid.isScalarGroup()) {
-				evaluationNotPossible(EvaluationLevel.PROCESSING);
-				return;
-			}
-		}
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    }
-    
-    public void visit(ExpressionSymbol obj) {
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    }
-    
-    public void visit(AggregateSymbol obj) {
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    }
-    
-    /**
-     * We assume the non-push down for correlation variables,
-     * then make specific checks when correlated variables are allowed.
-     */
-    public void visit(Reference obj) {
-        hasCorrelatedReferences |= obj.isCorrelated();
-    	evaluationNotPossible(EvaluationLevel.PROCESSING);
-    }
-    
-    public void visit(StoredProcedure proc){
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-		for (SPParameter param : proc.getInputParameters()) {
-			if (!(param.getExpression() instanceof Constant)) {
-				evaluationNotPossible(EvaluationLevel.PROCESSING);
-			}
-		}
-    }
-    
-    public void visit(ScalarSubquery obj){
-    	if (obj.shouldEvaluate()) {
-    		evaluationNotPossible(EvaluationLevel.PROCESSING);
-    	} else {
-    		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    	}
-    }
-    
-    public void visit(DependentSetCriteria obj) {
-		evaluationNotPossible(EvaluationLevel.PROCESSING);
-    }
-    
-    public void visit(ExistsCriteria obj) {
-    	if (obj.shouldEvaluate()) {
-    		evaluationNotPossible(EvaluationLevel.PROCESSING);
-    	} else {
-    		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    	}
-    }        
-
-    public void visit(SubquerySetCriteria obj) {
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    }        
-
-    public void visit(SubqueryCompareCriteria obj) {
-		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
-    }
-    
-    private boolean isEvaluationPossible() {
-    	if (levels.isEmpty()) {
-    		return true;
-    	}
-    	return levels.last().compareTo(targetLevel) <= 0;
-    }
-    
-    /**
-	 *  Will return true if the expression can be deterministically evaluated at runtime, but it may not be
-	 *  evaluatable during planning
-	 */
-	public static final boolean willBecomeConstant(LanguageObject obj) {
-	    return willBecomeConstant(obj, false);
-	}
-
-	/**
-	 *  Should be called to check if the object can fully evaluated
-	 */
-	public static final boolean isFullyEvaluatable(LanguageObject obj, boolean duringPlanning) {
-	    return isEvaluatable(obj, duringPlanning?EvaluationLevel.PLANNING:EvaluationLevel.PROCESSING);
-	}
-
-	public static final boolean isEvaluatable(LanguageObject obj, EvaluationLevel target) {
-        EvaluatableVisitor visitor = new EvaluatableVisitor();
-        visitor.targetLevel = target;
-        PreOrderNavigator.doVisit(obj, visitor);
-        return visitor.isEvaluationPossible();
-    }
-    
-    public static final boolean willBecomeConstant(LanguageObject obj, boolean pushdown) {
-        EvaluatableVisitor visitor = new EvaluatableVisitor();
-        visitor.targetLevel = EvaluationLevel.PROCESSING;
-        PreOrderNavigator.doVisit(obj, visitor);
-        if (pushdown && (visitor.hasCorrelatedReferences || visitor.determinismLevel.isRestrictiveThanOrEqual(Determinism.NONDETERMINISTIC))) {
-        	return false;
-        }
-        return visitor.isEvaluationPossible();
-    }
-    
-    public static final boolean needsProcessingEvaluation(LanguageObject obj) {
-        EvaluatableVisitor visitor = new EvaluatableVisitor();
-        DeepPreOrderNavigator.doVisit(obj, visitor);
-        return visitor.levels.contains(EvaluationLevel.PROCESSING);
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java (from rev 2762, trunk/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/sql/visitor/EvaluatableVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,213 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+/**
+ * 
+ */
+package org.teiid.query.sql.visitor;
+
+import java.util.TreeSet;
+
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
+import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+
+
+/**
+ * <p>This visitor class will traverse a language object tree, and determine
+ * if the current expression can be evaluated</p>
+ */
+public class EvaluatableVisitor extends LanguageVisitor {
+	
+	public enum EvaluationLevel {
+		PLANNING,
+		PROCESSING,
+		PUSH_DOWN,
+	}
+
+	private TreeSet<EvaluationLevel> levels = new TreeSet<EvaluationLevel>();
+	private EvaluationLevel targetLevel;
+	private Determinism determinismLevel = Determinism.DETERMINISTIC;
+	private boolean hasCorrelatedReferences;
+	    
+    public void visit(Function obj) {
+        this.setDeterminismLevel(obj.getFunctionDescriptor().getDeterministic());
+        if (obj.getFunctionDescriptor().getPushdown() == PushDown.MUST_PUSHDOWN) {
+            evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+        } else if (obj.getName().equalsIgnoreCase(FunctionLibrary.LOOKUP)
+        		//TODO: if we had the context here we could plan better for non-prepared requests
+        		|| obj.getFunctionDescriptor().getDeterministic().compareTo(Determinism.COMMAND_DETERMINISTIC) <= 0) {
+            evaluationNotPossible(EvaluationLevel.PROCESSING);
+        }
+    }
+    
+    @Override
+    public void visit(Constant obj) {
+    	if (obj.isMultiValued()) {
+            evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    	}
+    }
+    
+    private void setDeterminismLevel(Determinism value) {
+    	if (determinismLevel == null || value.compareTo(determinismLevel) < 0) {
+    		determinismLevel = value;
+    	}
+    }
+    
+    private void evaluationNotPossible(EvaluationLevel newLevel) {
+    	levels.add(newLevel);
+    	EvaluationLevel level = levels.last();
+    	if (targetLevel != null && level.compareTo(targetLevel) > 0) {
+    		setAbort(true);
+    	}
+    }
+        
+    public void visit(ElementSymbol obj) {
+    	//if the element is a variable, or an element that will have a value, it will be evaluatable at runtime
+		//begin hack for not having the metadata passed in
+		if (obj.getGroupSymbol().getMetadataID() instanceof TempMetadataID) {
+			TempMetadataID tid = (TempMetadataID)obj.getGroupSymbol().getMetadataID();
+			if (tid.isScalarGroup()) {
+				evaluationNotPossible(EvaluationLevel.PROCESSING);
+				return;
+			}
+		}
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    }
+    
+    public void visit(ExpressionSymbol obj) {
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    }
+    
+    public void visit(AggregateSymbol obj) {
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    }
+    
+    /**
+     * We assume the non-push down for correlation variables,
+     * then make specific checks when correlated variables are allowed.
+     */
+    public void visit(Reference obj) {
+        hasCorrelatedReferences |= obj.isCorrelated();
+    	evaluationNotPossible(EvaluationLevel.PROCESSING);
+    }
+    
+    public void visit(StoredProcedure proc){
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+		for (SPParameter param : proc.getInputParameters()) {
+			if (!(param.getExpression() instanceof Constant)) {
+				evaluationNotPossible(EvaluationLevel.PROCESSING);
+			}
+		}
+    }
+    
+    public void visit(ScalarSubquery obj){
+    	if (obj.shouldEvaluate()) {
+    		evaluationNotPossible(EvaluationLevel.PROCESSING);
+    	} else {
+    		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    	}
+    }
+    
+    public void visit(DependentSetCriteria obj) {
+		evaluationNotPossible(EvaluationLevel.PROCESSING);
+    }
+    
+    public void visit(ExistsCriteria obj) {
+    	if (obj.shouldEvaluate()) {
+    		evaluationNotPossible(EvaluationLevel.PROCESSING);
+    	} else {
+    		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    	}
+    }        
+
+    public void visit(SubquerySetCriteria obj) {
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    }        
+
+    public void visit(SubqueryCompareCriteria obj) {
+		evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+    }
+    
+    private boolean isEvaluationPossible() {
+    	if (levels.isEmpty()) {
+    		return true;
+    	}
+    	return levels.last().compareTo(targetLevel) <= 0;
+    }
+    
+    /**
+	 *  Will return true if the expression can be deterministically evaluated at runtime, but it may not be
+	 *  evaluatable during planning
+	 */
+	public static final boolean willBecomeConstant(LanguageObject obj) {
+	    return willBecomeConstant(obj, false);
+	}
+
+	/**
+	 *  Should be called to check if the object can fully evaluated
+	 */
+	public static final boolean isFullyEvaluatable(LanguageObject obj, boolean duringPlanning) {
+	    return isEvaluatable(obj, duringPlanning?EvaluationLevel.PLANNING:EvaluationLevel.PROCESSING);
+	}
+
+	public static final boolean isEvaluatable(LanguageObject obj, EvaluationLevel target) {
+        EvaluatableVisitor visitor = new EvaluatableVisitor();
+        visitor.targetLevel = target;
+        PreOrderNavigator.doVisit(obj, visitor);
+        return visitor.isEvaluationPossible();
+    }
+    
+    public static final boolean willBecomeConstant(LanguageObject obj, boolean pushdown) {
+        EvaluatableVisitor visitor = new EvaluatableVisitor();
+        visitor.targetLevel = EvaluationLevel.PROCESSING;
+        PreOrderNavigator.doVisit(obj, visitor);
+        if (pushdown && (visitor.hasCorrelatedReferences || visitor.determinismLevel == Determinism.NONDETERMINISTIC)) {
+        	return false;
+        }
+        return visitor.isEvaluationPossible();
+    }
+    
+    public static final boolean needsProcessingEvaluation(LanguageObject obj) {
+        EvaluatableVisitor visitor = new EvaluatableVisitor();
+        DeepPreOrderNavigator.doVisit(obj, visitor);
+        return visitor.levels.contains(EvaluationLevel.PROCESSING);
+    }
+}

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,513 +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.util;
-
-import java.io.Serializable;
-import java.util.LinkedList;
-import java.util.Properties;
-import java.util.Random;
-import java.util.Set;
-import java.util.TimeZone;
-
-import org.teiid.api.exception.query.QueryProcessingException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.dqp.internal.process.PreparedPlan;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.SecurityFunctionEvaluator;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.relational.PlanToProcessConverter;
-import org.teiid.query.parser.ParseInfo;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.util.VariableContext;
-import org.teiid.query.tempdata.TempTableStore;
-
-/** 
- * Defines the context that a command is processing in.  For example, this defines
- * who is processing the command and why.  Also, this class (or subclasses) provide
- * a means to pass context-specific information between users of the query processor
- * framework.
- */
-public class CommandContext implements Cloneable, org.teiid.CommandContext {
-	
-	private static class GlobalState {
-	    /** Uniquely identify the command being processed */
-	    private Object processorID;
-	    
-	    /** Identify a group of related commands, which typically get cleaned up together */
-	    private String connectionID;
-
-	    private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
-	    
-	    private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
-
-	    private String userName;
-	    
-	    private Serializable commandPayload;
-	    
-	    private String vdbName = ""; //$NON-NLS-1$
-	    
-	    private int vdbVersion;
-	    
-	    private Properties environmentProperties;
-	    
-	    /** Indicate whether statistics should be collected for relational node processing*/
-	    private boolean collectNodeStatistics;
-	    
-	    private Random random = null;
-	    
-	    private SecurityFunctionEvaluator securityFunctionEvaluator;
-	    
-	    private TimeZone timezone = TimeZone.getDefault();
-	    
-	    private PlanToProcessConverter planToProcessConverter;
-	    
-	    private QueryProcessor.ProcessorFactory queryProcessorFactory;
-	        
-	    private Determinism determinismLevel = Determinism.DETERMINISTIC;
-	    
-	    private Set<String> groups;
-	    
-	    private long timeSliceEnd = Long.MAX_VALUE;
-	    
-	    private long timeoutEnd = Long.MAX_VALUE;
-	    
-	    private QueryMetadataInterface metadata; 
-	    
-	    private boolean validateXML;
-	    
-	    private BufferManager bufferManager;
-	    
-	    private TempTableStore globalTables;
-	    
-	    private SessionAwareCache<PreparedPlan> planCache;
-	    
-	    private boolean resultSetCacheEnabled = true;
-	    
-	}
-	
-	private GlobalState globalState = new GlobalState();
-
-    private VariableContext variableContext = new VariableContext();
-    private TempTableStore tempTableStore;
-    private LinkedList<String> recursionStack;
-    private boolean nonBlocking;
-
-    /**
-     * Construct a new context.
-     */
-    public CommandContext(Object processorID, String connectionID, String userName, 
-        Serializable commandPayload, String vdbName, int vdbVersion, Properties envProperties, boolean collectNodeStatistics) {
-        setProcessorID(processorID);
-        setConnectionID(connectionID);
-        setUserName(userName);
-        setCommandPayload(commandPayload);
-        setVdbName(vdbName);
-        setVdbVersion(vdbVersion);  
-        setEnvironmentProperties(envProperties);        
-        setCollectNodeStatistics(collectNodeStatistics);
-    }
-
-    /**
-     * Construct a new context.
-     */
-    public CommandContext(Object processorID, String connectionID, String userName, 
-        String vdbName, int vdbVersion) {
-
-        this(processorID, connectionID, userName, null, vdbName, 
-            vdbVersion, null, false);            
-             
-    }
-
-    public CommandContext() {
-    }
-    
-    private CommandContext(GlobalState state) {
-    	this.globalState = state;
-    }
-    
-    public Determinism getDeterminismLevel() {
-		return globalState.determinismLevel;
-	}
-    
-    public Determinism resetDeterminismLevel() {
-    	Determinism result = globalState.determinismLevel;
-    	globalState.determinismLevel = Determinism.DETERMINISTIC;
-    	return result;
-    }
-    
-    public void setDeterminismLevel(Determinism level) {
-    	globalState.determinismLevel = Determinism.restrictiveOf(globalState.determinismLevel, level);
-    }
-    
-    /**
-     * @return
-     */
-    public Object getProcessorID() {
-        return globalState.processorID;
-    }
-
-    /**
-     * @param object
-     */
-    public void setProcessorID(Object object) {
-        ArgCheck.isNotNull(object);
-        globalState.processorID = object;
-    }
-
-    public CommandContext clone() {
-    	CommandContext clone = new CommandContext(this.globalState);
-    	clone.variableContext = this.variableContext;
-    	clone.tempTableStore = this.tempTableStore;
-    	if (this.recursionStack != null) {
-            clone.recursionStack = new LinkedList<String>(this.recursionStack);
-        }
-    	clone.setNonBlocking(this.nonBlocking);
-    	return clone;
-    }
-    
-    public String toString() {
-        return "CommandContext: " + globalState.processorID; //$NON-NLS-1$
-    }
-
-    /**
-     * @return String
-     */
-    public String getConnectionID() {
-        return globalState.connectionID;
-    }
-
-    /**
-     * @return String
-     */
-    public String getUserName() {
-        return globalState.userName;
-    }
-
-    /**
-     * @return String
-     */
-    public String getVdbName() {
-        return globalState.vdbName;
-    }
-
-    /**
-     * @return String
-     */
-    public int getVdbVersion() {
-        return globalState.vdbVersion;
-    }
-
-    /**
-     * Sets the connectionID.
-     * @param connectionID The connectionID to set
-     */
-    public void setConnectionID(String connectionID) {
-        this.globalState.connectionID = connectionID;
-    }
-
-    /**
-     * Sets the userName.
-     * @param userName The userName to set
-     */
-    public void setUserName(String userName) {
-        this.globalState.userName = userName;
-    }
-
-    /**
-     * Sets the vdbName.
-     * @param vdbName The vdbName to set
-     */
-    public void setVdbName(String vdbName) {
-        this.globalState.vdbName = vdbName;
-    }
-
-    /**
-     * Sets the vdbVersion.
-     * @param vdbVersion The vdbVersion to set
-     */
-    public void setVdbVersion(int vdbVersion) {
-        this.globalState.vdbVersion = vdbVersion;
-    }
-
-    public Properties getEnvironmentProperties() {
-        return globalState.environmentProperties;
-    }
-
-    public void setEnvironmentProperties(Properties properties) {
-    	globalState.environmentProperties = properties;
-    }
-    
-    public Serializable getCommandPayload() {
-        return this.globalState.commandPayload;
-    }
-    public void setCommandPayload(Serializable commandPayload) {
-        this.globalState.commandPayload = commandPayload;
-    }    
-    
-    /** 
-     * @param collectNodeStatistics The collectNodeStatistics to set.
-     * @since 4.2
-     */
-    public void setCollectNodeStatistics(boolean collectNodeStatistics) {
-        this.globalState.collectNodeStatistics = collectNodeStatistics;
-    }
-    
-    public boolean getCollectNodeStatistics() {
-        return this.globalState.collectNodeStatistics;
-    }
-    
-    public int getConnectorBatchSize() {
-        return this.globalState.connectorBatchSize;
-    }
-    
-    public void setConnectorBatchSize(int connectorBatchSize) {
-        this.globalState.connectorBatchSize = connectorBatchSize;
-    }
-
-    
-    public int getProcessorBatchSize() {
-        return this.globalState.processorBatchSize;
-    }
-
-    
-    public void setProcessorBatchSize(int processorBatchSize) {
-        this.globalState.processorBatchSize = processorBatchSize;
-    }
-    
-    public double getNextRand() {
-        if (globalState.random == null) {
-        	globalState.random = new Random();
-        }
-        return globalState.random.nextDouble();
-    }
-    
-    public double getNextRand(long seed) {
-        if (globalState.random == null) {
-        	globalState.random = new Random();
-        }
-        globalState.random.setSeed(seed);
-        return globalState.random.nextDouble();
-    }
-    
-    void setRandom(Random random) {
-        this.globalState.random = random;
-    }
-
-    public void pushCall(String value) throws QueryProcessingException {
-        if (recursionStack == null) {
-            recursionStack = new LinkedList<String>();
-        } else if (recursionStack.contains(value)) {
-			throw new QueryProcessingException(QueryPlugin.Util.getString("ExecDynamicSqlInstruction.3", value)); //$NON-NLS-1$
-        }
-        
-        recursionStack.push(value);
-    }
-    
-    public int getCallStackDepth() {
-    	if (this.recursionStack == null) {
-    		return 0;
-    	}
-    	return this.recursionStack.size();
-    }
-    
-    public void popCall() {
-        if (recursionStack != null) {
-            recursionStack.pop();
-        }
-    }
-
-    /** 
-     * @return Returns the securityFunctionEvaluator.
-     */
-    public SecurityFunctionEvaluator getSecurityFunctionEvaluator() {
-        return this.globalState.securityFunctionEvaluator;
-    }
-    
-    /** 
-     * @param securityFunctionEvaluator The securityFunctionEvaluator to set.
-     */
-    public void setSecurityFunctionEvaluator(SecurityFunctionEvaluator securityFunctionEvaluator) {
-        this.globalState.securityFunctionEvaluator = securityFunctionEvaluator;
-    }
-
-	public TempTableStore getTempTableStore() {
-		return tempTableStore;
-	}
-
-	public void setTempTableStore(TempTableStore tempTableStore) {
-		this.tempTableStore = tempTableStore;
-	}
-	
-	public TimeZone getServerTimeZone() {
-		return globalState.timezone;
-	}
-
-	public void setPlanToProcessConverter(PlanToProcessConverter planToProcessConverter) {
-		this.globalState.planToProcessConverter = planToProcessConverter;
-	}
-
-	public PlanToProcessConverter getPlanToProcessConverter() {
-		return globalState.planToProcessConverter;
-	}
-	
-	public QueryProcessor.ProcessorFactory getQueryProcessorFactory() {
-		return this.globalState.queryProcessorFactory;
-	}
-
-	public void setQueryProcessorFactory(QueryProcessor.ProcessorFactory queryProcessorFactory) {
-		this.globalState.queryProcessorFactory = queryProcessorFactory;
-	}
-	
-	public VariableContext getVariableContext() {
-		return variableContext;
-	}
-	
-	public void setVariableContext(VariableContext variableContext) {
-		this.variableContext = variableContext;
-	}
-	
-	public void pushVariableContext(VariableContext toPush) {
-		toPush.setParentContext(this.variableContext);
-		this.variableContext = toPush;
-	}
-	
-	public Object getFromContext(Expression expression) throws TeiidComponentException {
-		if (variableContext == null || !(expression instanceof ElementSymbol)) {
-			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-		Object value = variableContext.getValue((ElementSymbol)expression);
-		if (value == null && !variableContext.containsVariable((ElementSymbol)expression)) {
-			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		}
-		return value;
-	}
-	
-	public Set<String> getGroups() {
-		return globalState.groups;
-	}
-	
-	public void setGroups(Set<String> groups) {
-		this.globalState.groups = groups;
-	}
-	
-	public long getTimeSliceEnd() {
-		return globalState.timeSliceEnd;
-	}
-	
-	public long getTimeoutEnd() {
-		return globalState.timeoutEnd;
-	}
-	
-	public void setTimeSliceEnd(long timeSliceEnd) {
-		globalState.timeSliceEnd = timeSliceEnd;
-	}
-	
-	public void setTimeoutEnd(long timeoutEnd) {
-		globalState.timeoutEnd = timeoutEnd;
-	}
-
-	public void setMetadata(QueryMetadataInterface metadata) {
-		globalState.metadata = metadata;
-	}
-	
-	public QueryMetadataInterface getMetadata() {
-		return globalState.metadata;
-	}
-    
-    public void setValidateXML(boolean validateXML) {
-    	globalState.validateXML = validateXML;
-	}
-    
-    public boolean validateXML() {
-		return globalState.validateXML;
-	}
-    
-    public BufferManager getBufferManager() {
-    	return globalState.bufferManager;
-    }
-    
-    public void setBufferManager(BufferManager bm) {
-    	globalState.bufferManager = bm;
-    }
-    
-    public TempTableStore getGlobalTableStore() {
-    	return globalState.globalTables;
-    }
-    
-    public void setGlobalTableStore(TempTableStore tempTableStore) {
-    	globalState.globalTables = tempTableStore;
-    }
-    
-    public boolean isNonBlocking() {
-		return nonBlocking;
-	}
-    
-    public void setNonBlocking(boolean nonBlocking) {
-		this.nonBlocking = nonBlocking;
-	}
-    
-    public void setPreparedPlanCache(SessionAwareCache<PreparedPlan> cache) {
-    	this.globalState.planCache = cache;
-    }
-    
-    public PreparedPlan getPlan(String key) {
-    	if (this.globalState.planCache == null) {
-    		return null;
-    	}
-    	CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
-    	PreparedPlan pp = this.globalState.planCache.get(id);
-    	if (pp != null) {
-    		if (id.getSessionId() != null) {
-    			setDeterminismLevel(Determinism.USER_DETERMINISTIC);
-    		} else if (id.getUserName() != null) {
-    			setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
-    		}
-        	return pp;
-    	}
-    	return null;
-    }
-    
-    public void putPlan(String key, PreparedPlan plan, Determinism determinismLevel) {
-    	if (this.globalState.planCache == null) {
-    		return;
-    	}
-    	CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
-    	this.globalState.planCache.put(id, determinismLevel, plan, null);
-    }
-    
-    public boolean isResultSetCacheEnabled() {
-		return globalState.resultSetCacheEnabled;
-	}
-    
-    public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
-		this.globalState.resultSetCacheEnabled = resultSetCacheEnabled;
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java (from rev 2762, trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/util/CommandContext.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,515 @@
+/*
+ * 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.util;
+
+import java.io.Serializable;
+import java.util.LinkedList;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.TimeZone;
+
+import org.teiid.api.exception.query.QueryProcessingException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.util.ArgCheck;
+import org.teiid.dqp.internal.process.PreparedPlan;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.SecurityFunctionEvaluator;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.relational.PlanToProcessConverter;
+import org.teiid.query.parser.ParseInfo;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.util.VariableContext;
+import org.teiid.query.tempdata.TempTableStore;
+
+/** 
+ * Defines the context that a command is processing in.  For example, this defines
+ * who is processing the command and why.  Also, this class (or subclasses) provide
+ * a means to pass context-specific information between users of the query processor
+ * framework.
+ */
+public class CommandContext implements Cloneable, org.teiid.CommandContext {
+	
+	private static class GlobalState {
+	    /** Uniquely identify the command being processed */
+	    private Object processorID;
+	    
+	    /** Identify a group of related commands, which typically get cleaned up together */
+	    private String connectionID;
+
+	    private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
+	    
+	    private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
+
+	    private String userName;
+	    
+	    private Serializable commandPayload;
+	    
+	    private String vdbName = ""; //$NON-NLS-1$
+	    
+	    private int vdbVersion;
+	    
+	    private Properties environmentProperties;
+	    
+	    /** Indicate whether statistics should be collected for relational node processing*/
+	    private boolean collectNodeStatistics;
+	    
+	    private Random random = null;
+	    
+	    private SecurityFunctionEvaluator securityFunctionEvaluator;
+	    
+	    private TimeZone timezone = TimeZone.getDefault();
+	    
+	    private PlanToProcessConverter planToProcessConverter;
+	    
+	    private QueryProcessor.ProcessorFactory queryProcessorFactory;
+	        
+	    private Determinism determinismLevel = Determinism.DETERMINISTIC;
+	    
+	    private Set<String> groups;
+	    
+	    private long timeSliceEnd = Long.MAX_VALUE;
+	    
+	    private long timeoutEnd = Long.MAX_VALUE;
+	    
+	    private QueryMetadataInterface metadata; 
+	    
+	    private boolean validateXML;
+	    
+	    private BufferManager bufferManager;
+	    
+	    private TempTableStore globalTables;
+	    
+	    private SessionAwareCache<PreparedPlan> planCache;
+	    
+	    private boolean resultSetCacheEnabled = true;
+	    
+	}
+	
+	private GlobalState globalState = new GlobalState();
+
+    private VariableContext variableContext = new VariableContext();
+    private TempTableStore tempTableStore;
+    private LinkedList<String> recursionStack;
+    private boolean nonBlocking;
+
+    /**
+     * Construct a new context.
+     */
+    public CommandContext(Object processorID, String connectionID, String userName, 
+        Serializable commandPayload, String vdbName, int vdbVersion, Properties envProperties, boolean collectNodeStatistics) {
+        setProcessorID(processorID);
+        setConnectionID(connectionID);
+        setUserName(userName);
+        setCommandPayload(commandPayload);
+        setVdbName(vdbName);
+        setVdbVersion(vdbVersion);  
+        setEnvironmentProperties(envProperties);        
+        setCollectNodeStatistics(collectNodeStatistics);
+    }
+
+    /**
+     * Construct a new context.
+     */
+    public CommandContext(Object processorID, String connectionID, String userName, 
+        String vdbName, int vdbVersion) {
+
+        this(processorID, connectionID, userName, null, vdbName, 
+            vdbVersion, null, false);            
+             
+    }
+
+    public CommandContext() {
+    }
+    
+    private CommandContext(GlobalState state) {
+    	this.globalState = state;
+    }
+    
+    public Determinism getDeterminismLevel() {
+		return globalState.determinismLevel;
+	}
+    
+    public Determinism resetDeterminismLevel() {
+    	Determinism result = globalState.determinismLevel;
+    	globalState.determinismLevel = Determinism.DETERMINISTIC;
+    	return result;
+    }
+    
+    public void setDeterminismLevel(Determinism level) {
+    	if (globalState.determinismLevel == null || level.compareTo(globalState.determinismLevel) < 0) {
+    		globalState.determinismLevel = level;
+    	}
+    }
+    
+    /**
+     * @return
+     */
+    public Object getProcessorID() {
+        return globalState.processorID;
+    }
+
+    /**
+     * @param object
+     */
+    public void setProcessorID(Object object) {
+        ArgCheck.isNotNull(object);
+        globalState.processorID = object;
+    }
+
+    public CommandContext clone() {
+    	CommandContext clone = new CommandContext(this.globalState);
+    	clone.variableContext = this.variableContext;
+    	clone.tempTableStore = this.tempTableStore;
+    	if (this.recursionStack != null) {
+            clone.recursionStack = new LinkedList<String>(this.recursionStack);
+        }
+    	clone.setNonBlocking(this.nonBlocking);
+    	return clone;
+    }
+    
+    public String toString() {
+        return "CommandContext: " + globalState.processorID; //$NON-NLS-1$
+    }
+
+    /**
+     * @return String
+     */
+    public String getConnectionID() {
+        return globalState.connectionID;
+    }
+
+    /**
+     * @return String
+     */
+    public String getUserName() {
+        return globalState.userName;
+    }
+
+    /**
+     * @return String
+     */
+    public String getVdbName() {
+        return globalState.vdbName;
+    }
+
+    /**
+     * @return String
+     */
+    public int getVdbVersion() {
+        return globalState.vdbVersion;
+    }
+
+    /**
+     * Sets the connectionID.
+     * @param connectionID The connectionID to set
+     */
+    public void setConnectionID(String connectionID) {
+        this.globalState.connectionID = connectionID;
+    }
+
+    /**
+     * Sets the userName.
+     * @param userName The userName to set
+     */
+    public void setUserName(String userName) {
+        this.globalState.userName = userName;
+    }
+
+    /**
+     * Sets the vdbName.
+     * @param vdbName The vdbName to set
+     */
+    public void setVdbName(String vdbName) {
+        this.globalState.vdbName = vdbName;
+    }
+
+    /**
+     * Sets the vdbVersion.
+     * @param vdbVersion The vdbVersion to set
+     */
+    public void setVdbVersion(int vdbVersion) {
+        this.globalState.vdbVersion = vdbVersion;
+    }
+
+    public Properties getEnvironmentProperties() {
+        return globalState.environmentProperties;
+    }
+
+    public void setEnvironmentProperties(Properties properties) {
+    	globalState.environmentProperties = properties;
+    }
+    
+    public Serializable getCommandPayload() {
+        return this.globalState.commandPayload;
+    }
+    public void setCommandPayload(Serializable commandPayload) {
+        this.globalState.commandPayload = commandPayload;
+    }    
+    
+    /** 
+     * @param collectNodeStatistics The collectNodeStatistics to set.
+     * @since 4.2
+     */
+    public void setCollectNodeStatistics(boolean collectNodeStatistics) {
+        this.globalState.collectNodeStatistics = collectNodeStatistics;
+    }
+    
+    public boolean getCollectNodeStatistics() {
+        return this.globalState.collectNodeStatistics;
+    }
+    
+    public int getConnectorBatchSize() {
+        return this.globalState.connectorBatchSize;
+    }
+    
+    public void setConnectorBatchSize(int connectorBatchSize) {
+        this.globalState.connectorBatchSize = connectorBatchSize;
+    }
+
+    
+    public int getProcessorBatchSize() {
+        return this.globalState.processorBatchSize;
+    }
+
+    
+    public void setProcessorBatchSize(int processorBatchSize) {
+        this.globalState.processorBatchSize = processorBatchSize;
+    }
+    
+    public double getNextRand() {
+        if (globalState.random == null) {
+        	globalState.random = new Random();
+        }
+        return globalState.random.nextDouble();
+    }
+    
+    public double getNextRand(long seed) {
+        if (globalState.random == null) {
+        	globalState.random = new Random();
+        }
+        globalState.random.setSeed(seed);
+        return globalState.random.nextDouble();
+    }
+    
+    void setRandom(Random random) {
+        this.globalState.random = random;
+    }
+
+    public void pushCall(String value) throws QueryProcessingException {
+        if (recursionStack == null) {
+            recursionStack = new LinkedList<String>();
+        } else if (recursionStack.contains(value)) {
+			throw new QueryProcessingException(QueryPlugin.Util.getString("ExecDynamicSqlInstruction.3", value)); //$NON-NLS-1$
+        }
+        
+        recursionStack.push(value);
+    }
+    
+    public int getCallStackDepth() {
+    	if (this.recursionStack == null) {
+    		return 0;
+    	}
+    	return this.recursionStack.size();
+    }
+    
+    public void popCall() {
+        if (recursionStack != null) {
+            recursionStack.pop();
+        }
+    }
+
+    /** 
+     * @return Returns the securityFunctionEvaluator.
+     */
+    public SecurityFunctionEvaluator getSecurityFunctionEvaluator() {
+        return this.globalState.securityFunctionEvaluator;
+    }
+    
+    /** 
+     * @param securityFunctionEvaluator The securityFunctionEvaluator to set.
+     */
+    public void setSecurityFunctionEvaluator(SecurityFunctionEvaluator securityFunctionEvaluator) {
+        this.globalState.securityFunctionEvaluator = securityFunctionEvaluator;
+    }
+
+	public TempTableStore getTempTableStore() {
+		return tempTableStore;
+	}
+
+	public void setTempTableStore(TempTableStore tempTableStore) {
+		this.tempTableStore = tempTableStore;
+	}
+	
+	public TimeZone getServerTimeZone() {
+		return globalState.timezone;
+	}
+
+	public void setPlanToProcessConverter(PlanToProcessConverter planToProcessConverter) {
+		this.globalState.planToProcessConverter = planToProcessConverter;
+	}
+
+	public PlanToProcessConverter getPlanToProcessConverter() {
+		return globalState.planToProcessConverter;
+	}
+	
+	public QueryProcessor.ProcessorFactory getQueryProcessorFactory() {
+		return this.globalState.queryProcessorFactory;
+	}
+
+	public void setQueryProcessorFactory(QueryProcessor.ProcessorFactory queryProcessorFactory) {
+		this.globalState.queryProcessorFactory = queryProcessorFactory;
+	}
+	
+	public VariableContext getVariableContext() {
+		return variableContext;
+	}
+	
+	public void setVariableContext(VariableContext variableContext) {
+		this.variableContext = variableContext;
+	}
+	
+	public void pushVariableContext(VariableContext toPush) {
+		toPush.setParentContext(this.variableContext);
+		this.variableContext = toPush;
+	}
+	
+	public Object getFromContext(Expression expression) throws TeiidComponentException {
+		if (variableContext == null || !(expression instanceof ElementSymbol)) {
+			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+		Object value = variableContext.getValue((ElementSymbol)expression);
+		if (value == null && !variableContext.containsVariable((ElementSymbol)expression)) {
+			throw new TeiidComponentException("ERR.015.006.0033", QueryPlugin.Util.getString("ERR.015.006.0033", expression, "No value was available")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		}
+		return value;
+	}
+	
+	public Set<String> getGroups() {
+		return globalState.groups;
+	}
+	
+	public void setGroups(Set<String> groups) {
+		this.globalState.groups = groups;
+	}
+	
+	public long getTimeSliceEnd() {
+		return globalState.timeSliceEnd;
+	}
+	
+	public long getTimeoutEnd() {
+		return globalState.timeoutEnd;
+	}
+	
+	public void setTimeSliceEnd(long timeSliceEnd) {
+		globalState.timeSliceEnd = timeSliceEnd;
+	}
+	
+	public void setTimeoutEnd(long timeoutEnd) {
+		globalState.timeoutEnd = timeoutEnd;
+	}
+
+	public void setMetadata(QueryMetadataInterface metadata) {
+		globalState.metadata = metadata;
+	}
+	
+	public QueryMetadataInterface getMetadata() {
+		return globalState.metadata;
+	}
+    
+    public void setValidateXML(boolean validateXML) {
+    	globalState.validateXML = validateXML;
+	}
+    
+    public boolean validateXML() {
+		return globalState.validateXML;
+	}
+    
+    public BufferManager getBufferManager() {
+    	return globalState.bufferManager;
+    }
+    
+    public void setBufferManager(BufferManager bm) {
+    	globalState.bufferManager = bm;
+    }
+    
+    public TempTableStore getGlobalTableStore() {
+    	return globalState.globalTables;
+    }
+    
+    public void setGlobalTableStore(TempTableStore tempTableStore) {
+    	globalState.globalTables = tempTableStore;
+    }
+    
+    public boolean isNonBlocking() {
+		return nonBlocking;
+	}
+    
+    public void setNonBlocking(boolean nonBlocking) {
+		this.nonBlocking = nonBlocking;
+	}
+    
+    public void setPreparedPlanCache(SessionAwareCache<PreparedPlan> cache) {
+    	this.globalState.planCache = cache;
+    }
+    
+    public PreparedPlan getPlan(String key) {
+    	if (this.globalState.planCache == null) {
+    		return null;
+    	}
+    	CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
+    	PreparedPlan pp = this.globalState.planCache.get(id);
+    	if (pp != null) {
+    		if (id.getSessionId() != null) {
+    			setDeterminismLevel(Determinism.USER_DETERMINISTIC);
+    		} else if (id.getUserName() != null) {
+    			setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
+    		}
+        	return pp;
+    	}
+    	return null;
+    }
+    
+    public void putPlan(String key, PreparedPlan plan, Determinism determinismLevel) {
+    	if (this.globalState.planCache == null) {
+    		return;
+    	}
+    	CacheID id = new CacheID(new ParseInfo(), key, getVdbName(), getVdbVersion(), getConnectionID(), getUserName());
+    	this.globalState.planCache.put(id, determinismLevel, plan, null);
+    }
+    
+    public boolean isResultSetCacheEnabled() {
+		return globalState.resultSetCacheEnabled;
+	}
+    
+    public void setResultSetCacheEnabled(boolean resultSetCacheEnabled) {
+		this.globalState.resultSetCacheEnabled = resultSetCacheEnabled;
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1483 +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.validator;
-
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import net.sf.saxon.om.Name11Checker;
-import net.sf.saxon.om.QNameException;
-import net.sf.saxon.trans.XPathException;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionMethods;
-import org.teiid.query.function.source.XMLSystemFunctions;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.ProcedureReservedWords;
-import org.teiid.query.sql.lang.BatchedUpdateCommand;
-import org.teiid.query.sql.lang.BetweenCriteria;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.lang.CompoundCriteria;
-import org.teiid.query.sql.lang.Create;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.Delete;
-import org.teiid.query.sql.lang.DependentSetCriteria;
-import org.teiid.query.sql.lang.Drop;
-import org.teiid.query.sql.lang.DynamicCommand;
-import org.teiid.query.sql.lang.ExistsCriteria;
-import org.teiid.query.sql.lang.GroupBy;
-import org.teiid.query.sql.lang.Insert;
-import org.teiid.query.sql.lang.Into;
-import org.teiid.query.sql.lang.IsNullCriteria;
-import org.teiid.query.sql.lang.Limit;
-import org.teiid.query.sql.lang.MatchCriteria;
-import org.teiid.query.sql.lang.NotCriteria;
-import org.teiid.query.sql.lang.Option;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.lang.OrderByItem;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.Query;
-import org.teiid.query.sql.lang.QueryCommand;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.lang.SetClause;
-import org.teiid.query.sql.lang.SetClauseList;
-import org.teiid.query.sql.lang.SetCriteria;
-import org.teiid.query.sql.lang.SetQuery;
-import org.teiid.query.sql.lang.StoredProcedure;
-import org.teiid.query.sql.lang.SubqueryCompareCriteria;
-import org.teiid.query.sql.lang.SubqueryContainer;
-import org.teiid.query.sql.lang.SubqueryFromClause;
-import org.teiid.query.sql.lang.SubquerySetCriteria;
-import org.teiid.query.sql.lang.TextTable;
-import org.teiid.query.sql.lang.Update;
-import org.teiid.query.sql.lang.WithQueryCommand;
-import org.teiid.query.sql.lang.XMLTable;
-import org.teiid.query.sql.lang.SetQuery.Operation;
-import org.teiid.query.sql.lang.XMLTable.XMLColumn;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.proc.AssignmentStatement;
-import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
-import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.proc.DeclareStatement;
-import org.teiid.query.sql.proc.HasCriteria;
-import org.teiid.query.sql.proc.IfStatement;
-import org.teiid.query.sql.proc.LoopStatement;
-import org.teiid.query.sql.proc.TranslateCriteria;
-import org.teiid.query.sql.proc.WhileStatement;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.DerivedColumn;
-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.QueryString;
-import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.ScalarSubquery;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.symbol.TextLine;
-import org.teiid.query.sql.symbol.XMLAttributes;
-import org.teiid.query.sql.symbol.XMLElement;
-import org.teiid.query.sql.symbol.XMLForest;
-import org.teiid.query.sql.symbol.XMLNamespaces;
-import org.teiid.query.sql.symbol.XMLParse;
-import org.teiid.query.sql.symbol.XMLQuery;
-import org.teiid.query.sql.symbol.AggregateSymbol.Type;
-import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
-import org.teiid.query.sql.visitor.CommandCollectorVisitor;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.PredicateCollectorVisitor;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.validator.UpdateValidator.UpdateInfo;
-import org.teiid.query.validator.UpdateValidator.UpdateType;
-import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
-import org.teiid.translator.SourceSystemFunctions;
-
-public class ValidationVisitor extends AbstractValidationVisitor {
-
-    private final class PositiveIntegerConstraint implements
-			Reference.Constraint {
-    	
-    	private String msgKey;
-    	
-    	public PositiveIntegerConstraint(String msgKey) {
-    		this.msgKey = msgKey;
-		}
-    	
-		@Override
-		public void validate(Object value) throws QueryValidatorException {
-			if (((Integer)value).intValue() < 0) {
-				throw new QueryValidatorException(QueryPlugin.Util.getString(msgKey)); 
-			}
-		}
-	}
-
-	// State during validation
-    private boolean isXML = false;	// only used for Query commands
-    
-    // update procedure being validated
-    private CreateUpdateProcedureCommand updateProc;
-    
-    public void setUpdateProc(CreateUpdateProcedureCommand updateProc) {
-		this.updateProc = updateProc;
-	}
-    
-    public void reset() {
-        super.reset();
-        this.isXML = false;
-    }
-
-    // ############### Visitor methods for language objects ##################
-    
-    public void visit(BatchedUpdateCommand obj) {
-        List commands = obj.getUpdateCommands();
-        Command command = null;
-        int type = 0;
-        for (int i = 0; i < commands.size(); i++) {
-            command = (Command)commands.get(i);
-            type = command.getType();
-            if (type != Command.TYPE_INSERT &&
-                type != Command.TYPE_UPDATE &&
-                type != Command.TYPE_DELETE &&
-                type != Command.TYPE_QUERY) { // SELECT INTO command
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_batch_command"),command); //$NON-NLS-1$
-            } else if (type == Command.TYPE_QUERY) {
-                Into into = ((Query)command).getInto();
-                if (into == null) {
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_batch_command"),command); //$NON-NLS-1$
-                }
-            }
-        }
-    }
-
-	public void visit(Delete obj) {
-    	validateNoXMLUpdates(obj);
-        GroupSymbol group = obj.getGroup();
-        validateGroupSupportsUpdate(group);
-        Criteria crit = obj.getCriteria();
-    	validateVirtualUpdate(obj, crit);
-    }
-
-	private void validateVirtualUpdate(ProcedureContainer container, 
-			Criteria crit) {
-		if (crit == null || container.getUpdateInfo() == null) {
-			return; 
-		}
-		if ((container.getType() == Command.TYPE_UPDATE && container.getUpdateInfo().getUpdateType() == UpdateType.UPDATE_PROCEDURE) 
-				|| (container.getType() == Command.TYPE_DELETE && container.getUpdateInfo().getDeleteType() == UpdateType.UPDATE_PROCEDURE)) {
-			if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(crit).isEmpty()) {
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.virtual_update_subquery"), crit); //$NON-NLS-1$
-			}
-		}
-	}
-
-    public void visit(GroupBy obj) {
-    	// Get list of all group by IDs
-        List groupBySymbols = obj.getSymbols();
-        validateSortable(groupBySymbols);
-		Iterator symbolIter = groupBySymbols.iterator();
-		while(symbolIter.hasNext()) {
-            SingleElementSymbol symbol = (SingleElementSymbol)symbolIter.next();
-            if(symbol instanceof ExpressionSymbol) {
-                ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
-                Expression expr = exprSymbol.getExpression();
-                if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr).isEmpty() || expr instanceof Constant || expr instanceof Reference) {
-                	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.groupby_subquery", expr), expr); //$NON-NLS-1$
-                }
-            }                
-		}
-    }
-    
-    @Override
-    public void visit(GroupSymbol obj) {
-    	try {
-			if (this.getMetadata().isScalarGroup(obj.getMetadataID())) {
-			    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_scalar_group_reference", obj),obj); //$NON-NLS-1$    		
-			}
-		} catch (QueryMetadataException e) {
-			handleException(e);
-		} catch (TeiidComponentException e) {
-			handleException(e);
-		}
-    }
-
-    public void visit(Insert obj) {
-        validateNoXMLUpdates(obj);
-        validateGroupSupportsUpdate(obj.getGroup());
-        validateInsert(obj);
-        
-        if (obj.getQueryExpression() != null) {
-        	validateMultisourceInsert(obj.getGroup());
-        }
-        if (obj.getUpdateInfo() != null && obj.getUpdateInfo().isInherentInsert()) {
-	        Collection<ElementSymbol> updateCols = obj.getVariables();
-	    	if (obj.getUpdateInfo().findUpdateMapping(updateCols, false) == null) {
-	    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", updateCols), obj); //$NON-NLS-1$
-	    	}
-        }
-    }
-
-    @Override
-    public void visit(OrderByItem obj) {
-    	validateSortable(obj.getSymbol());
-    }
-    
-    public void visit(Query obj) {
-        validateHasProjectedSymbols(obj);
-        if(isXMLCommand(obj)) {
-            //no temp table (Select Into) allowed
-            if(obj.getInto() != null){
-                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0069"),obj); //$NON-NLS-1$
-            }
-
-        	this.isXML = true;
-	        validateXMLQuery(obj);
-        } else {
-            validateAggregates(obj);
-
-            //if it is select with no from, should not have ScalarSubQuery
-            if(obj.getSelect() != null && obj.getFrom() == null){
-                if(!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(obj.getSelect()).isEmpty()){
-                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0067"),obj); //$NON-NLS-1$
-                }
-            }
-            
-            if (obj.getInto() != null) {
-                validateSelectInto(obj);
-            }                        
-        }
-    }
-	
-	public void visit(Select obj) {
-        validateSelectElements(obj);
-        if(obj.isDistinct()) {
-            validateSortable(obj.getProjectedSymbols());
-        }
-    }
-
-	public void visit(SubquerySetCriteria obj) {
-		validateSubquery(obj);
-		if (isNonComparable(obj.getExpression())) {
-			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj); //$NON-NLS-1$
-    	}
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-        
-		Collection projSymbols = obj.getCommand().getProjectedSymbols();
-
-		//Subcommand should have one projected symbol (query with one expression
-		//in SELECT or stored procedure execution that returns a single value).
-		if(projSymbols.size() != 1) {
-			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0011"),obj); //$NON-NLS-1$
-		}
-	}
-
-    public void visit(DependentSetCriteria obj) {
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    public void visit(SetQuery obj) {
-        validateHasProjectedSymbols(obj);
-        validateSetQuery(obj);
-    }
-    
-    public void visit(Update obj) {
-        validateNoXMLUpdates(obj);
-        validateGroupSupportsUpdate(obj.getGroup());
-        validateUpdate(obj);
-    	validateVirtualUpdate(obj, obj.getCriteria());
-    }
-
-    public void visit(Into obj) {
-        GroupSymbol target = obj.getGroup();
-        validateGroupSupportsUpdate(target);
-        validateMultisourceInsert(obj.getGroup());
-    }
-
-	private void validateMultisourceInsert(GroupSymbol group) {
-		try {
-			if (getMetadata().isMultiSource(getMetadata().getModelID(group.getMetadataID()))) {
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.multisource_insert", group), group); //$NON-NLS-1$
-			}
-        } catch (QueryMetadataException e) {
-			handleException(e);
-		} catch (TeiidComponentException e) {
-			handleException(e);
-		}
-	}
-
-    public void visit(Function obj) {
-    	if(FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
-    		try {
-				ResolverUtil.ResolvedLookup resolvedLookup = ResolverUtil.resolveLookup(obj, getMetadata());
-				if(ValidationVisitor.isNonComparable(resolvedLookup.getKeyElement())) {
-		            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_lookup_key", resolvedLookup.getKeyElement()), resolvedLookup.getKeyElement()); //$NON-NLS-1$            
-		        }
-			} catch (TeiidComponentException e) {
-				handleException(e, obj);
-			} catch (TeiidProcessingException e) {
-				handleException(e, obj);
-			}
-        } else if (obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)) {
-            if(!isXML) {
-                // can't use this pseudo-function in non-XML queries
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command"), obj); //$NON-NLS-1$
-            } else {
-                if (!(obj.getArg(0) instanceof ElementSymbol)){
-                    handleValidationError(QueryPlugin.Util.getString("ERR.015.004.0036"), obj);  //$NON-NLS-1$
-                }
-                
-                for (Iterator functions = FunctionCollectorVisitor.getFunctions(obj.getArg(1), false).iterator(); functions.hasNext();) {
-                    Function function = (Function)functions.next();
-                    
-                    if (function.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)) {
-                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Context_function_nested"), obj); //$NON-NLS-1$
-                    }
-                }
-            }
-    	} else if (obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
-                   obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
-            if(isXML) {
-                if (!(obj.getArg(0) instanceof ElementSymbol)) {
-                    // Arg must be an element symbol
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.2"), obj); //$NON-NLS-1$
-                }
-            } else {
-                // can't use this pseudo-function in non-XML queries
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.The_rowlimit_function_cannot_be_used_in_a_non-XML_command"), obj); //$NON-NLS-1$
-            }
-        } else if(obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.XPATHVALUE)) {
-	        // Validate the xpath value is valid
-	        if(obj.getArgs()[1] instanceof Constant) {
-	            Constant xpathConst = (Constant) obj.getArgs()[1];
-                try {
-                    XMLSystemFunctions.validateXpath((String)xpathConst.getValue());
-                } catch(XPathException e) {
-                	handleValidationError(QueryPlugin.Util.getString("QueryResolver.invalid_xpath", e.getMessage()), obj); //$NON-NLS-1$
-                }
-	        }
-        } else if(obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.TO_BYTES) || obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.TO_CHARS)) {
-        	try {
-        		FunctionMethods.getCharset((String)((Constant)obj.getArg(1)).getValue());
-        	} catch (IllegalArgumentException e) {
-        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_encoding", obj.getArg(1)), obj); //$NON-NLS-1$
-        	}
-        }
-    }
-
-    // ############### Visitor methods for stored procedure lang objects ##################
-
-    public void visit(AssignmentStatement obj) {
-    	
-    	ElementSymbol variable = obj.getVariable();
-
-    	validateAssignment(obj, variable);
-    }
-    
-    @Override
-    public void visit(CommandStatement obj) {
-    	if (obj.getCommand() instanceof StoredProcedure) {
-    		StoredProcedure proc = (StoredProcedure)obj.getCommand();
-    		for (SPParameter param : proc.getParameters()) {
-				if ((param.getParameterType() == SPParameter.RETURN_VALUE 
-						|| param.getParameterType() == SPParameter.OUT) && param.getExpression() instanceof ElementSymbol) {
-					validateAssignment(obj, (ElementSymbol)param.getExpression());
-				}
-			}
-    	}
-    }
-
-	private void validateAssignment(LanguageObject obj,
-			ElementSymbol variable) {
-		String groupName = variable.getGroupSymbol().getCanonicalName();
-		//This will actually get detected by the resolver, since we inject an automatic declaration.
-    	if(groupName.equals(ProcedureReservedWords.CHANGING) || groupName.equals(ProcedureReservedWords.INPUTS)) {
-			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0012", ProcedureReservedWords.INPUTS, ProcedureReservedWords.CHANGING), obj); //$NON-NLS-1$
-		}
-	}
-    
-    @Override
-    public void visit(ScalarSubquery obj) {
-    	validateSubquery(obj);
-        Collection<SingleElementSymbol> projSymbols = obj.getCommand().getProjectedSymbols();
-
-        //Scalar subquery should have one projected symbol (query with one expression
-        //in SELECT or stored procedure execution that returns a single value).
-        if(projSymbols.size() != 1) {
-        	handleValidationError(QueryPlugin.Util.getString("ERR.015.008.0032", obj.getCommand()), obj.getCommand()); //$NON-NLS-1$
-        }
-    }
-
-    public void visit(CreateUpdateProcedureCommand obj) {
-        if(!obj.isUpdateProcedure()){
-        	//Every virtual procedure should have at least one query.
-        	if(CommandCollectorVisitor.getCommands(obj).isEmpty()){
-        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Procedure_should_have_query"), obj); //$NON-NLS-1$
-        	}
-        	
-            //check that the procedure does not contain references to itself
-            if (GroupCollectorVisitor.getGroups(obj,true).contains(obj.getVirtualGroup())) {
-            	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Procedure_has_group_self_reference"),obj); //$NON-NLS-1$
-            }
-            
-            return;
-        }
-
-		// set the state to validate this procedure
-        this.updateProc = obj;
-        validateContainsRowsUpdatedVariable(obj);
-    }
-
-    public void visit(DeclareStatement obj) {
-    	ElementSymbol variable = obj.getVariable();
-    	String elementname = variable.getShortName().toUpperCase();
-
-		// varible cannot be one of the special variables
-    	if(elementname.equals(ProcedureReservedWords.ROWS_UPDATED)) {
-			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0017", new Object[] {ProcedureReservedWords.ROWS_UPDATED}), obj); //$NON-NLS-1$
-		} else if(elementname.equals(ProcedureReservedWords.ROWCOUNT)) {
-			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0017", new Object[] {ProcedureReservedWords.ROWCOUNT}), obj); //$NON-NLS-1$
-		}
-        
-        validateAssignment(obj, obj.getVariable());
-    }
-
-    public void visit(IfStatement obj) {
-    	Criteria criteria = obj.getCondition();
-
-    	validatorCriteriaStatement(obj, criteria);
-    }
-    
-    public void visit(WhileStatement obj) {
-        Criteria criteria = obj.getCondition();
-
-        validatorCriteriaStatement(obj, criteria);
-    }
-
-    /** 
-     * @param obj
-     * @param criteria
-     */
-    private void validatorCriteriaStatement(LanguageObject obj,
-                                            Criteria criteria) {
-        Iterator criteriaIter = PredicateCollectorVisitor.getPredicates(criteria).iterator();
-    	while(criteriaIter.hasNext()) {
-    		Criteria predicateCriteria = (Criteria) criteriaIter.next();
-    		Iterator elmntIter = ElementCollectorVisitor.getElements(predicateCriteria, true).iterator();
-    		if(predicateCriteria instanceof TranslateCriteria) {
-				handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0019"), obj); //$NON-NLS-1$
-    		} else if(!(predicateCriteria instanceof HasCriteria)) {
-    			while(elmntIter.hasNext()) {
-    				ElementSymbol element = (ElementSymbol) elmntIter.next();
-    				if(!element.isExternalReference()) {
-						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0020"), obj); //$NON-NLS-1$
-    				}
-    			}
-    		}
-    	}
-    }
-
-    public void visit(TranslateCriteria obj) {
-
-		if(obj.hasTranslations()) {
-			Collection selectElmnts = null;
-			if(obj.getSelector().hasElements()) {
-				selectElmnts = obj.getSelector().getElements();
-			}
-			Iterator critIter = obj.getTranslations().iterator();
-			while(critIter.hasNext()) {
-				CompareCriteria transCrit = (CompareCriteria) critIter.next();
-				Collection leftElmnts = ElementCollectorVisitor.getElements(transCrit.getLeftExpression(), true);
-				// there is always only one element
-				ElementSymbol leftExpr = (ElementSymbol)leftElmnts.iterator().next();
-
-				if(selectElmnts != null && !selectElmnts.contains(leftExpr)) {
-					handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0021"), leftExpr); //$NON-NLS-1$
-				}
-			}
-		}
-
-		// additional validation checks
-		validateTranslateCriteria(obj);
-    }
-
-    public void visit(CompoundCriteria obj) {
-        // Validate use of 'rowlimit' or 'rowlimitexception' pseudo-function - each occurrence must be in a single
-        // CompareCriteria which is entirely it's own conjunct (not OR'ed with anything else)
-        if (isXML) {
-            // Collect all occurrances of rowlimit and rowlimitexception functions
-            List rowLimitFunctions = new ArrayList();
-            FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
-            PreOrderNavigator.doVisit(obj, visitor); 
-            visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
-            PreOrderNavigator.doVisit(obj, visitor);
-            final int functionCount = rowLimitFunctions.size();
-            if (functionCount > 0) {
-                
-                // Verify each use of rowlimit function is in a compare criteria that is 
-                // entirely it's own conjunct
-                Iterator conjunctIter = Criteria.separateCriteriaByAnd(obj).iterator();            
-                
-                int i = 0;
-                while (conjunctIter.hasNext() && i<functionCount ) {
-                    Object conjunct = conjunctIter.next();
-                    if (conjunct instanceof CompareCriteria) {
-                        CompareCriteria crit = (CompareCriteria)conjunct;
-                        if ((rowLimitFunctions.contains(crit.getLeftExpression()) && !rowLimitFunctions.contains(crit.getRightExpression())) || 
-                            (rowLimitFunctions.contains(crit.getRightExpression()) && !rowLimitFunctions.contains(crit.getLeftExpression()))) {
-                        	i++;
-                        }
-                    }
-                }
-                if (i<functionCount) {
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.3"), obj); //$NON-NLS-1$
-                }
-            }
-        }
-        
-    }
-
-    // ######################### Validation methods #########################
-
-	/**
-	 * A valid translated expression is not an <code>AggregateSymbol</code> and
-	 * does not include elements not present on the groups of the command using
-	 * the translated criteria.
-	 */
-    protected void validateTranslateCriteria(TranslateCriteria obj) {
-    	if(this.currentCommand == null) {
-    		return;
-    	}
-    	Map symbolMap = this.updateProc.getSymbolMap();
-		Command userCommand = this.updateProc.getUserCommand();
-    	// modeler validation
-    	if(userCommand == null) {
-    		return;
-    	}
-		Criteria userCrit = null;
-		int userCmdType = userCommand.getType();
-		switch(userCmdType) {
-			case Command.TYPE_DELETE:
-				userCrit = ((Delete)userCommand).getCriteria();
-				break;
-			case Command.TYPE_UPDATE:
-				userCrit = ((Update)userCommand).getCriteria();
-				break;
-			default:
-				break;
-		}
-		// nothing to validate if there is no user criteria
-		if(userCrit == null) {
-			return;
-		}
-
-    	Collection transleElmnts = ElementCollectorVisitor.getElements(obj, true);
-    	Collection groups = GroupCollectorVisitor.getGroups(this.currentCommand, true);
-		int selectType = obj.getSelector().getSelectorType();
-
-		Collection predicates = PredicateCollectorVisitor.getPredicates(userCrit);
-		if (predicates.size() != Criteria.separateCriteriaByAnd(userCrit).size()) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.translated_or"), userCrit); //$NON-NLS-1$
-		}
-		Iterator critIter = predicates.iterator();
-		while(critIter.hasNext()) {
-			Criteria predCrit = (Criteria) critIter.next();
-			if(selectType != CriteriaSelector.NO_TYPE) {
-				if(predCrit instanceof CompareCriteria) {
-					CompareCriteria ccCrit = (CompareCriteria) predCrit;
-					if(selectType != ccCrit.getOperator()) {
-						continue;
-					}
-				} else if(predCrit instanceof MatchCriteria) {
-					if(selectType != CriteriaSelector.LIKE) {
-						continue;
-					}
-				} else if(predCrit instanceof IsNullCriteria) {
-					if(selectType != CriteriaSelector.IS_NULL) {
-						continue;
-					}
-                } else if(predCrit instanceof SetCriteria) {
-                    if(selectType != CriteriaSelector.IN) {
-                    	continue;
-                    }
-                } else if(predCrit instanceof BetweenCriteria) {
-                    if(selectType != CriteriaSelector.BETWEEN) {
-                    	continue;
-                    }
-				}
-			}
-	    	Iterator critEmlntIter = ElementCollectorVisitor.getElements(predCrit, true).iterator();
-	    	// collect all elements elements on the criteria map to
-	    	while(critEmlntIter.hasNext()) {
-	    		ElementSymbol criteriaElement = (ElementSymbol) critEmlntIter.next();
-	    		if(transleElmnts.contains(criteriaElement)) {
-		    		Expression mappedExpr = (Expression) symbolMap.get(criteriaElement);
-		    		if(mappedExpr instanceof AggregateSymbol) {
-						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0022", criteriaElement), criteriaElement); //$NON-NLS-1$
-		    		}
-
-		    		Iterator mapElmntIter = ElementCollectorVisitor.getElements(mappedExpr, true).iterator();
-			    	boolean groupMatch = false;
-			    	while(mapElmntIter.hasNext()) {
-				    	ElementSymbol mapElement = (ElementSymbol) mapElmntIter.next();
-				    	GroupSymbol mapGrp = mapElement.getGroupSymbol();
-				    	if(groups.contains(mapGrp)) {
-				    		groupMatch = true;
-				    	}
-			    	}
-			    	if(!groupMatch) {
-						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0023", criteriaElement), criteriaElement); //$NON-NLS-1$
-			    	}
-				}
-	    	}
-		}
-    }
-
-    protected void validateSelectElements(Select obj) {
-    	if(isXML) {
-    		return;
-    	}
-
-        Collection elements = ElementCollectorVisitor.getElements(obj, true);
-        
-        Collection cantSelect = validateElementsSupport(
-            elements,
-            SupportConstants.Element.SELECT );
-
-		if(cantSelect != null) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0024", cantSelect), cantSelect); //$NON-NLS-1$
-		}
-    }
-
-    protected void validateHasProjectedSymbols(Command obj) {
-        if(obj.getProjectedSymbols().size() == 0) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0025"), obj); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Validate that no elements of type OBJECT are in a SELECT DISTINCT or
-     * and ORDER BY.
-     * @param symbols List of SingleElementSymbol
-     */
-    protected void validateSortable(List symbols) {
-        Iterator iter = symbols.iterator();
-        while(iter.hasNext()) {
-            SingleElementSymbol symbol = (SingleElementSymbol) iter.next();
-            validateSortable(symbol);
-        }
-    }
-
-	private void validateSortable(SingleElementSymbol symbol) {
-		if (isNonComparable(symbol)) {
-		    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0026", symbol), symbol); //$NON-NLS-1$
-		}
-	}
-
-    public static boolean isNonComparable(Expression symbol) {
-        return DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(symbol.getType()));
-    }
-
-	/**
-	 * This method can be used to validate Update commands cannot be
-	 * executed against XML documents.
-	 */
-    protected void validateNoXMLUpdates(Command obj) {
-     	if(isXMLCommand(obj)) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0029"), obj); //$NON-NLS-1$
-     	}
-    }
-
-	/**
-	 * This method can be used to validate commands used in the stored
-	 * procedure languge cannot be executed against XML documents.
-	 */
-    protected void validateNoXMLProcedures(Command obj) {
-     	if(isXMLCommand(obj)) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0030"), obj); //$NON-NLS-1$
-     	}
-    }
-
-    private void validateXMLQuery(Query obj) {
-        if(obj.getGroupBy() != null) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0031"), obj); //$NON-NLS-1$
-        }
-        if(obj.getHaving() != null) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0032"), obj); //$NON-NLS-1$
-        }
-        if(obj.getLimit() != null) {
-            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.limit_not_valid_for_xml"), obj); //$NON-NLS-1$
-        }
-        if (obj.getOrderBy() != null) {
-        	OrderBy orderBy = obj.getOrderBy();
-        	for (OrderByItem item : orderBy.getOrderByItems()) {
-				if (!(item.getSymbol() instanceof ElementSymbol)) {
-					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.orderby_expression_xml"), obj); //$NON-NLS-1$
-				}
-			}
-         }
-    }
-    
-    protected void validateGroupSupportsUpdate(GroupSymbol groupSymbol) {
-    	try {
-	    	if(! getMetadata().groupSupports(groupSymbol.getMetadataID(), SupportConstants.Group.UPDATE)) {
-	            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0033", SQLStringVisitor.getSQLString(groupSymbol)), groupSymbol); //$NON-NLS-1$
-	        }
-	    } catch (TeiidComponentException e) {
-	        handleException(e, groupSymbol);
-	    }
-    }
-    
-    protected void validateSetQuery(SetQuery query) {
-        // Walk through sub queries - validate each one separately and
-        // also check the columns of each for comparability
-        for (QueryCommand subQuery : query.getQueryCommands()) {
-            if(isXMLCommand(subQuery)) {
-                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0034"), query); //$NON-NLS-1$
-            }
-            if (subQuery instanceof Query && ((Query)subQuery).getInto() != null) {
-            	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.union_insert"), query); //$NON-NLS-1$
-            }
-        }
-        
-        if (!query.isAll() || query.getOperation() == Operation.EXCEPT || query.getOperation() == Operation.INTERSECT) {
-            validateSortable(query.getProjectedSymbols());
-        }
-        
-        if (query.isAll() && (query.getOperation() == Operation.EXCEPT || query.getOperation() == Operation.INTERSECT)) {
-            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.excpet_intersect_all"), query); //$NON-NLS-1$
-        }
-    }
-
-    private void validateAggregates(Query query) {
-        Select select = query.getSelect();
-        GroupBy groupBy = query.getGroupBy();
-        Criteria having = query.getHaving();
-        if(groupBy != null || having != null || !AggregateSymbolCollectorVisitor.getAggregates(select, false).isEmpty()) {
-            Set<Expression> groupSymbols = null;
-            if(groupBy != null) {
-                groupSymbols = new HashSet<Expression>();
-                for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
-                    final SingleElementSymbol element = (SingleElementSymbol)iterator.next();
-                    groupSymbols.add(SymbolMap.getExpression(element));
-                }
-            }
-            
-            // Validate HAVING, if it exists
-            AggregateValidationVisitor visitor = new AggregateValidationVisitor(groupSymbols);
-            if(having != null) {
-                AggregateValidationVisitor.validate(having, visitor);
-            }
-            
-            // Validate SELECT
-            List projectedSymbols = select.getProjectedSymbols();
-            Iterator symbolIter = projectedSymbols.iterator();
-            while(symbolIter.hasNext()) {
-                SingleElementSymbol symbol = (SingleElementSymbol) symbolIter.next();
-                AggregateValidationVisitor.validate(symbol, visitor);                                            
-            }
-            
-            // Move items to this report
-            ValidatorReport report = visitor.getReport();
-            Collection items = report.getItems();
-            super.getReport().addItems(items);        
-        }
-    }
-    
-    protected void validateInsert(Insert obj) {
-        Collection vars = obj.getVariables();
-        Iterator varIter = vars.iterator();
-        Collection values = obj.getValues();
-        Iterator valIter = values.iterator();
-        GroupSymbol insertGroup = obj.getGroup();
-
-
-        try {
-            // Validate that all elements in variable list are updatable
-            Iterator elementIter = vars.iterator();
-            while(elementIter.hasNext()) {
-                ElementSymbol insertElem = (ElementSymbol) elementIter.next();
-                if(! getMetadata().elementSupports(insertElem.getMetadataID(), SupportConstants.Element.UPDATE)) {
-                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0052", insertElem), insertElem); //$NON-NLS-1$
-                }
-            }
-
-            // Get elements in the group.
-    		Collection insertElmnts = new LinkedList(ResolverUtil.resolveElementsInGroup(insertGroup, getMetadata()));
-
-    		// remove all elements specified in insert to get the ignored elements
-    		insertElmnts.removeAll(vars);
-
-			Iterator ignoreIter = insertElmnts.iterator();
-			while(ignoreIter.hasNext()) {
-	            ElementSymbol nextElmnt = (ElementSymbol) ignoreIter.next();
-				if(!getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.DEFAULT_VALUE) &&
-					!getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.NULL) &&
-                    !getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.AUTO_INCREMENT) &&
-                     !getMetadata().isMultiSourceElement(nextElmnt.getMetadataID())) {
-		                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0053", new Object[] {insertGroup, nextElmnt}), nextElmnt); //$NON-NLS-1$
-				}
-			}
-
-            //check to see if the elements support nulls in metadata,
-            // if any of the value present in the insert are null
-            while(valIter.hasNext() && varIter.hasNext()) {
-                Expression nextValue = (Expression) valIter.next();
-                ElementSymbol nextVar = (ElementSymbol) varIter.next();
-
-                if (EvaluatableVisitor.isFullyEvaluatable(nextValue, true)) {
-                    try {
-                        // If nextValue is an expression, evaluate it before checking for null
-                        Object evaluatedValue = Evaluator.evaluate(nextValue);
-                        if(evaluatedValue == null && ! getMetadata().elementSupports(nextVar.getMetadataID(), SupportConstants.Element.NULL)) {
-                            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0055", SQLStringVisitor.getSQLString(nextVar)), nextVar); //$NON-NLS-1$
-                        }
-                    } catch(ExpressionEvaluationException e) {
-                        //ignore for now, we don't have the context which could be the problem
-                    }
-                }
-            }// end of while
-        } catch(TeiidComponentException e) {
-            handleException(e, obj);
-        } 
-    }
-    
-    protected void validateSetClauseList(SetClauseList list) {
-    	Set<ElementSymbol> dups = new HashSet<ElementSymbol>();
-	    HashSet<ElementSymbol> changeVars = new HashSet<ElementSymbol>();
-	    for (SetClause clause : list.getClauses()) {
-	    	ElementSymbol elementID = clause.getSymbol();
-	        if (!changeVars.add(elementID)) {
-	        	dups.add(elementID);
-	        }
-		}
-	    if(!dups.isEmpty()) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0062", dups), dups); //$NON-NLS-1$
-	    }
-    }
-    
-    protected void validateUpdate(Update update) {
-        try {
-            UpdateInfo info = update.getUpdateInfo();
-
-            // list of elements that are being updated
-		    for (SetClause entry : update.getChangeList().getClauses()) {
-        	    ElementSymbol elementID = entry.getSymbol();
-
-                // Check that left side element is updatable
-                if(! getMetadata().elementSupports(elementID.getMetadataID(), SupportConstants.Element.UPDATE)) {
-                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0059", elementID), elementID); //$NON-NLS-1$
-                }
-                
-                Object metadataID = elementID.getMetadataID();
-                if (getMetadata().isMultiSourceElement(metadataID)){
-                	handleValidationError(QueryPlugin.Util.getString("multi_source_update_not_allowed", elementID), elementID); //$NON-NLS-1$
-                }
-
-			    // Check that right expression is a constant and is non-null
-                Expression value = entry.getValue();
-                
-                if (EvaluatableVisitor.isFullyEvaluatable(value, true)) {
-                    try {
-                        value = new Constant(Evaluator.evaluate(value));
-                    } catch (ExpressionEvaluationException err) {
-                    }
-                }
-                
-                if(value instanceof Constant) {
-    			    // If value is null, check that element supports this as a nullable column
-                    if(((Constant)value).isNull() && ! getMetadata().elementSupports(elementID.getMetadataID(), SupportConstants.Element.NULL)) {
-                        handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0060", SQLStringVisitor.getSQLString(elementID)), elementID); //$NON-NLS-1$
-                    }// end of if
-                } else if (info != null && info.getUpdateType() == UpdateType.UPDATE_PROCEDURE && getMetadata().isVirtualGroup(update.getGroup().getMetadataID()) && !EvaluatableVisitor.willBecomeConstant(value)) {
-                    // If this is an update on a virtual group, verify that no elements are in the right side
-                    Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(value, false);
-                    for (ElementSymbol element : elements) {
-                        if(! element.isExternalReference()) {
-                            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0061", SQLStringVisitor.getSQLString(value)), value); //$NON-NLS-1$
-                        }
-                    }
-                } 
-		    }
-            if (info != null && info.isInherentUpdate()) {
-            	Set<ElementSymbol> updateCols = update.getChangeList().getClauseMap().keySet();
-            	if (!info.hasValidUpdateMapping(updateCols)) {
-            		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", updateCols), update); //$NON-NLS-1$
-            	}
-            }
-        } catch(TeiidException e) {
-            handleException(e, update);
-        }
-        
-        validateSetClauseList(update.getChangeList());
-    }
-    
-    /**
-     * Validates SELECT INTO queries.
-     * @param query
-     * @since 4.2
-     */
-    protected void validateSelectInto(Query query) {
-        List symbols = query.getSelect().getProjectedSymbols();
-        GroupSymbol intoGroup = query.getInto().getGroup();
-        validateInto(query, symbols, intoGroup);
-    }
-
-    private void validateInto(LanguageObject query,
-                                List symbols,
-                                GroupSymbol intoGroup) {
-        try {
-            List elementIDs = getMetadata().getElementIDsInGroupID(intoGroup.getMetadataID());
-            
-            // Check if there are too many elements in the SELECT clause
-            if (symbols.size() != elementIDs.size()) {
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.select_into_wrong_elements", new Object[] {new Integer(elementIDs.size()), new Integer(symbols.size())}), query); //$NON-NLS-1$
-                return;
-            }
-            
-            for (int symbolNum = 0; symbolNum < symbols.size(); symbolNum++) {
-                SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(symbolNum);
-                Object elementID = elementIDs.get(symbolNum);
-                // Check if supports updates
-                if (!getMetadata().elementSupports(elementID, SupportConstants.Element.UPDATE)) {
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.element_updates_not_allowed", getMetadata().getFullName(elementID)), intoGroup); //$NON-NLS-1$
-                }
-
-                Class symbolType = symbol.getType();
-                String symbolTypeName = DataTypeManager.getDataTypeName(symbolType);
-                String targetTypeName = getMetadata().getElementType(elementID);
-                if (symbolTypeName.equals(targetTypeName)) {
-                    continue;
-                }
-                if (!DataTypeManager.isImplicitConversion(symbolTypeName, targetTypeName)) { // If there's no implicit conversion between the two
-                    Object[] params = new Object [] {symbolTypeName, targetTypeName, new Integer(symbolNum + 1), query};
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.select_into_no_implicit_conversion", params), query); //$NON-NLS-1$
-                    continue;
-                }
-            }
-        } catch (TeiidComponentException e) {
-            handleException(e, query);
-        } 
-    }
-    
-    /**
-     * Validate that the command assigns a value to the ROWS_UPDATED variable 
-     * @param obj
-     * @since 4.2
-     */
-    protected void validateContainsRowsUpdatedVariable(CreateUpdateProcedureCommand obj) {
-        final Collection assignVars = new ArrayList();
-       // Use visitor to find assignment statements
-        LanguageVisitor visitor = new LanguageVisitor() {
-            public void visit(AssignmentStatement obj) {
-                assignVars.add(obj.getVariable());
-            }
-        };
-        PreOrderNavigator.doVisit(obj, visitor);
-        boolean foundVar = false;
-        for(Iterator varIter = assignVars.iterator(); varIter.hasNext();) {
-            ElementSymbol variable = (ElementSymbol) varIter.next();
-            if(variable.getShortName().equalsIgnoreCase(ProcedureReservedWords.ROWS_UPDATED)) {
-                foundVar = true;
-                break;
-            }
-        }
-        if(!foundVar) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0016", ProcedureReservedWords.ROWS_UPDATED), obj); //$NON-NLS-1$
-        }
-    }
-    
-    private void validateRowLimitFunctionNotInInvalidCriteria(Criteria obj) {
-        // Collect all occurrances of rowlimit and rowlimitexception functions
-        List rowLimitFunctions = new ArrayList();
-        FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
-        PreOrderNavigator.doVisit(obj, visitor);      
-        visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
-        PreOrderNavigator.doVisit(obj, visitor); 
-        if (rowLimitFunctions.size() > 0) {
-            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.3"), obj); //$NON-NLS-1$
-        }
-    }
-    
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.BetweenCriteria)
-     * @since 4.3
-     */
-    public void visit(BetweenCriteria obj) {
-    	if (isNonComparable(obj.getExpression())) {
-    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
-    	}
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.IsNullCriteria)
-     * @since 4.3
-     */
-    public void visit(IsNullCriteria obj) {
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.MatchCriteria)
-     * @since 4.3
-     */
-    public void visit(MatchCriteria obj) {
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.NotCriteria)
-     * @since 4.3
-     */
-    public void visit(NotCriteria obj) {
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SetCriteria)
-     * @since 4.3
-     */
-    public void visit(SetCriteria obj) {
-    	if (isNonComparable(obj.getExpression())) {
-    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
-    	}
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
-     * @since 4.3
-     */
-    public void visit(SubqueryCompareCriteria obj) {
-    	validateSubquery(obj);
-    	if (isNonComparable(obj.getLeftExpression())) {
-    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
-    	}
-        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
-    }
-    
-    public void visit(Option obj) {
-        List dep = obj.getDependentGroups();
-        List notDep = obj.getNotDependentGroups();
-        if (dep != null && !dep.isEmpty()
-            && notDep != null && !notDep.isEmpty()) {
-            String groupName = null;
-            String notDepGroup = null;
-            for (Iterator i = dep.iterator(); i.hasNext();) {
-                groupName = (String)i.next();
-                for (Iterator j = notDep.iterator(); j.hasNext();) {
-                    notDepGroup = (String)j.next();
-                    if (notDepGroup.equalsIgnoreCase(groupName)) {
-                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.group_in_both_dep", groupName), obj); //$NON-NLS-1$
-                        return;
-                    }
-                }
-            }
-        }
-    }
-    
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.DynamicCommand)
-     */
-    public void visit(DynamicCommand obj) {
-        if (obj.getIntoGroup() != null) {
-            validateInto(obj, obj.getAsColumns(), obj.getIntoGroup());
-        }
-        if (obj.getUsing() != null) {
-        	validateSetClauseList(obj.getUsing());
-        }
-    }
-    
-    @Override
-    public void visit(Create obj) {
-    	if (!obj.getPrimaryKey().isEmpty()) {
-    		validateSortable(obj.getPrimaryKey());
-    	}
-    }
-    
-    /** 
-     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.Drop)
-     */
-    public void visit(Drop drop) {
-        if (!drop.getTable().isTempTable()) {
-            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.drop_of_nontemptable", drop.getTable()), drop); //$NON-NLS-1$
-        }
-    }
-    
-    @Override
-    public void visit(CompareCriteria obj) {
-    	if (isNonComparable(obj.getLeftExpression())) {
-    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
-    	}
-    	
-        // Validate use of 'rowlimit' and 'rowlimitexception' pseudo-functions - they cannot be nested within another
-        // function, and their operands must be a nonnegative integers
-
-        // Collect all occurrences of rowlimit function
-        List rowLimitFunctions = new ArrayList();
-        FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
-        PreOrderNavigator.doVisit(obj, visitor);   
-        visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
-        PreOrderNavigator.doVisit(obj, visitor);            
-        final int functionCount = rowLimitFunctions.size();
-        if (functionCount > 0) {
-            Function function = null;
-            Expression expr = null;
-            if (obj.getLeftExpression() instanceof Function) {
-                Function leftExpr = (Function)obj.getLeftExpression();
-                if (leftExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
-                    leftExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
-                    function = leftExpr;
-                    expr = obj.getRightExpression();
-                }
-            } 
-            if (function == null && obj.getRightExpression() instanceof Function) {
-                Function rightExpr = (Function)obj.getRightExpression();
-                if (rightExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
-                    rightExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
-                    function = rightExpr;
-                    expr = obj.getLeftExpression();
-                }
-            }
-            if (function == null) {
-                // must be nested, which is invalid
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.0"), obj); //$NON-NLS-1$
-            } else {
-                if (expr instanceof Constant) {
-                    Constant constant = (Constant)expr;
-                    if (constant.getValue() instanceof Integer) {
-                        Integer integer = (Integer)constant.getValue();
-                        if (integer.intValue() < 0) {
-                            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
-                        }
-                    } else {
-                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
-                    }
-                } else if (expr instanceof Reference) {
-                	((Reference)expr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.1")); //$NON-NLS-1$
-                } else {
-                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
-                }
-            }                 
-        }
-    }
-    
-    public void visit(Limit obj) {
-        Expression offsetExpr = obj.getOffset();
-        if (offsetExpr instanceof Constant) {
-            Integer offset = (Integer)((Constant)offsetExpr).getValue();
-            if (offset.intValue() < 0) {
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.badoffset2"), obj); //$NON-NLS-1$
-            }
-        } else if (offsetExpr instanceof Reference) {
-        	((Reference)offsetExpr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.badoffset2")); //$NON-NLS-1$
-        }
-        Expression limitExpr = obj.getRowLimit();
-        if (limitExpr instanceof Constant) {
-            Integer limit = (Integer)((Constant)limitExpr).getValue();
-            if (limit.intValue() < 0) {
-                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.badlimit2"), obj); //$NON-NLS-1$
-            }
-        } else if (limitExpr instanceof Reference) {
-        	((Reference)limitExpr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.badlimit2")); //$NON-NLS-1$
-        }
-    }
-    
-    @Override
-    public void visit(XMLForest obj) {
-    	validateDerivedColumnNames(obj, obj.getArgs());
-    	for (DerivedColumn dc : obj.getArgs()) {
-			if (dc.getAlias() == null) {
-				continue;
-			}
-			validateQName(obj, dc.getAlias());
-			validateXMLContentTypes(dc.getExpression(), obj);
-		}
-    }
-    
-    @Override
-    public void visit(AggregateSymbol obj) {
-    	if (obj.getAggregateFunction() != Type.TEXTAGG) {
-    		return;
-    	}
-    	TextLine tl = (TextLine)obj.getExpression();
-    	if (tl.isIncludeHeader()) {
-    		validateDerivedColumnNames(obj, tl.getExpressions());
-    	}
-    	for (DerivedColumn dc : tl.getExpressions()) {
-			validateXMLContentTypes(dc.getExpression(), obj);
-		}
-    	validateTextOptions(obj, tl.getDelimiter(), tl.getQuote());
-    	if (tl.getEncoding() != null) {
-    		try {
-    			Charset.forName(tl.getEncoding());
-    		} catch (IllegalArgumentException e) {
-    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_encoding", tl.getEncoding()), obj); //$NON-NLS-1$
-    		}
-    	}
-    }
-    
-	private String[] validateQName(LanguageObject obj, String name) {
-		try {
-			return Name11Checker.getInstance().getQNameParts(name);
-		} catch (QNameException e) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_invalid_qname", name), obj); //$NON-NLS-1$
-		}
-		return null;
-	}
-
-	private void validateDerivedColumnNames(LanguageObject obj, List<DerivedColumn> cols) {
-		for (DerivedColumn dc : cols) {
-    		if (dc.getAlias() == null && !(dc.getExpression() instanceof ElementSymbol)) {
-    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.expression_requires_name"), obj); //$NON-NLS-1$
-        	} 
-		}
-	}
-    
-    @Override
-    public void visit(XMLAttributes obj) {
-    	validateDerivedColumnNames(obj, obj.getArgs());
-    	for (DerivedColumn dc : obj.getArgs()) {
-			if (dc.getAlias() == null) {
-				continue;
-			}
-			if ("xmlns".equals(dc.getAlias())) { //$NON-NLS-1$
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_attributes_reserved"), obj); //$NON-NLS-1$
-			}
-			String[] parts = validateQName(obj, dc.getAlias());
-			if (parts == null) {
-				continue;
-			}
-			if ("xmlns".equals(parts[0])) { //$NON-NLS-1$
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_attributes_reserved", dc.getAlias()), obj); //$NON-NLS-1$
-			}
-		}
-    }
-    
-    @Override
-    public void visit(XMLElement obj) {
-    	for (Expression expression : obj.getContent()) {
-    		validateXMLContentTypes(expression, obj);
-    	}
-    	validateQName(obj, obj.getName());
-    }
-    
-    public void validateXMLContentTypes(Expression expression, LanguageObject parent) {
-		if (expression.getType() == DataTypeManager.DefaultDataClasses.OBJECT || expression.getType() == DataTypeManager.DefaultDataClasses.BLOB) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_content_type", expression), parent); //$NON-NLS-1$
-		}
-    }
-    
-    @Override
-    public void visit(QueryString obj) {
-    	validateDerivedColumnNames(obj, obj.getArgs());
-    }
-    
-    @Override
-    public void visit(XMLTable obj) {
-    	List<DerivedColumn> passing = obj.getPassing();
-    	validatePassing(obj, obj.getXQueryExpression(), passing);
-    	boolean hasOrdinal = false;
-    	for (XMLColumn xc : obj.getColumns()) {
-			if (!xc.isOrdinal()) {
-				if (xc.getDefaultExpression() != null && !EvaluatableVisitor.isFullyEvaluatable(obj, false)) {
-					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_default", xc.getDefaultExpression()), obj); //$NON-NLS-1$
-				}
-				continue;
-			}
-			if (hasOrdinal) {
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.one_ordinal"), obj); //$NON-NLS-1$
-				break;
-			}
-			hasOrdinal = true;
-		}
-    }
-    
-    @Override
-    public void visit(XMLQuery obj) {
-    	validatePassing(obj, obj.getXQueryExpression(), obj.getPassing());
-    }
-
-	private void validatePassing(LanguageObject obj, SaxonXQueryExpression xqe, List<DerivedColumn> passing) {
-		boolean context = false;
-    	boolean hadError = false;
-    	HashSet<String> names = new HashSet<String>();
-    	for (DerivedColumn dc : passing) {
-    		if (dc.getAlias() == null) {
-    			Class<?> type = dc.getExpression().getType();
-    			if (type != DataTypeManager.DefaultDataClasses.XML) {
-    				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.context_item_type"), obj); //$NON-NLS-1$
-    			}
-    			if (context && !hadError) {
-    				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.passing_requires_name"), obj); //$NON-NLS-1$
-    				hadError = true;
-    			}
-    			context = true;
-        	} else { 
-        		validateXMLContentTypes(dc.getExpression(), obj);
-        		if (!names.add(dc.getAlias().toUpperCase())) {
-        			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.duplicate_passing", dc.getAlias()), obj); //$NON-NLS-1$
-        		}
-        	}
-		}
-    	if (xqe.usesContextItem() && !context) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.context_required"), obj); //$NON-NLS-1$    		
-    	}
-	}
-    
-    @Override
-    public void visit(XMLNamespaces obj) {
-    	boolean hasDefault = false;
-    	for (XMLNamespaces.NamespaceItem item : obj.getNamespaceItems()) {
-			if (item.getPrefix() != null) {
-				if (item.getPrefix().equals("xml") || item.getPrefix().equals("xmlns")) { //$NON-NLS-1$ //$NON-NLS-2$
-					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces_reserved"), obj); //$NON-NLS-1$
-				}
-				if (item.getUri().length() == 0) {
-					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces_null_uri"), obj); //$NON-NLS-1$
-				}
-				continue;
-			}
-			if (hasDefault) {
-				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces"), obj); //$NON-NLS-1$
-				break;
-			}
-			hasDefault = true;
-		}
-    }
-    
-    @Override
-    public void visit(TextTable obj) {
-    	boolean widthSet = false;
-    	Character delimiter = null;
-    	Character quote = null;
-    	for (TextTable.TextColumn column : obj.getColumns()) {
-			if (column.getWidth() != null) {
-				widthSet = true;
-				if (column.getWidth() < 0) {
-					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
-				}
-			} else if (widthSet) {
-    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_invalid_width"), obj); //$NON-NLS-1$
-			}
-		}
-    	if (widthSet) {
-    		if (obj.getDelimiter() != null || obj.getHeader() != null || obj.getQuote() != null) {
-        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_width"), obj); //$NON-NLS-1$
-    		}
-    	} else {
-        	if (obj.getHeader() != null && obj.getHeader() < 0) {
-	    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
-	    	}
-    		delimiter = obj.getDelimiter();
-    		quote = obj.getQuote();
-			validateTextOptions(obj, delimiter, quote);
-    	}
-    	if (obj.getSkip() != null && obj.getSkip() < 0) {
-    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
-    	}
-    }
-
-	private void validateTextOptions(LanguageObject obj, Character delimiter,
-			Character quote) {
-		if (quote == null) {
-			quote = '"';
-		} 
-		if (delimiter == null) {
-			delimiter = ',';
-		}
-		if (EquivalenceUtil.areEqual(quote, delimiter)) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_delimiter"), obj); //$NON-NLS-1$
-		}
-		if (EquivalenceUtil.areEqual(quote, '\n') 
-				|| EquivalenceUtil.areEqual(delimiter, '\n')) {
-			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_newline"), obj); //$NON-NLS-1$
-		}
-	}
-    
-    @Override
-    public void visit(XMLParse obj) {
-    	if (obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.STRING && 
-    			obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.CLOB &&
-    			obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.BLOB) {
-    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xmlserialize_type"), obj); //$NON-NLS-1$
-    	}
-    }
-    
-    @Override
-    public void visit(ExistsCriteria obj) {
-    	validateSubquery(obj);
-    }
-    
-    @Override
-    public void visit(SubqueryFromClause obj) {
-    	validateSubquery(obj);
-    }
-    
-    @Override
-    public void visit(LoopStatement obj) {
-    	validateSubquery(obj);
-    }
-    
-    @Override
-    public void visit(WithQueryCommand obj) {
-    	validateSubquery(obj);
-    }
-
-    //TODO: it may be simpler to catch this in the parser
-    private void validateSubquery(SubqueryContainer subQuery) {
-    	if (subQuery.getCommand() instanceof Query && ((Query)subQuery.getCommand()).getInto() != null) {
-        	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.subquery_insert"), subQuery.getCommand()); //$NON-NLS-1$
-        }
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java (from rev 2774, trunk/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1452 @@
+/*
+ * 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.validator;
+
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import net.sf.saxon.om.Name11Checker;
+import net.sf.saxon.om.QNameException;
+import net.sf.saxon.trans.XPathException;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.FunctionLibrary;
+import org.teiid.query.function.FunctionMethods;
+import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.metadata.SupportConstants;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.BatchedUpdateCommand;
+import org.teiid.query.sql.lang.BetweenCriteria;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.CompoundCriteria;
+import org.teiid.query.sql.lang.Create;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Delete;
+import org.teiid.query.sql.lang.DependentSetCriteria;
+import org.teiid.query.sql.lang.Drop;
+import org.teiid.query.sql.lang.DynamicCommand;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
+import org.teiid.query.sql.lang.Into;
+import org.teiid.query.sql.lang.IsNullCriteria;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.MatchCriteria;
+import org.teiid.query.sql.lang.NotCriteria;
+import org.teiid.query.sql.lang.Option;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetClause;
+import org.teiid.query.sql.lang.SetClauseList;
+import org.teiid.query.sql.lang.SetCriteria;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.lang.SubqueryCompareCriteria;
+import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.lang.SubqueryFromClause;
+import org.teiid.query.sql.lang.SubquerySetCriteria;
+import org.teiid.query.sql.lang.TextTable;
+import org.teiid.query.sql.lang.Update;
+import org.teiid.query.sql.lang.WithQueryCommand;
+import org.teiid.query.sql.lang.XMLTable;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+import org.teiid.query.sql.lang.XMLTable.XMLColumn;
+import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.CommandStatement;
+import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
+import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.DeclareStatement;
+import org.teiid.query.sql.proc.HasCriteria;
+import org.teiid.query.sql.proc.IfStatement;
+import org.teiid.query.sql.proc.LoopStatement;
+import org.teiid.query.sql.proc.TranslateCriteria;
+import org.teiid.query.sql.proc.WhileStatement;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.DerivedColumn;
+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.QueryString;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.ScalarSubquery;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.XMLAttributes;
+import org.teiid.query.sql.symbol.XMLElement;
+import org.teiid.query.sql.symbol.XMLForest;
+import org.teiid.query.sql.symbol.XMLNamespaces;
+import org.teiid.query.sql.symbol.XMLParse;
+import org.teiid.query.sql.symbol.XMLQuery;
+import org.teiid.query.sql.symbol.AggregateSymbol.Type;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.visitor.CommandCollectorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.EvaluatableVisitor;
+import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.PredicateCollectorVisitor;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
+import org.teiid.query.validator.UpdateValidator.UpdateInfo;
+import org.teiid.query.validator.UpdateValidator.UpdateType;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
+import org.teiid.translator.SourceSystemFunctions;
+
+public class ValidationVisitor extends AbstractValidationVisitor {
+
+    private final class PositiveIntegerConstraint implements
+			Reference.Constraint {
+    	
+    	private String msgKey;
+    	
+    	public PositiveIntegerConstraint(String msgKey) {
+    		this.msgKey = msgKey;
+		}
+    	
+		@Override
+		public void validate(Object value) throws QueryValidatorException {
+			if (((Integer)value).intValue() < 0) {
+				throw new QueryValidatorException(QueryPlugin.Util.getString(msgKey)); 
+			}
+		}
+	}
+
+	// State during validation
+    private boolean isXML = false;	// only used for Query commands
+    
+    // update procedure being validated
+    private CreateUpdateProcedureCommand updateProc;
+    
+    public void setUpdateProc(CreateUpdateProcedureCommand updateProc) {
+		this.updateProc = updateProc;
+	}
+    
+    public void reset() {
+        super.reset();
+        this.isXML = false;
+    }
+
+    // ############### Visitor methods for language objects ##################
+    
+    public void visit(BatchedUpdateCommand obj) {
+        List commands = obj.getUpdateCommands();
+        Command command = null;
+        int type = 0;
+        for (int i = 0; i < commands.size(); i++) {
+            command = (Command)commands.get(i);
+            type = command.getType();
+            if (type != Command.TYPE_INSERT &&
+                type != Command.TYPE_UPDATE &&
+                type != Command.TYPE_DELETE &&
+                type != Command.TYPE_QUERY) { // SELECT INTO command
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_batch_command"),command); //$NON-NLS-1$
+            } else if (type == Command.TYPE_QUERY) {
+                Into into = ((Query)command).getInto();
+                if (into == null) {
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_batch_command"),command); //$NON-NLS-1$
+                }
+            }
+        }
+    }
+
+	public void visit(Delete obj) {
+    	validateNoXMLUpdates(obj);
+        GroupSymbol group = obj.getGroup();
+        validateGroupSupportsUpdate(group);
+    }
+
+    public void visit(GroupBy obj) {
+    	// Get list of all group by IDs
+        List groupBySymbols = obj.getSymbols();
+        validateSortable(groupBySymbols);
+		Iterator symbolIter = groupBySymbols.iterator();
+		while(symbolIter.hasNext()) {
+            SingleElementSymbol symbol = (SingleElementSymbol)symbolIter.next();
+            if(symbol instanceof ExpressionSymbol) {
+                ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
+                Expression expr = exprSymbol.getExpression();
+                if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr).isEmpty() || expr instanceof Constant || expr instanceof Reference) {
+                	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.groupby_subquery", expr), expr); //$NON-NLS-1$
+                }
+            }                
+		}
+    }
+    
+    @Override
+    public void visit(GroupSymbol obj) {
+    	try {
+			if (this.getMetadata().isScalarGroup(obj.getMetadataID())) {
+			    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_scalar_group_reference", obj),obj); //$NON-NLS-1$    		
+			}
+		} catch (QueryMetadataException e) {
+			handleException(e);
+		} catch (TeiidComponentException e) {
+			handleException(e);
+		}
+    }
+
+    public void visit(Insert obj) {
+        validateNoXMLUpdates(obj);
+        validateGroupSupportsUpdate(obj.getGroup());
+        validateInsert(obj);
+        
+        if (obj.getQueryExpression() != null) {
+        	validateMultisourceInsert(obj.getGroup());
+        }
+        if (obj.getUpdateInfo() != null && obj.getUpdateInfo().isInherentInsert()) {
+	        Collection<ElementSymbol> updateCols = obj.getVariables();
+	    	if (obj.getUpdateInfo().findUpdateMapping(updateCols, false) == null) {
+	    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", updateCols), obj); //$NON-NLS-1$
+	    	}
+        }
+    }
+
+    @Override
+    public void visit(OrderByItem obj) {
+    	validateSortable(obj.getSymbol());
+    }
+    
+    public void visit(Query obj) {
+        validateHasProjectedSymbols(obj);
+        if(isXMLCommand(obj)) {
+            //no temp table (Select Into) allowed
+            if(obj.getInto() != null){
+                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0069"),obj); //$NON-NLS-1$
+            }
+
+        	this.isXML = true;
+	        validateXMLQuery(obj);
+        } else {
+            validateAggregates(obj);
+
+            //if it is select with no from, should not have ScalarSubQuery
+            if(obj.getSelect() != null && obj.getFrom() == null){
+                if(!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(obj.getSelect()).isEmpty()){
+                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0067"),obj); //$NON-NLS-1$
+                }
+            }
+            
+            if (obj.getInto() != null) {
+                validateSelectInto(obj);
+            }                        
+        }
+    }
+	
+	public void visit(Select obj) {
+        validateSelectElements(obj);
+        if(obj.isDistinct()) {
+            validateSortable(obj.getProjectedSymbols());
+        }
+    }
+
+	public void visit(SubquerySetCriteria obj) {
+		validateSubquery(obj);
+		if (isNonComparable(obj.getExpression())) {
+			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj); //$NON-NLS-1$
+    	}
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+        
+		Collection projSymbols = obj.getCommand().getProjectedSymbols();
+
+		//Subcommand should have one projected symbol (query with one expression
+		//in SELECT or stored procedure execution that returns a single value).
+		if(projSymbols.size() != 1) {
+			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0011"),obj); //$NON-NLS-1$
+		}
+	}
+
+    public void visit(DependentSetCriteria obj) {
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    public void visit(SetQuery obj) {
+        validateHasProjectedSymbols(obj);
+        validateSetQuery(obj);
+    }
+    
+    public void visit(Update obj) {
+        validateNoXMLUpdates(obj);
+        validateGroupSupportsUpdate(obj.getGroup());
+        validateUpdate(obj);
+    }
+
+    public void visit(Into obj) {
+        GroupSymbol target = obj.getGroup();
+        validateGroupSupportsUpdate(target);
+        validateMultisourceInsert(obj.getGroup());
+    }
+
+	private void validateMultisourceInsert(GroupSymbol group) {
+		try {
+			if (getMetadata().isMultiSource(getMetadata().getModelID(group.getMetadataID()))) {
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.multisource_insert", group), group); //$NON-NLS-1$
+			}
+        } catch (QueryMetadataException e) {
+			handleException(e);
+		} catch (TeiidComponentException e) {
+			handleException(e);
+		}
+	}
+
+    public void visit(Function obj) {
+    	if(FunctionLibrary.LOOKUP.equalsIgnoreCase(obj.getName())) {
+    		try {
+				ResolverUtil.ResolvedLookup resolvedLookup = ResolverUtil.resolveLookup(obj, getMetadata());
+				if(ValidationVisitor.isNonComparable(resolvedLookup.getKeyElement())) {
+		            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_lookup_key", resolvedLookup.getKeyElement()), resolvedLookup.getKeyElement()); //$NON-NLS-1$            
+		        }
+			} catch (TeiidComponentException e) {
+				handleException(e, obj);
+			} catch (TeiidProcessingException e) {
+				handleException(e, obj);
+			}
+        } else if (obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)) {
+            if(!isXML) {
+                // can't use this pseudo-function in non-XML queries
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.The_context_function_cannot_be_used_in_a_non-XML_command"), obj); //$NON-NLS-1$
+            } else {
+                if (!(obj.getArg(0) instanceof ElementSymbol)){
+                    handleValidationError(QueryPlugin.Util.getString("ERR.015.004.0036"), obj);  //$NON-NLS-1$
+                }
+                
+                for (Iterator functions = FunctionCollectorVisitor.getFunctions(obj.getArg(1), false).iterator(); functions.hasNext();) {
+                    Function function = (Function)functions.next();
+                    
+                    if (function.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.CONTEXT)) {
+                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Context_function_nested"), obj); //$NON-NLS-1$
+                    }
+                }
+            }
+    	} else if (obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
+                   obj.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
+            if(isXML) {
+                if (!(obj.getArg(0) instanceof ElementSymbol)) {
+                    // Arg must be an element symbol
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.2"), obj); //$NON-NLS-1$
+                }
+            } else {
+                // can't use this pseudo-function in non-XML queries
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.The_rowlimit_function_cannot_be_used_in_a_non-XML_command"), obj); //$NON-NLS-1$
+            }
+        } else if(obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.XPATHVALUE)) {
+	        // Validate the xpath value is valid
+	        if(obj.getArgs()[1] instanceof Constant) {
+	            Constant xpathConst = (Constant) obj.getArgs()[1];
+                try {
+                    XMLSystemFunctions.validateXpath((String)xpathConst.getValue());
+                } catch(XPathException e) {
+                	handleValidationError(QueryPlugin.Util.getString("QueryResolver.invalid_xpath", e.getMessage()), obj); //$NON-NLS-1$
+                }
+	        }
+        } else if(obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.TO_BYTES) || obj.getFunctionDescriptor().getName().equalsIgnoreCase(SourceSystemFunctions.TO_CHARS)) {
+        	try {
+        		FunctionMethods.getCharset((String)((Constant)obj.getArg(1)).getValue());
+        	} catch (IllegalArgumentException e) {
+        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_encoding", obj.getArg(1)), obj); //$NON-NLS-1$
+        	}
+        }
+    }
+
+    // ############### Visitor methods for stored procedure lang objects ##################
+
+    public void visit(AssignmentStatement obj) {
+    	
+    	ElementSymbol variable = obj.getVariable();
+
+    	validateAssignment(obj, variable);
+    }
+    
+    @Override
+    public void visit(CommandStatement obj) {
+    	if (obj.getCommand() instanceof StoredProcedure) {
+    		StoredProcedure proc = (StoredProcedure)obj.getCommand();
+    		for (SPParameter param : proc.getParameters()) {
+				if ((param.getParameterType() == SPParameter.RETURN_VALUE 
+						|| param.getParameterType() == SPParameter.OUT) && param.getExpression() instanceof ElementSymbol) {
+					validateAssignment(obj, (ElementSymbol)param.getExpression());
+				}
+			}
+    	}
+    }
+
+	private void validateAssignment(LanguageObject obj,
+			ElementSymbol variable) {
+		String groupName = variable.getGroupSymbol().getCanonicalName();
+		//This will actually get detected by the resolver, since we inject an automatic declaration.
+    	if(groupName.equals(ProcedureReservedWords.CHANGING) || groupName.equals(ProcedureReservedWords.INPUTS)) {
+			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0012", ProcedureReservedWords.INPUTS, ProcedureReservedWords.CHANGING), obj); //$NON-NLS-1$
+		}
+	}
+    
+    @Override
+    public void visit(ScalarSubquery obj) {
+    	validateSubquery(obj);
+        Collection<SingleElementSymbol> projSymbols = obj.getCommand().getProjectedSymbols();
+
+        //Scalar subquery should have one projected symbol (query with one expression
+        //in SELECT or stored procedure execution that returns a single value).
+        if(projSymbols.size() != 1) {
+        	handleValidationError(QueryPlugin.Util.getString("ERR.015.008.0032", obj.getCommand()), obj.getCommand()); //$NON-NLS-1$
+        }
+    }
+
+    public void visit(CreateUpdateProcedureCommand obj) {
+        if(!obj.isUpdateProcedure()){
+        	//Every virtual procedure should have at least one query.
+        	if(CommandCollectorVisitor.getCommands(obj).isEmpty()){
+        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Procedure_should_have_query"), obj); //$NON-NLS-1$
+        	}
+        	
+            //check that the procedure does not contain references to itself
+            if (GroupCollectorVisitor.getGroups(obj,true).contains(obj.getVirtualGroup())) {
+            	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.Procedure_has_group_self_reference"),obj); //$NON-NLS-1$
+            }
+            
+            return;
+        }
+
+		// set the state to validate this procedure
+        this.updateProc = obj;
+        validateContainsRowsUpdatedVariable(obj);
+    }
+
+    public void visit(DeclareStatement obj) {
+    	ElementSymbol variable = obj.getVariable();
+    	String elementname = variable.getShortName().toUpperCase();
+
+		// varible cannot be one of the special variables
+    	if(elementname.equals(ProcedureReservedWords.ROWS_UPDATED)) {
+			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0017", new Object[] {ProcedureReservedWords.ROWS_UPDATED}), obj); //$NON-NLS-1$
+		} else if(elementname.equals(ProcedureReservedWords.ROWCOUNT)) {
+			handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0017", new Object[] {ProcedureReservedWords.ROWCOUNT}), obj); //$NON-NLS-1$
+		}
+        
+        validateAssignment(obj, obj.getVariable());
+    }
+
+    public void visit(IfStatement obj) {
+    	Criteria criteria = obj.getCondition();
+
+    	validatorCriteriaStatement(obj, criteria);
+    }
+    
+    public void visit(WhileStatement obj) {
+        Criteria criteria = obj.getCondition();
+
+        validatorCriteriaStatement(obj, criteria);
+    }
+
+    /** 
+     * @param obj
+     * @param criteria
+     */
+    private void validatorCriteriaStatement(LanguageObject obj,
+                                            Criteria criteria) {
+        Iterator criteriaIter = PredicateCollectorVisitor.getPredicates(criteria).iterator();
+    	while(criteriaIter.hasNext()) {
+    		Criteria predicateCriteria = (Criteria) criteriaIter.next();
+    		Iterator elmntIter = ElementCollectorVisitor.getElements(predicateCriteria, true).iterator();
+    		if(predicateCriteria instanceof TranslateCriteria) {
+				handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0019"), obj); //$NON-NLS-1$
+    		} else if(!(predicateCriteria instanceof HasCriteria)) {
+    			while(elmntIter.hasNext()) {
+    				ElementSymbol element = (ElementSymbol) elmntIter.next();
+    				if(!element.isExternalReference()) {
+						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0020"), obj); //$NON-NLS-1$
+    				}
+    			}
+    		}
+    	}
+    }
+
+    public void visit(TranslateCriteria obj) {
+
+		if(obj.hasTranslations()) {
+			Collection selectElmnts = null;
+			if(obj.getSelector().hasElements()) {
+				selectElmnts = obj.getSelector().getElements();
+			}
+			Iterator critIter = obj.getTranslations().iterator();
+			while(critIter.hasNext()) {
+				CompareCriteria transCrit = (CompareCriteria) critIter.next();
+				Collection leftElmnts = ElementCollectorVisitor.getElements(transCrit.getLeftExpression(), true);
+				// there is always only one element
+				ElementSymbol leftExpr = (ElementSymbol)leftElmnts.iterator().next();
+
+				if(selectElmnts != null && !selectElmnts.contains(leftExpr)) {
+					handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0021"), leftExpr); //$NON-NLS-1$
+				}
+			}
+		}
+
+		// additional validation checks
+		validateTranslateCriteria(obj);
+    }
+
+    public void visit(CompoundCriteria obj) {
+        // Validate use of 'rowlimit' or 'rowlimitexception' pseudo-function - each occurrence must be in a single
+        // CompareCriteria which is entirely it's own conjunct (not OR'ed with anything else)
+        if (isXML) {
+            // Collect all occurrances of rowlimit and rowlimitexception functions
+            List rowLimitFunctions = new ArrayList();
+            FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
+            PreOrderNavigator.doVisit(obj, visitor); 
+            visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
+            PreOrderNavigator.doVisit(obj, visitor);
+            final int functionCount = rowLimitFunctions.size();
+            if (functionCount > 0) {
+                
+                // Verify each use of rowlimit function is in a compare criteria that is 
+                // entirely it's own conjunct
+                Iterator conjunctIter = Criteria.separateCriteriaByAnd(obj).iterator();            
+                
+                int i = 0;
+                while (conjunctIter.hasNext() && i<functionCount ) {
+                    Object conjunct = conjunctIter.next();
+                    if (conjunct instanceof CompareCriteria) {
+                        CompareCriteria crit = (CompareCriteria)conjunct;
+                        if ((rowLimitFunctions.contains(crit.getLeftExpression()) && !rowLimitFunctions.contains(crit.getRightExpression())) || 
+                            (rowLimitFunctions.contains(crit.getRightExpression()) && !rowLimitFunctions.contains(crit.getLeftExpression()))) {
+                        	i++;
+                        }
+                    }
+                }
+                if (i<functionCount) {
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.3"), obj); //$NON-NLS-1$
+                }
+            }
+        }
+        
+    }
+
+    // ######################### Validation methods #########################
+
+	/**
+	 * A valid translated expression is not an <code>AggregateSymbol</code> and
+	 * does not include elements not present on the groups of the command using
+	 * the translated criteria.
+	 */
+    protected void validateTranslateCriteria(TranslateCriteria obj) {
+    	if(this.currentCommand == null) {
+    		return;
+    	}
+    	Map symbolMap = this.updateProc.getSymbolMap();
+		Command userCommand = this.updateProc.getUserCommand();
+    	// modeler validation
+    	if(userCommand == null) {
+    		return;
+    	}
+		Criteria userCrit = null;
+		int userCmdType = userCommand.getType();
+		switch(userCmdType) {
+			case Command.TYPE_DELETE:
+				userCrit = ((Delete)userCommand).getCriteria();
+				break;
+			case Command.TYPE_UPDATE:
+				userCrit = ((Update)userCommand).getCriteria();
+				break;
+			default:
+				break;
+		}
+		// nothing to validate if there is no user criteria
+		if(userCrit == null) {
+			return;
+		}
+
+    	Collection transleElmnts = ElementCollectorVisitor.getElements(obj, true);
+    	Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(this.currentCommand, true);
+		int selectType = obj.getSelector().getSelectorType();
+
+		for (Criteria predCrit : Criteria.separateCriteriaByAnd(userCrit)) {
+			if(selectType != CriteriaSelector.NO_TYPE) {
+				if(predCrit instanceof CompareCriteria) {
+					CompareCriteria ccCrit = (CompareCriteria) predCrit;
+					if(selectType != ccCrit.getOperator()) {
+						continue;
+					}
+				} else if(predCrit instanceof MatchCriteria) {
+					if(selectType != CriteriaSelector.LIKE) {
+						continue;
+					}
+				} else if(predCrit instanceof IsNullCriteria) {
+					if(selectType != CriteriaSelector.IS_NULL) {
+						continue;
+					}
+                } else if(predCrit instanceof SetCriteria) {
+                    if(selectType != CriteriaSelector.IN) {
+                    	continue;
+                    }
+                } else if(predCrit instanceof BetweenCriteria) {
+                    if(selectType != CriteriaSelector.BETWEEN) {
+                    	continue;
+                    }
+				}
+			}
+	    	Iterator critEmlntIter = ElementCollectorVisitor.getElements(predCrit, true).iterator();
+	    	// collect all elements elements on the criteria map to
+	    	while(critEmlntIter.hasNext()) {
+	    		ElementSymbol criteriaElement = (ElementSymbol) critEmlntIter.next();
+	    		if(transleElmnts.contains(criteriaElement)) {
+		    		Expression mappedExpr = (Expression) symbolMap.get(criteriaElement);
+		    		if(mappedExpr instanceof AggregateSymbol) {
+						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0022", criteriaElement), criteriaElement); //$NON-NLS-1$
+		    		}
+
+		    		if (!groups.containsAll(GroupsUsedByElementsVisitor.getGroups(mappedExpr))) {
+						handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0023", criteriaElement), criteriaElement); //$NON-NLS-1$
+			    	}
+				}
+	    	}
+		}
+    }
+
+    protected void validateSelectElements(Select obj) {
+    	if(isXML) {
+    		return;
+    	}
+
+        Collection elements = ElementCollectorVisitor.getElements(obj, true);
+        
+        Collection cantSelect = validateElementsSupport(
+            elements,
+            SupportConstants.Element.SELECT );
+
+		if(cantSelect != null) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0024", cantSelect), cantSelect); //$NON-NLS-1$
+		}
+    }
+
+    protected void validateHasProjectedSymbols(Command obj) {
+        if(obj.getProjectedSymbols().size() == 0) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0025"), obj); //$NON-NLS-1$
+        }
+    }
+
+    /**
+     * Validate that no elements of type OBJECT are in a SELECT DISTINCT or
+     * and ORDER BY.
+     * @param symbols List of SingleElementSymbol
+     */
+    protected void validateSortable(List symbols) {
+        Iterator iter = symbols.iterator();
+        while(iter.hasNext()) {
+            SingleElementSymbol symbol = (SingleElementSymbol) iter.next();
+            validateSortable(symbol);
+        }
+    }
+
+	private void validateSortable(SingleElementSymbol symbol) {
+		if (isNonComparable(symbol)) {
+		    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0026", symbol), symbol); //$NON-NLS-1$
+		}
+	}
+
+    public static boolean isNonComparable(Expression symbol) {
+        return DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(symbol.getType()));
+    }
+
+	/**
+	 * This method can be used to validate Update commands cannot be
+	 * executed against XML documents.
+	 */
+    protected void validateNoXMLUpdates(Command obj) {
+     	if(isXMLCommand(obj)) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0029"), obj); //$NON-NLS-1$
+     	}
+    }
+
+	/**
+	 * This method can be used to validate commands used in the stored
+	 * procedure languge cannot be executed against XML documents.
+	 */
+    protected void validateNoXMLProcedures(Command obj) {
+     	if(isXMLCommand(obj)) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0030"), obj); //$NON-NLS-1$
+     	}
+    }
+
+    private void validateXMLQuery(Query obj) {
+        if(obj.getGroupBy() != null) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0031"), obj); //$NON-NLS-1$
+        }
+        if(obj.getHaving() != null) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0032"), obj); //$NON-NLS-1$
+        }
+        if(obj.getLimit() != null) {
+            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.limit_not_valid_for_xml"), obj); //$NON-NLS-1$
+        }
+        if (obj.getOrderBy() != null) {
+        	OrderBy orderBy = obj.getOrderBy();
+        	for (OrderByItem item : orderBy.getOrderByItems()) {
+				if (!(item.getSymbol() instanceof ElementSymbol)) {
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.orderby_expression_xml"), obj); //$NON-NLS-1$
+				}
+			}
+         }
+    }
+    
+    protected void validateGroupSupportsUpdate(GroupSymbol groupSymbol) {
+    	try {
+	    	if(! getMetadata().groupSupports(groupSymbol.getMetadataID(), SupportConstants.Group.UPDATE)) {
+	            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0033", SQLStringVisitor.getSQLString(groupSymbol)), groupSymbol); //$NON-NLS-1$
+	        }
+	    } catch (TeiidComponentException e) {
+	        handleException(e, groupSymbol);
+	    }
+    }
+    
+    protected void validateSetQuery(SetQuery query) {
+        // Walk through sub queries - validate each one separately and
+        // also check the columns of each for comparability
+        for (QueryCommand subQuery : query.getQueryCommands()) {
+            if(isXMLCommand(subQuery)) {
+                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0034"), query); //$NON-NLS-1$
+            }
+            if (subQuery instanceof Query && ((Query)subQuery).getInto() != null) {
+            	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.union_insert"), query); //$NON-NLS-1$
+            }
+        }
+        
+        if (!query.isAll() || query.getOperation() == Operation.EXCEPT || query.getOperation() == Operation.INTERSECT) {
+            validateSortable(query.getProjectedSymbols());
+        }
+        
+        if (query.isAll() && (query.getOperation() == Operation.EXCEPT || query.getOperation() == Operation.INTERSECT)) {
+            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.excpet_intersect_all"), query); //$NON-NLS-1$
+        }
+    }
+
+    private void validateAggregates(Query query) {
+        Select select = query.getSelect();
+        GroupBy groupBy = query.getGroupBy();
+        Criteria having = query.getHaving();
+        if(groupBy != null || having != null || !AggregateSymbolCollectorVisitor.getAggregates(select, false).isEmpty()) {
+            Set<Expression> groupSymbols = null;
+            if(groupBy != null) {
+                groupSymbols = new HashSet<Expression>();
+                for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
+                    final SingleElementSymbol element = (SingleElementSymbol)iterator.next();
+                    groupSymbols.add(SymbolMap.getExpression(element));
+                }
+            }
+            
+            // Validate HAVING, if it exists
+            AggregateValidationVisitor visitor = new AggregateValidationVisitor(groupSymbols);
+            if(having != null) {
+                AggregateValidationVisitor.validate(having, visitor);
+            }
+            
+            // Validate SELECT
+            List projectedSymbols = select.getProjectedSymbols();
+            Iterator symbolIter = projectedSymbols.iterator();
+            while(symbolIter.hasNext()) {
+                SingleElementSymbol symbol = (SingleElementSymbol) symbolIter.next();
+                AggregateValidationVisitor.validate(symbol, visitor);                                            
+            }
+            
+            // Move items to this report
+            ValidatorReport report = visitor.getReport();
+            Collection items = report.getItems();
+            super.getReport().addItems(items);        
+        }
+    }
+    
+    protected void validateInsert(Insert obj) {
+        Collection vars = obj.getVariables();
+        Iterator varIter = vars.iterator();
+        Collection values = obj.getValues();
+        Iterator valIter = values.iterator();
+        GroupSymbol insertGroup = obj.getGroup();
+
+
+        try {
+            // Validate that all elements in variable list are updatable
+            Iterator elementIter = vars.iterator();
+            while(elementIter.hasNext()) {
+                ElementSymbol insertElem = (ElementSymbol) elementIter.next();
+                if(! getMetadata().elementSupports(insertElem.getMetadataID(), SupportConstants.Element.UPDATE)) {
+                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0052", insertElem), insertElem); //$NON-NLS-1$
+                }
+            }
+
+            // Get elements in the group.
+    		Collection insertElmnts = new LinkedList(ResolverUtil.resolveElementsInGroup(insertGroup, getMetadata()));
+
+    		// remove all elements specified in insert to get the ignored elements
+    		insertElmnts.removeAll(vars);
+
+			Iterator ignoreIter = insertElmnts.iterator();
+			while(ignoreIter.hasNext()) {
+	            ElementSymbol nextElmnt = (ElementSymbol) ignoreIter.next();
+				if(!getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.DEFAULT_VALUE) &&
+					!getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.NULL) &&
+                    !getMetadata().elementSupports(nextElmnt.getMetadataID(), SupportConstants.Element.AUTO_INCREMENT) &&
+                     !getMetadata().isMultiSourceElement(nextElmnt.getMetadataID())) {
+		                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0053", new Object[] {insertGroup, nextElmnt}), nextElmnt); //$NON-NLS-1$
+				}
+			}
+
+            //check to see if the elements support nulls in metadata,
+            // if any of the value present in the insert are null
+            while(valIter.hasNext() && varIter.hasNext()) {
+                Expression nextValue = (Expression) valIter.next();
+                ElementSymbol nextVar = (ElementSymbol) varIter.next();
+
+                if (EvaluatableVisitor.isFullyEvaluatable(nextValue, true)) {
+                    try {
+                        // If nextValue is an expression, evaluate it before checking for null
+                        Object evaluatedValue = Evaluator.evaluate(nextValue);
+                        if(evaluatedValue == null && ! getMetadata().elementSupports(nextVar.getMetadataID(), SupportConstants.Element.NULL)) {
+                            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0055", SQLStringVisitor.getSQLString(nextVar)), nextVar); //$NON-NLS-1$
+                        }
+                    } catch(ExpressionEvaluationException e) {
+                        //ignore for now, we don't have the context which could be the problem
+                    }
+                }
+            }// end of while
+        } catch(TeiidComponentException e) {
+            handleException(e, obj);
+        } 
+    }
+    
+    protected void validateSetClauseList(SetClauseList list) {
+    	Set<ElementSymbol> dups = new HashSet<ElementSymbol>();
+	    HashSet<ElementSymbol> changeVars = new HashSet<ElementSymbol>();
+	    for (SetClause clause : list.getClauses()) {
+	    	ElementSymbol elementID = clause.getSymbol();
+	        if (!changeVars.add(elementID)) {
+	        	dups.add(elementID);
+	        }
+		}
+	    if(!dups.isEmpty()) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0062", dups), dups); //$NON-NLS-1$
+	    }
+    }
+    
+    protected void validateUpdate(Update update) {
+        try {
+            UpdateInfo info = update.getUpdateInfo();
+
+            // list of elements that are being updated
+		    for (SetClause entry : update.getChangeList().getClauses()) {
+        	    ElementSymbol elementID = entry.getSymbol();
+
+                // Check that left side element is updatable
+                if(! getMetadata().elementSupports(elementID.getMetadataID(), SupportConstants.Element.UPDATE)) {
+                    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0059", elementID), elementID); //$NON-NLS-1$
+                }
+                
+                Object metadataID = elementID.getMetadataID();
+                if (getMetadata().isMultiSourceElement(metadataID)){
+                	handleValidationError(QueryPlugin.Util.getString("multi_source_update_not_allowed", elementID), elementID); //$NON-NLS-1$
+                }
+
+			    // Check that right expression is a constant and is non-null
+                Expression value = entry.getValue();
+                
+                if (EvaluatableVisitor.isFullyEvaluatable(value, true)) {
+                    try {
+                        value = new Constant(Evaluator.evaluate(value));
+                    } catch (ExpressionEvaluationException err) {
+                    }
+                }
+                
+                if(value instanceof Constant) {
+    			    // If value is null, check that element supports this as a nullable column
+                    if(((Constant)value).isNull() && ! getMetadata().elementSupports(elementID.getMetadataID(), SupportConstants.Element.NULL)) {
+                        handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0060", SQLStringVisitor.getSQLString(elementID)), elementID); //$NON-NLS-1$
+                    }// end of if
+                } else if (info != null && info.getUpdateType() == UpdateType.UPDATE_PROCEDURE && getMetadata().isVirtualGroup(update.getGroup().getMetadataID()) && !EvaluatableVisitor.willBecomeConstant(value)) {
+                    // If this is an update on a virtual group, verify that no elements are in the right side
+                    Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(value, false);
+                    for (ElementSymbol element : elements) {
+                        if(! element.isExternalReference()) {
+                            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0061", SQLStringVisitor.getSQLString(value)), value); //$NON-NLS-1$
+                        }
+                    }
+                } 
+		    }
+            if (info != null && info.isInherentUpdate()) {
+            	Set<ElementSymbol> updateCols = update.getChangeList().getClauseMap().keySet();
+            	if (!info.hasValidUpdateMapping(updateCols)) {
+            		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.nonUpdatable", updateCols), update); //$NON-NLS-1$
+            	}
+            }
+        } catch(TeiidException e) {
+            handleException(e, update);
+        }
+        
+        validateSetClauseList(update.getChangeList());
+    }
+    
+    /**
+     * Validates SELECT INTO queries.
+     * @param query
+     * @since 4.2
+     */
+    protected void validateSelectInto(Query query) {
+        List symbols = query.getSelect().getProjectedSymbols();
+        GroupSymbol intoGroup = query.getInto().getGroup();
+        validateInto(query, symbols, intoGroup);
+    }
+
+    private void validateInto(LanguageObject query,
+                                List symbols,
+                                GroupSymbol intoGroup) {
+        try {
+            List elementIDs = getMetadata().getElementIDsInGroupID(intoGroup.getMetadataID());
+            
+            // Check if there are too many elements in the SELECT clause
+            if (symbols.size() != elementIDs.size()) {
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.select_into_wrong_elements", new Object[] {new Integer(elementIDs.size()), new Integer(symbols.size())}), query); //$NON-NLS-1$
+                return;
+            }
+            
+            for (int symbolNum = 0; symbolNum < symbols.size(); symbolNum++) {
+                SingleElementSymbol symbol = (SingleElementSymbol)symbols.get(symbolNum);
+                Object elementID = elementIDs.get(symbolNum);
+                // Check if supports updates
+                if (!getMetadata().elementSupports(elementID, SupportConstants.Element.UPDATE)) {
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.element_updates_not_allowed", getMetadata().getFullName(elementID)), intoGroup); //$NON-NLS-1$
+                }
+
+                Class symbolType = symbol.getType();
+                String symbolTypeName = DataTypeManager.getDataTypeName(symbolType);
+                String targetTypeName = getMetadata().getElementType(elementID);
+                if (symbolTypeName.equals(targetTypeName)) {
+                    continue;
+                }
+                if (!DataTypeManager.isImplicitConversion(symbolTypeName, targetTypeName)) { // If there's no implicit conversion between the two
+                    Object[] params = new Object [] {symbolTypeName, targetTypeName, new Integer(symbolNum + 1), query};
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.select_into_no_implicit_conversion", params), query); //$NON-NLS-1$
+                    continue;
+                }
+            }
+        } catch (TeiidComponentException e) {
+            handleException(e, query);
+        } 
+    }
+    
+    /**
+     * Validate that the command assigns a value to the ROWS_UPDATED variable 
+     * @param obj
+     * @since 4.2
+     */
+    protected void validateContainsRowsUpdatedVariable(CreateUpdateProcedureCommand obj) {
+        final Collection assignVars = new ArrayList();
+       // Use visitor to find assignment statements
+        LanguageVisitor visitor = new LanguageVisitor() {
+            public void visit(AssignmentStatement obj) {
+                assignVars.add(obj.getVariable());
+            }
+        };
+        PreOrderNavigator.doVisit(obj, visitor);
+        boolean foundVar = false;
+        for(Iterator varIter = assignVars.iterator(); varIter.hasNext();) {
+            ElementSymbol variable = (ElementSymbol) varIter.next();
+            if(variable.getShortName().equalsIgnoreCase(ProcedureReservedWords.ROWS_UPDATED)) {
+                foundVar = true;
+                break;
+            }
+        }
+        if(!foundVar) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0016", ProcedureReservedWords.ROWS_UPDATED), obj); //$NON-NLS-1$
+        }
+    }
+    
+    private void validateRowLimitFunctionNotInInvalidCriteria(Criteria obj) {
+        // Collect all occurrances of rowlimit and rowlimitexception functions
+        List rowLimitFunctions = new ArrayList();
+        FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
+        PreOrderNavigator.doVisit(obj, visitor);      
+        visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
+        PreOrderNavigator.doVisit(obj, visitor); 
+        if (rowLimitFunctions.size() > 0) {
+            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.3"), obj); //$NON-NLS-1$
+        }
+    }
+    
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.BetweenCriteria)
+     * @since 4.3
+     */
+    public void visit(BetweenCriteria obj) {
+    	if (isNonComparable(obj.getExpression())) {
+    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
+    	}
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.IsNullCriteria)
+     * @since 4.3
+     */
+    public void visit(IsNullCriteria obj) {
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.MatchCriteria)
+     * @since 4.3
+     */
+    public void visit(MatchCriteria obj) {
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.NotCriteria)
+     * @since 4.3
+     */
+    public void visit(NotCriteria obj) {
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SetCriteria)
+     * @since 4.3
+     */
+    public void visit(SetCriteria obj) {
+    	if (isNonComparable(obj.getExpression())) {
+    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
+    	}
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.SubqueryCompareCriteria)
+     * @since 4.3
+     */
+    public void visit(SubqueryCompareCriteria obj) {
+    	validateSubquery(obj);
+    	if (isNonComparable(obj.getLeftExpression())) {
+    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
+    	}
+        this.validateRowLimitFunctionNotInInvalidCriteria(obj);
+    }
+    
+    public void visit(Option obj) {
+        List dep = obj.getDependentGroups();
+        List notDep = obj.getNotDependentGroups();
+        if (dep != null && !dep.isEmpty()
+            && notDep != null && !notDep.isEmpty()) {
+            String groupName = null;
+            String notDepGroup = null;
+            for (Iterator i = dep.iterator(); i.hasNext();) {
+                groupName = (String)i.next();
+                for (Iterator j = notDep.iterator(); j.hasNext();) {
+                    notDepGroup = (String)j.next();
+                    if (notDepGroup.equalsIgnoreCase(groupName)) {
+                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.group_in_both_dep", groupName), obj); //$NON-NLS-1$
+                        return;
+                    }
+                }
+            }
+        }
+    }
+    
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.DynamicCommand)
+     */
+    public void visit(DynamicCommand obj) {
+        if (obj.getIntoGroup() != null) {
+            validateInto(obj, obj.getAsColumns(), obj.getIntoGroup());
+        }
+        if (obj.getUsing() != null) {
+        	validateSetClauseList(obj.getUsing());
+        }
+    }
+    
+    @Override
+    public void visit(Create obj) {
+    	if (!obj.getPrimaryKey().isEmpty()) {
+    		validateSortable(obj.getPrimaryKey());
+    	}
+    }
+    
+    /** 
+     * @see org.teiid.query.sql.LanguageVisitor#visit(org.teiid.query.sql.lang.Drop)
+     */
+    public void visit(Drop drop) {
+        if (!drop.getTable().isTempTable()) {
+            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.drop_of_nontemptable", drop.getTable()), drop); //$NON-NLS-1$
+        }
+    }
+    
+    @Override
+    public void visit(CompareCriteria obj) {
+    	if (isNonComparable(obj.getLeftExpression())) {
+    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0027", obj),obj);    		 //$NON-NLS-1$
+    	}
+    	
+        // Validate use of 'rowlimit' and 'rowlimitexception' pseudo-functions - they cannot be nested within another
+        // function, and their operands must be a nonnegative integers
+
+        // Collect all occurrences of rowlimit function
+        List rowLimitFunctions = new ArrayList();
+        FunctionCollectorVisitor visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMIT);
+        PreOrderNavigator.doVisit(obj, visitor);   
+        visitor = new FunctionCollectorVisitor(rowLimitFunctions, FunctionLibrary.ROWLIMITEXCEPTION);
+        PreOrderNavigator.doVisit(obj, visitor);            
+        final int functionCount = rowLimitFunctions.size();
+        if (functionCount > 0) {
+            Function function = null;
+            Expression expr = null;
+            if (obj.getLeftExpression() instanceof Function) {
+                Function leftExpr = (Function)obj.getLeftExpression();
+                if (leftExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
+                    leftExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
+                    function = leftExpr;
+                    expr = obj.getRightExpression();
+                }
+            } 
+            if (function == null && obj.getRightExpression() instanceof Function) {
+                Function rightExpr = (Function)obj.getRightExpression();
+                if (rightExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMIT) ||
+                    rightExpr.getFunctionDescriptor().getName().equalsIgnoreCase(FunctionLibrary.ROWLIMITEXCEPTION)) {
+                    function = rightExpr;
+                    expr = obj.getLeftExpression();
+                }
+            }
+            if (function == null) {
+                // must be nested, which is invalid
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.0"), obj); //$NON-NLS-1$
+            } else {
+                if (expr instanceof Constant) {
+                    Constant constant = (Constant)expr;
+                    if (constant.getValue() instanceof Integer) {
+                        Integer integer = (Integer)constant.getValue();
+                        if (integer.intValue() < 0) {
+                            handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
+                        }
+                    } else {
+                        handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
+                    }
+                } else if (expr instanceof Reference) {
+                	((Reference)expr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.1")); //$NON-NLS-1$
+                } else {
+                    handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.1"), obj); //$NON-NLS-1$
+                }
+            }                 
+        }
+    }
+    
+    public void visit(Limit obj) {
+        Expression offsetExpr = obj.getOffset();
+        if (offsetExpr instanceof Constant) {
+            Integer offset = (Integer)((Constant)offsetExpr).getValue();
+            if (offset.intValue() < 0) {
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.badoffset2"), obj); //$NON-NLS-1$
+            }
+        } else if (offsetExpr instanceof Reference) {
+        	((Reference)offsetExpr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.badoffset2")); //$NON-NLS-1$
+        }
+        Expression limitExpr = obj.getRowLimit();
+        if (limitExpr instanceof Constant) {
+            Integer limit = (Integer)((Constant)limitExpr).getValue();
+            if (limit.intValue() < 0) {
+                handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.badlimit2"), obj); //$NON-NLS-1$
+            }
+        } else if (limitExpr instanceof Reference) {
+        	((Reference)limitExpr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.badlimit2")); //$NON-NLS-1$
+        }
+    }
+    
+    @Override
+    public void visit(XMLForest obj) {
+    	validateDerivedColumnNames(obj, obj.getArgs());
+    	for (DerivedColumn dc : obj.getArgs()) {
+			if (dc.getAlias() == null) {
+				continue;
+			}
+			validateQName(obj, dc.getAlias());
+			validateXMLContentTypes(dc.getExpression(), obj);
+		}
+    }
+    
+    @Override
+    public void visit(AggregateSymbol obj) {
+    	if (obj.getAggregateFunction() != Type.TEXTAGG) {
+    		return;
+    	}
+    	TextLine tl = (TextLine)obj.getExpression();
+    	if (tl.isIncludeHeader()) {
+    		validateDerivedColumnNames(obj, tl.getExpressions());
+    	}
+    	for (DerivedColumn dc : tl.getExpressions()) {
+			validateXMLContentTypes(dc.getExpression(), obj);
+		}
+    	validateTextOptions(obj, tl.getDelimiter(), tl.getQuote());
+    	if (tl.getEncoding() != null) {
+    		try {
+    			Charset.forName(tl.getEncoding());
+    		} catch (IllegalArgumentException e) {
+    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_encoding", tl.getEncoding()), obj); //$NON-NLS-1$
+    		}
+    	}
+    }
+    
+	private String[] validateQName(LanguageObject obj, String name) {
+		try {
+			return Name11Checker.getInstance().getQNameParts(name);
+		} catch (QNameException e) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_invalid_qname", name), obj); //$NON-NLS-1$
+		}
+		return null;
+	}
+
+	private void validateDerivedColumnNames(LanguageObject obj, List<DerivedColumn> cols) {
+		for (DerivedColumn dc : cols) {
+    		if (dc.getAlias() == null && !(dc.getExpression() instanceof ElementSymbol)) {
+    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.expression_requires_name"), obj); //$NON-NLS-1$
+        	} 
+		}
+	}
+    
+    @Override
+    public void visit(XMLAttributes obj) {
+    	validateDerivedColumnNames(obj, obj.getArgs());
+    	for (DerivedColumn dc : obj.getArgs()) {
+			if (dc.getAlias() == null) {
+				continue;
+			}
+			if ("xmlns".equals(dc.getAlias())) { //$NON-NLS-1$
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_attributes_reserved"), obj); //$NON-NLS-1$
+			}
+			String[] parts = validateQName(obj, dc.getAlias());
+			if (parts == null) {
+				continue;
+			}
+			if ("xmlns".equals(parts[0])) { //$NON-NLS-1$
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_attributes_reserved", dc.getAlias()), obj); //$NON-NLS-1$
+			}
+		}
+    }
+    
+    @Override
+    public void visit(XMLElement obj) {
+    	for (Expression expression : obj.getContent()) {
+    		validateXMLContentTypes(expression, obj);
+    	}
+    	validateQName(obj, obj.getName());
+    }
+    
+    public void validateXMLContentTypes(Expression expression, LanguageObject parent) {
+		if (expression.getType() == DataTypeManager.DefaultDataClasses.OBJECT || expression.getType() == DataTypeManager.DefaultDataClasses.BLOB) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_content_type", expression), parent); //$NON-NLS-1$
+		}
+    }
+    
+    @Override
+    public void visit(QueryString obj) {
+    	validateDerivedColumnNames(obj, obj.getArgs());
+    }
+    
+    @Override
+    public void visit(XMLTable obj) {
+    	List<DerivedColumn> passing = obj.getPassing();
+    	validatePassing(obj, obj.getXQueryExpression(), passing);
+    	boolean hasOrdinal = false;
+    	for (XMLColumn xc : obj.getColumns()) {
+			if (!xc.isOrdinal()) {
+				if (xc.getDefaultExpression() != null && !EvaluatableVisitor.isFullyEvaluatable(obj, false)) {
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_default", xc.getDefaultExpression()), obj); //$NON-NLS-1$
+				}
+				continue;
+			}
+			if (hasOrdinal) {
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.one_ordinal"), obj); //$NON-NLS-1$
+				break;
+			}
+			hasOrdinal = true;
+		}
+    }
+    
+    @Override
+    public void visit(XMLQuery obj) {
+    	validatePassing(obj, obj.getXQueryExpression(), obj.getPassing());
+    }
+
+	private void validatePassing(LanguageObject obj, SaxonXQueryExpression xqe, List<DerivedColumn> passing) {
+		boolean context = false;
+    	boolean hadError = false;
+    	HashSet<String> names = new HashSet<String>();
+    	for (DerivedColumn dc : passing) {
+    		if (dc.getAlias() == null) {
+    			Class<?> type = dc.getExpression().getType();
+    			if (type != DataTypeManager.DefaultDataClasses.XML) {
+    				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.context_item_type"), obj); //$NON-NLS-1$
+    			}
+    			if (context && !hadError) {
+    				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.passing_requires_name"), obj); //$NON-NLS-1$
+    				hadError = true;
+    			}
+    			context = true;
+        	} else { 
+        		validateXMLContentTypes(dc.getExpression(), obj);
+        		if (!names.add(dc.getAlias().toUpperCase())) {
+        			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.duplicate_passing", dc.getAlias()), obj); //$NON-NLS-1$
+        		}
+        	}
+		}
+    	if (xqe.usesContextItem() && !context) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.context_required"), obj); //$NON-NLS-1$    		
+    	}
+	}
+    
+    @Override
+    public void visit(XMLNamespaces obj) {
+    	boolean hasDefault = false;
+    	for (XMLNamespaces.NamespaceItem item : obj.getNamespaceItems()) {
+			if (item.getPrefix() != null) {
+				if (item.getPrefix().equals("xml") || item.getPrefix().equals("xmlns")) { //$NON-NLS-1$ //$NON-NLS-2$
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces_reserved"), obj); //$NON-NLS-1$
+				}
+				if (item.getUri().length() == 0) {
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces_null_uri"), obj); //$NON-NLS-1$
+				}
+				continue;
+			}
+			if (hasDefault) {
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xml_namespaces"), obj); //$NON-NLS-1$
+				break;
+			}
+			hasDefault = true;
+		}
+    }
+    
+    @Override
+    public void visit(TextTable obj) {
+    	boolean widthSet = false;
+    	Character delimiter = null;
+    	Character quote = null;
+    	for (TextTable.TextColumn column : obj.getColumns()) {
+			if (column.getWidth() != null) {
+				widthSet = true;
+				if (column.getWidth() < 0) {
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
+				}
+			} else if (widthSet) {
+    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_invalid_width"), obj); //$NON-NLS-1$
+			}
+		}
+    	if (widthSet) {
+    		if (obj.getDelimiter() != null || obj.getHeader() != null || obj.getQuote() != null) {
+        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_width"), obj); //$NON-NLS-1$
+    		}
+    	} else {
+        	if (obj.getHeader() != null && obj.getHeader() < 0) {
+	    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
+	    	}
+    		delimiter = obj.getDelimiter();
+    		quote = obj.getQuote();
+			validateTextOptions(obj, delimiter, quote);
+    	}
+    	if (obj.getSkip() != null && obj.getSkip() < 0) {
+    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
+    	}
+    }
+
+	private void validateTextOptions(LanguageObject obj, Character delimiter,
+			Character quote) {
+		if (quote == null) {
+			quote = '"';
+		} 
+		if (delimiter == null) {
+			delimiter = ',';
+		}
+		if (EquivalenceUtil.areEqual(quote, delimiter)) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_delimiter"), obj); //$NON-NLS-1$
+		}
+		if (EquivalenceUtil.areEqual(quote, '\n') 
+				|| EquivalenceUtil.areEqual(delimiter, '\n')) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_newline"), obj); //$NON-NLS-1$
+		}
+	}
+    
+    @Override
+    public void visit(XMLParse obj) {
+    	if (obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.STRING && 
+    			obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.CLOB &&
+    			obj.getExpression().getType() != DataTypeManager.DefaultDataClasses.BLOB) {
+    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.xmlparse_type"), obj); //$NON-NLS-1$
+    	}
+    }
+    
+    @Override
+    public void visit(ExistsCriteria obj) {
+    	validateSubquery(obj);
+    }
+    
+    @Override
+    public void visit(SubqueryFromClause obj) {
+    	validateSubquery(obj);
+    }
+    
+    @Override
+    public void visit(LoopStatement obj) {
+    	validateSubquery(obj);
+    }
+    
+    @Override
+    public void visit(WithQueryCommand obj) {
+    	validateSubquery(obj);
+    }
+
+    //TODO: it may be simplier to catch this in the parser
+    private void validateSubquery(SubqueryContainer subQuery) {
+    	if (subQuery.getCommand() instanceof Query && ((Query)subQuery.getCommand()).getInto() != null) {
+        	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.subquery_insert"), subQuery.getCommand()); //$NON-NLS-1$
+        }
+    }
+    
+}

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,299 +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.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.DataPolicy.PermissionType;
-import org.teiid.adminapi.impl.DataPolicyMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
-import org.teiid.api.exception.query.QueryParserException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.Symbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.validator.Validator;
-import org.teiid.query.validator.ValidatorFailure;
-import org.teiid.query.validator.ValidatorReport;
-
-
-public class TestAuthorizationValidationVisitor {
-
-    public static final String CONN_ID = "connID"; //$NON-NLS-1$
-
-    PermissionMetaData addResource(PermissionType type, boolean flag, String resource) {
-    	PermissionMetaData p = new PermissionMetaData();
-    	p.setResourceName(resource);
-    	switch(type) {
-    	case CREATE:
-    		p.setAllowCreate(flag);
-    		break;
-    	case DELETE:
-    		p.setAllowDelete(flag);
-    		break;
-    	case READ:
-    		p.setAllowRead(flag);
-    		break;
-    	case UPDATE:
-    		p.setAllowUpdate(flag);
-    		break;
-    	}
-    	return p;    	
-    }
-    PermissionMetaData addResource(PermissionType type, String resource) {
-    	return addResource(type, true, resource);
-    }
-
-    private DataPolicyMetadata exampleAuthSvc1() {
-    	DataPolicyMetadata svc = new DataPolicyMetadata();
-    	svc.setName("test"); //$NON-NLS-1$
-        
-        // pm1.g1
-        svc.addPermission(addResource(PermissionType.DELETE, "pm1.g1")); //$NON-NLS-1$
-        
-        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.READ, false, "pm1.g1.e2")); //$NON-NLS-1$
-
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e3")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e4")); //$NON-NLS-1$
-
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g1.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e3")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e4")); //$NON-NLS-1$
-        
-
-        // pm1.g2
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, false, "pm1.g2.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e3")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e4")); //$NON-NLS-1$
-
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g2.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e2")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e3")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e4")); //$NON-NLS-1$
-
-        // pm1.g4
-        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e2")); //$NON-NLS-1$
-
-        // pm1.sq2
-        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.sq1")); //$NON-NLS-1$
-        
-        return svc;
-    }
-    
-    //allow by default
-    private DataPolicyMetadata exampleAuthSvc2() {
-    	DataPolicyMetadata svc = new DataPolicyMetadata();
-    	svc.setName("test"); //$NON-NLS-1$
-    	
-    	svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
-    	svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g2")); //$NON-NLS-1$
-    	svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm2.g1")); //$NON-NLS-1$
-        
-    	// pm2.g2
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm2.g2.e1")); //$NON-NLS-1$
-        
-        // pm3.g2
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e2")); //$NON-NLS-1$
-        
-        return svc;
-    }
-
-    private void helpTest(DataPolicyMetadata policy, String sql, QueryMetadataInterface metadata, String[] expectedInaccesible, VDBMetaData vdb) throws QueryParserException, QueryResolverException, TeiidComponentException {
-        QueryParser parser = QueryParser.getQueryParser();
-        Command command = parser.parseCommand(sql);
-        QueryResolver.resolveCommand(command, metadata);
-        
-        vdb.addAttchment(QueryMetadataInterface.class, metadata);
-        
-        HashMap<String, DataPolicy> policies = new HashMap<String, DataPolicy>();
-        policies.put(policy.getName(), policy);
-        
-        AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(policies, "test"); //$NON-NLS-1$
-        ValidatorReport report = Validator.validate(command, metadata, visitor);
-        if(report.hasItems()) {
-            ValidatorFailure firstFailure = (ValidatorFailure) report.getItems().iterator().next();
-            
-            // strings
-            Set expected = new HashSet(Arrays.asList(expectedInaccesible));
-            // elements
-            Set actual = new HashSet();
-            Iterator iter = firstFailure.getInvalidObjects().iterator();
-            while(iter.hasNext()) {
-                Symbol symbol = (Symbol) iter.next();
-                actual.add(symbol.getName());
-            }
-            assertEquals(expected, actual);
-        } else if(expectedInaccesible.length > 0) {
-            fail("Expected inaccessible objects, but got none.");                 //$NON-NLS-1$
-        }
-    }
-    
-    @Test public void testEverythingAccessible() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-    
-    @Test public void testEverythingAccessible1() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-    
-    @Test public void testEverythingAccessible2() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e1', '1'), e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testInaccesibleElement() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT e2 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInaccesibleElement2() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e2', '1')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInaccesibleGroup() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g2", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2", "pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    @Test public void testInsert() throws Exception {        
-        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testInsertInaccessible() throws Exception {        
-        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g2 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testUpdate() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e2 = 5", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testUpdateCriteriaInaccessibleForRead() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testUpdateElementInaccessibleForUpdate() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e1 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testDelete() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testDeleteCriteriaInaccesibleForRead() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g2 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testDeleteInaccesibleGroup() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g3", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testProc() throws Exception {
-        helpTest(exampleAuthSvc1(), "EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$
-    }
-
-    @Test public void testProcInaccesible() throws Exception {
-        helpTest(exampleAuthSvc1(), "EXEC pm1.sq2('xyz')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.sq2"}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testSelectIntoEverythingAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testSelectIntoTarget_e1_NotAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm2.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm2.g2.e2","pm2.g2.e4","pm2.g2.e3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testSelectIntoTarget_e1e2_NotAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm3.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm3.g2.e4", "pm3.g2.e3"},FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testTempTableSelectInto() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-    
-    @Test public void testTempTableSelectInto1() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1, e2 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testTempTableInsert() throws Exception {
-        helpTest(exampleAuthSvc2(), "insert into #temp (e1, e2, e3, e4) values ('1', '2', '3', '4')", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-    }
-
-    @Test public void testXMLAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testXMLInAccessible() throws Exception {
-        helpTest(exampleAuthSvc1(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-	private void helpTestLookupVisibility(boolean visible) throws QueryParserException, QueryValidatorException, TeiidComponentException {
-		VDBMetaData vdb = FakeMetadataFactory.example1VDB();
-		vdb.getModel("pm1").setVisible(visible); //$NON-NLS-1$
-		AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(new HashMap<String, DataPolicy>(), "test"); //$NON-NLS-1$
-		String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
-		Command command = QueryParser.getQueryParser().parseCommand(sql);
-		Request.validateWithVisitor(mvvv, FakeMetadataFactory.example1Cached(), command);
-	}
-	
-	@Ignore("visibility no longer ristricts access")
-	@Test public void testLookupVisibility() throws Exception {
-		helpTestLookupVisibility(true);
-	}
-	
-	@Ignore("visibility no longer ristricts access")
-	@Test public void testLookupVisibilityFails() throws Exception {
-		try {
-			helpTestLookupVisibility(false);
-			fail("expected exception"); //$NON-NLS-1$
-		} catch (QueryValidatorException e) {
-			assertEquals("Group does not exist: pm1.g1", e.getMessage()); //$NON-NLS-1$
-		}
-	}
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java (from rev 2765, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,306 @@
+/*
+ * 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.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.DataPolicy.PermissionType;
+import org.teiid.adminapi.impl.DataPolicyMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
+import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.symbol.Symbol;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.validator.Validator;
+import org.teiid.query.validator.ValidatorFailure;
+import org.teiid.query.validator.ValidatorReport;
+
+ at SuppressWarnings("nls")
+public class TestAuthorizationValidationVisitor {
+
+    public static final String CONN_ID = "connID"; //$NON-NLS-1$
+
+    PermissionMetaData addResource(PermissionType type, boolean flag, String resource) {
+    	PermissionMetaData p = new PermissionMetaData();
+    	p.setResourceName(resource);
+    	switch(type) {
+    	case CREATE:
+    		p.setAllowCreate(flag);
+    		break;
+    	case DELETE:
+    		p.setAllowDelete(flag);
+    		break;
+    	case READ:
+    		p.setAllowRead(flag);
+    		break;
+    	case UPDATE:
+    		p.setAllowUpdate(flag);
+    		break;
+    	}
+    	return p;    	
+    }
+    PermissionMetaData addResource(PermissionType type, String resource) {
+    	return addResource(type, true, resource);
+    }
+
+    private DataPolicyMetadata exampleAuthSvc1() {
+    	DataPolicyMetadata svc = new DataPolicyMetadata();
+    	svc.setName("test"); //$NON-NLS-1$
+        
+        // pm1.g1
+        svc.addPermission(addResource(PermissionType.DELETE, "pm1.g1")); //$NON-NLS-1$
+        
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g1.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, false, "pm1.g1.e2")); //$NON-NLS-1$
+
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e3")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g1.e4")); //$NON-NLS-1$
+
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g1.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e3")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g1.e4")); //$NON-NLS-1$
+        
+
+        // pm1.g2
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, false, "pm1.g2.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e3")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2.e4")); //$NON-NLS-1$
+
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, false, "pm1.g2.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e2")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e3")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.UPDATE, "pm1.g2.e4")); //$NON-NLS-1$
+
+        // pm1.g4
+        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e2")); //$NON-NLS-1$
+
+        // pm1.sq2
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.sq1")); //$NON-NLS-1$
+        
+        return svc;
+    }
+    
+    //allow by default
+    private DataPolicyMetadata exampleAuthSvc2() {
+    	DataPolicyMetadata svc = new DataPolicyMetadata();
+    	svc.setName("test"); //$NON-NLS-1$
+    	
+    	svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm1.g2")); //$NON-NLS-1$
+    	svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.g2")); //$NON-NLS-1$
+    	svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm2.g1")); //$NON-NLS-1$
+        
+    	// pm2.g2
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm2.g2.e1")); //$NON-NLS-1$
+        
+        // pm3.g2
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e1")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e2")); //$NON-NLS-1$
+        svc.setAllowCreateTemporaryTables(false);
+        return svc;
+    }
+
+    private void helpTest(DataPolicyMetadata policy, String sql, QueryMetadataInterface metadata, String[] expectedInaccesible, VDBMetaData vdb) throws QueryParserException, QueryResolverException, TeiidComponentException {
+        QueryParser parser = QueryParser.getQueryParser();
+        Command command = parser.parseCommand(sql);
+        QueryResolver.resolveCommand(command, metadata);
+        
+        vdb.addAttchment(QueryMetadataInterface.class, metadata);
+        
+        HashMap<String, DataPolicy> policies = new HashMap<String, DataPolicy>();
+        policies.put(policy.getName(), policy);
+        
+        AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(policies, "test"); //$NON-NLS-1$
+        ValidatorReport report = Validator.validate(command, metadata, visitor);
+        if(report.hasItems()) {
+            ValidatorFailure firstFailure = (ValidatorFailure) report.getItems().iterator().next();
+            
+            // strings
+            Set expected = new HashSet(Arrays.asList(expectedInaccesible));
+            // elements
+            Set actual = new HashSet();
+            Iterator iter = firstFailure.getInvalidObjects().iterator();
+            while(iter.hasNext()) {
+                Symbol symbol = (Symbol) iter.next();
+                actual.add(symbol.getName());
+            }
+            assertEquals(expected, actual);
+        } else if(expectedInaccesible.length > 0) {
+            fail("Expected inaccessible objects, but got none.");                 //$NON-NLS-1$
+        }
+    }
+    
+    @Test public void testTemp() throws Exception {
+    	//allowed by default
+    	helpTest(exampleAuthSvc1(), "create local temporary table x (y string)", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    	//explicitly denied
+        helpTest(exampleAuthSvc2(), "create local temporary table x (y string)", FakeMetadataFactory.example1Cached(), new String[] {"x"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testEverythingAccessible() throws Exception {
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+    
+    @Test public void testEverythingAccessible1() throws Exception {
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+    
+    @Test public void testEverythingAccessible2() throws Exception {
+        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e1', '1'), e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testInaccesibleElement() throws Exception {        
+        helpTest(exampleAuthSvc1(), "SELECT e2 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInaccesibleElement2() throws Exception {        
+        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e2', '1')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInaccesibleGroup() throws Exception {        
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g2", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2", "pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    @Test public void testInsert() throws Exception {        
+        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testInsertInaccessible() throws Exception {        
+        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g2 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testUpdate() throws Exception {        
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e2 = 5", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testUpdateCriteriaInaccessibleForRead() throws Exception {        
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testUpdateElementInaccessibleForUpdate() throws Exception {        
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e1 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testDelete() throws Exception {        
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testDeleteCriteriaInaccesibleForRead() throws Exception {        
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g2 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testDeleteInaccesibleGroup() throws Exception {        
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g3", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testProc() throws Exception {
+        helpTest(exampleAuthSvc1(), "EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$
+    }
+
+    @Test public void testProcInaccesible() throws Exception {
+        helpTest(exampleAuthSvc1(), "EXEC pm1.sq2('xyz')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.sq2"}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testSelectIntoEverythingAccessible() throws Exception {
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testSelectIntoTarget_e1_NotAccessible() throws Exception {
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm2.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm2.g2.e2","pm2.g2.e4","pm2.g2.e3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testSelectIntoTarget_e1e2_NotAccessible() throws Exception {
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm3.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm3.g2.e4", "pm3.g2.e3"},FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testTempTableSelectInto() throws Exception {
+        helpTest(exampleAuthSvc1(), "SELECT e1 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+    
+    @Test public void testTempTableSelectInto1() throws Exception {
+        helpTest(exampleAuthSvc1(), "SELECT e1, e2 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testTempTableInsert() throws Exception {
+        helpTest(exampleAuthSvc2(), "insert into #temp (e1, e2, e3, e4) values ('1', '2', '3', '4')", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    }
+
+    @Test public void testXMLAccessible() throws Exception {
+        helpTest(exampleAuthSvc2(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testXMLInAccessible() throws Exception {
+        helpTest(exampleAuthSvc1(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+	private void helpTestLookupVisibility(boolean visible) throws QueryParserException, QueryValidatorException, TeiidComponentException {
+		VDBMetaData vdb = FakeMetadataFactory.example1VDB();
+		vdb.getModel("pm1").setVisible(visible); //$NON-NLS-1$
+		AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(new HashMap<String, DataPolicy>(), "test"); //$NON-NLS-1$
+		String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
+		Command command = QueryParser.getQueryParser().parseCommand(sql);
+		Request.validateWithVisitor(mvvv, FakeMetadataFactory.example1Cached(), command);
+	}
+	
+	@Ignore("visibility no longer ristricts access")
+	@Test public void testLookupVisibility() throws Exception {
+		helpTestLookupVisibility(true);
+	}
+	
+	@Ignore("visibility no longer ristricts access")
+	@Test public void testLookupVisibilityFails() throws Exception {
+		try {
+			helpTestLookupVisibility(false);
+			fail("expected exception"); //$NON-NLS-1$
+		} catch (QueryValidatorException e) {
+			assertEquals("Group does not exist: pm1.g1", e.getMessage()); //$NON-NLS-1$
+		}
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,145 +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 org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.client.RequestMessage;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.FakeTransactionService;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.RequestID;
-import org.teiid.dqp.service.AutoGenDataService;
-import org.teiid.dqp.service.FakeBufferService;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.TranslatorException;
-
-public class TestDataTierManager {
-    
-    private DQPCore rm;
-    private DataTierManagerImpl dtm;
-    private CommandContext context;
-    private AtomicRequestMessage request;
-    private Command command;
-    private DataTierTupleSource info;
-    private AutoGenDataService connectorManager = new AutoGenDataService();
-    private RequestWorkItem workItem;
-    
-    @Before public void setUp() {
-    	connectorManager = new AutoGenDataService();
-    }
-    
-    private static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws Exception {
-        Command command = QueryParser.getQueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, metadata);
-        return command;
-    }
-    
-    private void helpSetup(int nodeId) throws Exception {
-        helpSetup("SELECT * FROM BQT1.SmallA", nodeId); //$NON-NLS-1$
-    }
-    
-    private void helpSetup(String sql, int nodeId) throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.exampleBQTVDB());
-        
-        rm = new DQPCore();
-        rm.setTransactionService(new FakeTransactionService());
-        rm.setBufferService(new FakeBufferService());
-        rm.setCacheFactory(new DefaultCacheFactory());
-        rm.start(new DQPConfiguration());
-        FakeBufferService bs = new FakeBufferService();
-
-        ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
-        Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(connectorManager);
-        
-        
-        dtm = new DataTierManagerImpl(rm,
-                                  bs);
-        command = helpGetCommand(sql, metadata);
-        
-        RequestMessage original = new RequestMessage();
-        original.setExecutionId(1);
-        original.setPartialResults(true);
-        RequestID requestID = workContext.getRequestID(original.getExecutionId());
-        
-        context = new CommandContext();
-        context.setProcessorID(requestID);
-        context.setVdbName("test"); //$NON-NLS-1$
-        context.setVdbVersion(1);
-        context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bs.getBufferManager(), dtm, new DefaultCapabilitiesFinder(), null, metadata));
-        workItem = TestDQPCoreRequestHandling.addRequest(rm, original, requestID, null, workContext);
-        
-        request = new AtomicRequestMessage(original, workContext, nodeId);
-        request.setCommand(command);
-        request.setConnectorName("FakeConnectorID"); //$NON-NLS-1$
-        info = new DataTierTupleSource(request, workItem, connectorManager.registerRequest(request), dtm);
-    }
-    
-    @Test public void testDataTierTupleSource() throws Exception {
-    	helpSetup(1);
-    	for (int i = 0; i < 10;) {
-	    	try {
-	    		info.nextTuple();
-	    		i++;
-	    	} catch (BlockedException e) {
-	    		Thread.sleep(50);
-	    	}
-    	}
-        assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
-        assertNull(info.nextTuple());
-        info.closeSource();
-        assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
-    }
-    
-    @Test public void testPartialResults() throws Exception {
-    	helpSetup(1);
-    	info.exceptionOccurred(new TranslatorException(), true);
-    	assertNull(info.nextTuple());
-    }
-    
-    @Test public void testNoRowsException() throws Exception {
-    	this.connectorManager.setRows(0);
-    	helpSetup(3);
-    	while (true) {
-	    	try {
-	        	assertNull(info.nextTuple());
-	    		break;
-	    	} catch (BlockedException e) {
-	    		Thread.sleep(50);
-	    	}
-    	}
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java (from rev 2774, trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,152 @@
+/*
+ * 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 org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cache.DefaultCacheFactory;
+import org.teiid.client.RequestMessage;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.FakeTransactionService;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.AutoGenDataService;
+import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+public class TestDataTierManager {
+    
+    private DQPCore rm;
+    private DataTierManagerImpl dtm;
+    private CommandContext context;
+    private AtomicRequestMessage request;
+    private Command command;
+    private DataTierTupleSource info;
+    private AutoGenDataService connectorManager = new AutoGenDataService();
+    private RequestWorkItem workItem;
+    
+    @Before public void setUp() {
+    	connectorManager = new AutoGenDataService();
+    }
+    
+    private static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws Exception {
+        Command command = QueryParser.getQueryParser().parseCommand(sql);
+        QueryResolver.resolveCommand(command, metadata);
+        return command;
+    }
+    
+    private void helpSetup(int nodeId) throws Exception {
+        helpSetup("SELECT * FROM BQT1.SmallA", nodeId); //$NON-NLS-1$
+    }
+    
+    private void helpSetup(String sql, int nodeId) throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.exampleBQTVDB());
+        
+        rm = new DQPCore();
+        rm.setTransactionService(new FakeTransactionService());
+        rm.setBufferService(new FakeBufferService());
+        rm.setCacheFactory(new DefaultCacheFactory());
+        rm.start(new DQPConfiguration());
+        FakeBufferService bs = new FakeBufferService();
+
+        ConnectorManagerRepository repo = Mockito.mock(ConnectorManagerRepository.class);
+        Mockito.stub(repo.getConnectorManager(Mockito.anyString())).toReturn(connectorManager);
+        
+        
+        dtm = new DataTierManagerImpl(rm,
+                                  bs);
+        command = helpGetCommand(sql, metadata);
+        
+        RequestMessage original = new RequestMessage();
+        original.setExecutionId(1);
+        original.setPartialResults(true);
+        RequestID requestID = workContext.getRequestID(original.getExecutionId());
+        
+        context = new CommandContext();
+        context.setProcessorID(requestID);
+        context.setVdbName("test"); //$NON-NLS-1$
+        context.setVdbVersion(1);
+        context.setQueryProcessorFactory(new QueryProcessorFactoryImpl(bs.getBufferManager(), dtm, new DefaultCapabilitiesFinder(), null, metadata));
+        workItem = TestDQPCoreRequestHandling.addRequest(rm, original, requestID, null, workContext);
+        
+        request = new AtomicRequestMessage(original, workContext, nodeId);
+        request.setCommand(command);
+        request.setConnectorName("FakeConnectorID"); //$NON-NLS-1$
+        info = new DataTierTupleSource(request, workItem, connectorManager.registerRequest(request), dtm);
+    }
+    
+    @Test public void testDataTierTupleSource() throws Exception {
+    	helpSetup(1);
+    	for (int i = 0; i < 10;) {
+	    	try {
+	    		info.nextTuple();
+	    		i++;
+	    	} catch (BlockedException e) {
+	    		Thread.sleep(50);
+	    	}
+    	}
+        assertNotNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+        assertNull(info.nextTuple());
+        info.closeSource();
+        assertNull(workItem.getConnectorRequest(request.getAtomicRequestID()));
+    }
+    
+    @Test public void testPartialResults() throws Exception {
+    	helpSetup(1);
+    	connectorManager.throwExceptionOnExecute = true;
+    	for (int i = 0; i < 10; i++) {
+	    	try {
+	    		assertNull(info.nextTuple());
+	    		return;
+	    	} catch (BlockedException e) {
+	    		Thread.sleep(50);
+	    	}
+    	}
+    	fail();
+    }
+    
+    @Test public void testNoRowsException() throws Exception {
+    	this.connectorManager.setRows(0);
+    	helpSetup(3);
+    	while (true) {
+	    	try {
+	        	assertNull(info.nextTuple());
+	    		break;
+	    	} catch (BlockedException e) {
+	    		Thread.sleep(50);
+	    	}
+    	}
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,182 +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.service;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.datamgr.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.ConnectorWork;
-import org.teiid.dqp.internal.datamgr.ConnectorWorkItem;
-import org.teiid.dqp.message.AtomicRequestMessage;
-import org.teiid.dqp.message.AtomicResultsMessage;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.translator.DataNotAvailableException;
-import org.teiid.translator.TranslatorException;
-
-
-/**
- * This data service will automatically generate results when called with a query - basically
- * the same as the old loopback connector.
- */
-public class AutoGenDataService extends ConnectorManager{
-
-    // Number of rows that will be generated for each query
-    private int rows = 10;
-    private SourceCapabilities caps;
-	public boolean throwExceptionOnExecute;
-	public int dataNotAvailable = -1;
-    
-    public AutoGenDataService() {
-    	super("FakeConnector","FakeConnector"); //$NON-NLS-1$ //$NON-NLS-2$
-        caps = TestOptimizer.getTypicalCapabilities();
-    }
-
-    public void setRows(int rows) {
-        this.rows = rows;
-    }
-    
-    public int getRows() {
-        return this.rows;
-    }
-
-    @Override
-    public ConnectorWork registerRequest(AtomicRequestMessage message)
-    		throws TeiidComponentException {
-    	if (throwExceptionOnExecute) {
-    		throw new TeiidComponentException("Connector Exception"); //$NON-NLS-1$
-    	}
-        List projectedSymbols = (message.getCommand()).getProjectedSymbols();               
-        List[] results = createResults(projectedSymbols);
-                
-        final AtomicResultsMessage msg = ConnectorWorkItem.createResultsMessage(results, projectedSymbols);
-        msg.setFinalRow(rows);
-        return new ConnectorWork() {
-			
-			@Override
-			public AtomicResultsMessage more() throws TranslatorException {
-				throw new RuntimeException("Should not be called"); //$NON-NLS-1$
-			}
-			
-			@Override
-			public AtomicResultsMessage execute() throws TranslatorException {
-				if (dataNotAvailable > -1) {
-					int delay = dataNotAvailable;
-					dataNotAvailable = -1;
-					throw new DataNotAvailableException(delay);
-				}
-				return msg;
-			}
-			
-			@Override
-			public void close() {
-				
-			}
-			
-			@Override
-			public void cancel() {
-				
-			}
-			
-		};
-    }
-    
-    private List[] createResults(List symbols) {
-        List[] rows = new List[this.rows];
-
-        for(int i=0; i<this.rows; i++) {        
-            List row = new ArrayList();        
-            Iterator iter = symbols.iterator();
-            while(iter.hasNext()) {
-                SingleElementSymbol symbol = (SingleElementSymbol) iter.next();
-                Class type = symbol.getType();
-                row.add( getValue(type) );
-            }
-            rows[i] = row;
-        }   
-        
-        return rows;
-    }
-
-    private static final String STRING_VAL = "ABCDEFG"; //$NON-NLS-1$
-    private static final Integer INTEGER_VAL = new Integer(0);
-    private static final Long LONG_VAL = new Long(0);
-    private static final Float FLOAT_VAL = new Float(0.0);
-    private static final Short SHORT_VAL = new Short((short)0);
-    private static final Double DOUBLE_VAL = new Double(0.0);
-    private static final Character CHAR_VAL = new Character('c');
-    private static final Byte BYTE_VAL = new Byte((byte)0);
-    private static final Boolean BOOLEAN_VAL = Boolean.FALSE;
-    private static final BigInteger BIG_INTEGER_VAL = new BigInteger("0"); //$NON-NLS-1$
-    private static final BigDecimal BIG_DECIMAL_VAL = new BigDecimal("0"); //$NON-NLS-1$
-    private static final java.sql.Date SQL_DATE_VAL = new java.sql.Date(0);
-    private static final java.sql.Time TIME_VAL = new java.sql.Time(0);
-    private static final java.sql.Timestamp TIMESTAMP_VAL = new java.sql.Timestamp(0);
-    
-    private Object getValue(Class<?> type) {
-        if(type.equals(DataTypeManager.DefaultDataClasses.STRING)) {
-            return STRING_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
-            return INTEGER_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) { 
-            return SHORT_VAL;    
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
-            return LONG_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
-            return FLOAT_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
-            return DOUBLE_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.CHAR)) {
-            return CHAR_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
-            return BYTE_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
-            return BOOLEAN_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
-            return BIG_INTEGER_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
-            return BIG_DECIMAL_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.DATE)) {
-            return SQL_DATE_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.TIME)) {
-            return TIME_VAL;
-        } else if(type.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
-            return TIMESTAMP_VAL;
-        } else {
-            return null;
-        }
-    }
-
-    @Override
-	public SourceCapabilities getCapabilities(){
-        return caps;
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java (from rev 2774, trunk/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/dqp/service/AutoGenDataService.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,182 @@
+/*
+ * 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.service;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorWork;
+import org.teiid.dqp.internal.datamgr.ConnectorWorkItem;
+import org.teiid.dqp.message.AtomicRequestMessage;
+import org.teiid.dqp.message.AtomicResultsMessage;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ * This data service will automatically generate results when called with a query - basically
+ * the same as the old loopback connector.
+ */
+public class AutoGenDataService extends ConnectorManager{
+
+    // Number of rows that will be generated for each query
+    private int rows = 10;
+    private SourceCapabilities caps;
+	public boolean throwExceptionOnExecute;
+	public int dataNotAvailable = -1;
+    
+    public AutoGenDataService() {
+    	super("FakeConnector","FakeConnector"); //$NON-NLS-1$ //$NON-NLS-2$
+        caps = TestOptimizer.getTypicalCapabilities();
+    }
+
+    public void setRows(int rows) {
+        this.rows = rows;
+    }
+    
+    public int getRows() {
+        return this.rows;
+    }
+
+    @Override
+    public ConnectorWork registerRequest(AtomicRequestMessage message)
+    		throws TeiidComponentException {
+        List projectedSymbols = (message.getCommand()).getProjectedSymbols();               
+        List[] results = createResults(projectedSymbols);
+                
+        final AtomicResultsMessage msg = ConnectorWorkItem.createResultsMessage(results, projectedSymbols);
+        msg.setFinalRow(rows);
+        return new ConnectorWork() {
+			
+			@Override
+			public AtomicResultsMessage more() throws TranslatorException {
+				throw new RuntimeException("Should not be called"); //$NON-NLS-1$
+			}
+			
+			@Override
+			public AtomicResultsMessage execute() throws TranslatorException {
+				if (throwExceptionOnExecute) {
+		    		throw new TranslatorException("Connector Exception"); //$NON-NLS-1$
+		    	}
+				if (dataNotAvailable > -1) {
+					int delay = dataNotAvailable;
+					dataNotAvailable = -1;
+					throw new DataNotAvailableException(delay);
+				}
+				return msg;
+			}
+			
+			@Override
+			public void close() {
+				
+			}
+			
+			@Override
+			public void cancel() {
+				
+			}
+			
+		};
+    }
+    
+    private List[] createResults(List symbols) {
+        List[] rows = new List[this.rows];
+
+        for(int i=0; i<this.rows; i++) {        
+            List row = new ArrayList();        
+            Iterator iter = symbols.iterator();
+            while(iter.hasNext()) {
+                SingleElementSymbol symbol = (SingleElementSymbol) iter.next();
+                Class type = symbol.getType();
+                row.add( getValue(type) );
+            }
+            rows[i] = row;
+        }   
+        
+        return rows;
+    }
+
+    private static final String STRING_VAL = "ABCDEFG"; //$NON-NLS-1$
+    private static final Integer INTEGER_VAL = new Integer(0);
+    private static final Long LONG_VAL = new Long(0);
+    private static final Float FLOAT_VAL = new Float(0.0);
+    private static final Short SHORT_VAL = new Short((short)0);
+    private static final Double DOUBLE_VAL = new Double(0.0);
+    private static final Character CHAR_VAL = new Character('c');
+    private static final Byte BYTE_VAL = new Byte((byte)0);
+    private static final Boolean BOOLEAN_VAL = Boolean.FALSE;
+    private static final BigInteger BIG_INTEGER_VAL = new BigInteger("0"); //$NON-NLS-1$
+    private static final BigDecimal BIG_DECIMAL_VAL = new BigDecimal("0"); //$NON-NLS-1$
+    private static final java.sql.Date SQL_DATE_VAL = new java.sql.Date(0);
+    private static final java.sql.Time TIME_VAL = new java.sql.Time(0);
+    private static final java.sql.Timestamp TIMESTAMP_VAL = new java.sql.Timestamp(0);
+    
+    private Object getValue(Class<?> type) {
+        if(type.equals(DataTypeManager.DefaultDataClasses.STRING)) {
+            return STRING_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.INTEGER)) {
+            return INTEGER_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.SHORT)) { 
+            return SHORT_VAL;    
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.LONG)) {
+            return LONG_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.FLOAT)) {
+            return FLOAT_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.DOUBLE)) {
+            return DOUBLE_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.CHAR)) {
+            return CHAR_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.BYTE)) {
+            return BYTE_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.BOOLEAN)) {
+            return BOOLEAN_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_INTEGER)) {
+            return BIG_INTEGER_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
+            return BIG_DECIMAL_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.DATE)) {
+            return SQL_DATE_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.TIME)) {
+            return TIME_VAL;
+        } else if(type.equals(DataTypeManager.DefaultDataClasses.TIMESTAMP)) {
+            return TIMESTAMP_VAL;
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+	public SourceCapabilities getCapabilities(){
+        return caps;
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1410 +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.function;
-
-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.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.Properties;
-import java.util.TimeZone;
-
-import javax.sql.rowset.serial.SerialBlob;
-import javax.sql.rowset.serial.SerialClob;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.types.BlobType;
-import org.teiid.core.types.ClobType;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.types.NullType;
-import org.teiid.core.types.XMLType;
-import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
-import org.teiid.core.util.Base64;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.core.util.TimestampWithTimezone;
-import org.teiid.language.SQLConstants.NonReserved;
-import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.TimestampUtil;
-import org.teiid.query.util.CommandContext;
-import org.teiid.translator.SourceSystemFunctions;
-
-
- at SuppressWarnings("nls")
-public class TestFunctionLibrary {
-
-	// These are just used as shorthand convenience to make unit tests more readable below
-	private static final Class<String> T_STRING = DataTypeManager.DefaultDataClasses.STRING;
-	private static final Class<Integer> T_INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
-	private static final Class<BigInteger> T_BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
-	private static final Class<BigDecimal> T_BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;		
-    private static final Class<Long> T_LONG = DataTypeManager.DefaultDataClasses.LONG;
-	private static final Class<Float> T_FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
-    private static final Class<Double> T_DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
-	private static final Class<NullType> T_NULL = DataTypeManager.DefaultDataClasses.NULL;
-	private static final Class<Time> T_TIME = DataTypeManager.DefaultDataClasses.TIME;
-	private static final Class<Date> T_DATE = DataTypeManager.DefaultDataClasses.DATE;
-	private static final Class<Timestamp> T_TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
-	
-	private FunctionLibrary library = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree(new UDFSource(Collections.EMPTY_LIST)));
-
-	@Before public void setUp() { 
-		TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$ 
-	}
-	
-	@After public void tearDown() { 
-		TimestampWithTimezone.resetCalendar(null);
-	}
-	
-	// ################################## TEST HELPERS ################################
-	
-    private FunctionDescriptor helpCreateDescriptor(String name, Class[] types) { 
-        final String fname = name;
-        final Class[] ftypes = types;
-        return new FunctionDescriptor() {
-            public String getName() {
-                return fname;
-            }
-            public PushDown getPushdown() {
-                return PushDown.CAN_PUSHDOWN;
-            }
-            public Class[] getTypes() { 
-                return ftypes;
-            }
-            public Class getReturnType() { 
-                return null;
-            }
-            
-            public String toString() {
-                StringBuffer str = new StringBuffer(fname);
-                str.append("("); //$NON-NLS-1$
-                for(int i=0; i<ftypes.length; i++) {
-                    if(ftypes[i] != null) { 
-                        str.append(ftypes[i].getName());
-                    } else {
-                        str.append("null"); //$NON-NLS-1$
-                    }       
-                    if(i<(ftypes.length-1)) {
-                        str.append(", "); //$NON-NLS-1$
-                    }
-                }
-                return str.toString();
-            }
-            public boolean requiresContext() {
-                return false;
-            }
-            public boolean isNullDependent() {
-                return true;
-            }
-            
-        };
-    }
-    
-	private void helpFindFunction(String fname, Class[] types, FunctionDescriptor expected) {
-		FunctionDescriptor actual =  library.findFunction(fname, types);
-	
-        assertEquals("Function names do not match: ", expected.getName().toLowerCase(), actual.getName().toLowerCase());             //$NON-NLS-1$
-        assertEquals("Arg lengths do not match: ", expected.getTypes().length, actual.getTypes().length); //$NON-NLS-1$
-	}
-
-	private void helpFindFunctionFail(String fname, Class[] types) {
-		FunctionDescriptor actual =  library.findFunction(fname, types);
-		assertNull("Function was found but should not have been: " + actual, actual); //$NON-NLS-1$
-	}
-    
-	private void helpFindConversions(String fname, Class[] types, FunctionDescriptor[] expected) {
-
-		FunctionDescriptor[] actual = library.determineNecessaryConversions(fname, null, types, false);
-		
-		if(expected == null) {
-			if(actual != null) { 
-				fail("Expected to find no conversion for " + fname + Arrays.asList(types) + " but found: " + Arrays.asList(actual)); //$NON-NLS-1$ //$NON-NLS-2$
-			}	
-		} else {
-			if(actual == null) { 
-				fail("Expected to find conversion for " + fname + Arrays.asList(types) + " but found none"); //$NON-NLS-1$ //$NON-NLS-2$
-			} else {
-				// Compare returned descriptors with expected descriptor
-				for(int i=0; i<expected.length; i++) { 
-                    if(expected[i] == null) { 
-                        if(actual[i] != null) { 
-                            fail("Expected no conversion at index " + i + ", but found: " + actual[i]); //$NON-NLS-1$ //$NON-NLS-2$
-                        }
-                    } else {
-                        if(actual[i] == null) { 
-                            fail("Expected conversion at index " + i + ", but found none.");                             //$NON-NLS-1$ //$NON-NLS-2$
-                        } else {
-                            assertEquals("Expected conversion function names do not match: ", expected[i].getName(), actual[i].getName());             //$NON-NLS-1$
-                            assertEquals("Expected conversion arg lengths do not match: ", expected[i].getTypes().length, actual[i].getTypes().length);                         //$NON-NLS-1$
-                        }        
-                    }        
-				}			
-			}			
-		}
-	}	
-	
-	private void helpFindForm(String fname, int numArgs) {
-		FunctionForm form = library.findFunctionForm(fname, numArgs);
-        assertNotNull("Failed to find function '" + fname + "' with " + numArgs + " args", form); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        assertEquals("Function names do not match: ", fname.toUpperCase(), form.getName().toUpperCase());             //$NON-NLS-1$
-        assertEquals("Arg lengths do not match: ", numArgs, form.getArgNames().size()); //$NON-NLS-1$
-	}
-
-	private void helpInvokeMethod(String fname, Object[] inputs, Object expectedOutput) {
-        try {
-            helpInvokeMethod(fname, null, inputs, null, expectedOutput);
-        } catch (Exception err) {
-            throw new RuntimeException(err);
-        } 
-	}
-    
-    private void helpInvokeMethod(String fname, Class[] types, Object[] inputs, CommandContext context, Object expectedOutput) throws FunctionExecutionException {
-    	Object actualOutput = helpInvokeMethod(fname, types, inputs, context);
-        assertEquals("Actual function output not equal to expected: ", expectedOutput, actualOutput); //$NON-NLS-1$
-    }
-
-	private Object helpInvokeMethod(String fname, Class[] types,
-			Object[] inputs, CommandContext context)
-			throws FunctionExecutionException {
-		if (types == null) {
-            // Build type signature
-            types = new Class[inputs.length];
-            for(int i=0; i<inputs.length; i++) { 
-                types[i] = DataTypeManager.determineDataTypeClass(inputs[i]);   
-            }        
-    	}
-    	if (context == null) {
-    		context = new CommandContext();
-    	}
-        Object actualOutput = null;
-        // Find function descriptor
-        FunctionDescriptor descriptor = library.findFunction(fname, types);         
-        if (descriptor.requiresContext()) {
-            // Invoke function with inputs
-            Object[] in = new Object[inputs.length+1];
-            in[0] = context;
-            for (int i = 0; i < inputs.length; i++) {
-                in[i+1] = inputs[i];
-            }
-            actualOutput = descriptor.invokeFunction(in);
-        }
-        else {
-            // Invoke function with inputs
-            actualOutput = descriptor.invokeFunction(inputs);                
-        }
-		return actualOutput;
-	}
-    	    
-	private void helpInvokeMethodFail(String fname, Object[] inputs) {
-		   helpInvokeMethodFail(fname, null, inputs);
-	}	
-    	
-    private void helpInvokeMethodFail(String fname, Class<?> types[], Object[] inputs) {
-    	try {
-            helpInvokeMethod(fname, types, inputs, null);
-            fail("expected exception"); //$NON-NLS-1$
-        } catch (FunctionExecutionException err) {
-        }    
-    }    
-	// ################################## ACTUAL TESTS ################################
-	
-	@Test public void testFindFunction1() { 
-		helpFindFunction("convert", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
-            helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }) );
-	}
-	
-	@Test public void testFindFunction2() { 
-		helpFindFunction("cast", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
-            helpCreateDescriptor(FunctionLibrary.CAST, new Class[] { T_INTEGER, T_STRING }) );
-	}
-	
-    @Test public void testFindFunction3() {
-        helpFindFunction("curdate", new Class[0], //$NON-NLS-1$
-        	helpCreateDescriptor("curdate", new Class[0])); //$NON-NLS-1$
-    }
-   
-    @Test public void testFindFunction4() {
-        helpFindFunctionFail("curdate", new Class[] { T_INTEGER }); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindFunction5() {
-        helpFindFunction("+", new Class[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-        	helpCreateDescriptor("+", new Class[] { T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindFunction6() {
-        helpFindFunctionFail("+", new Class[] {T_INTEGER, T_FLOAT}); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindFunction7() {
-        helpFindFunctionFail("+", new Class[] {T_INTEGER, T_FLOAT, T_INTEGER}); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindFunction8() {
-        helpFindFunctionFail("+", new Class[] {T_INTEGER}); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindFunction9() {        
-		helpFindFunctionFail("+", new Class[] {T_INTEGER, T_NULL });     //$NON-NLS-1$
-    }
-
-    @Test public void testFindFunction10() {
-        helpFindFunction("substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-            helpCreateDescriptor("substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
-    }
-
-    @Test public void testFindFunction11() {
-        helpFindFunction("substring", new Class[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
-            helpCreateDescriptor("substring", new Class[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
-    }
-
-    @Test public void testFindFunction12() {
-        helpFindFunction("context", new Class[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
-            helpCreateDescriptor("context", new Class[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
-    }
-
-    @Test public void testFindFunction12a() {
-        helpFindFunction("rowlimit", new Class[] { T_STRING }, //$NON-NLS-1$
-            helpCreateDescriptor("rowlimit", new Class[] { T_STRING }) ); //$NON-NLS-1$
-    }
-
-    @Test public void testFindFunction12b() {
-        helpFindFunction("rowlimitexception", new Class[] { T_STRING }, //$NON-NLS-1$
-            helpCreateDescriptor("rowlimitexception", new Class[] { T_STRING }) ); //$NON-NLS-1$
-    }
-    
-	@Test public void testFind0ArgConversion1() { 	
-		helpFindConversions(
-			"curdate", new Class[] {}, //$NON-NLS-1$
-			new FunctionDescriptor[0] );
-	}
-
-	@Test public void testFind0ArgConversion2() { 	
-		helpFindConversions(
-			"curdate", new Class[] { T_INTEGER }, //$NON-NLS-1$
-			null );
-	}
-
-	@Test public void testFind1ArgConversion1() { 	
-		helpFindConversions(
-			"length", new Class[] { T_STRING }, //$NON-NLS-1$
-			new FunctionDescriptor[1] );
-	}
-
-	@Test public void testFind1ArgConversion2() { 	
-		helpFindConversions(
-			"length", new Class[] { T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING })
-			} );
-	}
-
-	@Test public void testFind1ArgConversion3() { 	
-		helpFindConversions(
-			"length", new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, T_STRING })
-			} );
-	}
-
-	@Test public void testFind2ArgConversion1() { 	
-		helpFindConversions(
-			"+", new Class[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[2] );
-	}
-
-	@Test public void testFind2ArgConversion2() { 	
-		helpFindConversions(
-			"+", new Class[] { T_INTEGER, T_FLOAT }, //$NON-NLS-1$
-			new FunctionDescriptor[] { 
-                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }), 
-                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_FLOAT, T_STRING }) } );
-	}
-
-	@Test public void testFind2ArgConversion3() { 	
-		helpFindConversions(
-			"+", new Class[] { T_FLOAT, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] { 
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_FLOAT, T_STRING }), 
-                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }) } );
-	}
-
-	@Test public void testFind2ArgConversion4() { 	
-		helpFindConversions(
-			"+", new Class[] { T_STRING, T_FLOAT }, //$NON-NLS-1$
-			null );
-	}
-
-	@Test public void testFind2ArgConversion5() { 	
-		helpFindConversions(
-			"+", new Class[] { T_NULL, T_NULL }, //$NON-NLS-1$
-			new FunctionDescriptor[] { 
-			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }), 
-                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) } );
-	}
-
-	@Test public void testFind2ArgConversion6() { 	
-		helpFindConversions(
-			"+", new Class[] { T_NULL, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] { 
-			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }), 
-				null } );
-	}
-
-	@Test public void testFind2ArgConversion7() { 	
-		helpFindConversions(
-			"+", new Class[] { T_INTEGER, T_NULL }, //$NON-NLS-1$
-			new FunctionDescriptor[] { 
-			    null, 
-			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) } );
-	}
-
-	@Test public void testFind3ArgConversion1() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[3] );
-	}
-
-	@Test public void testFind3ArgConversion2() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_INTEGER, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }),
-				null,
-				null    
-			} );
-	}
-
-	@Test public void testFind3ArgConversion3() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_INTEGER, T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }),
-				null,
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
-			} );
-	}
-
-	@Test public void testFind3ArgConversion4() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_STRING, T_INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
-			null );
-	}
-
-	@Test public void testFind3ArgConversion5() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_STRING, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-			    null,
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
-			} );
-	}
-
-	@Test public void testFind3ArgConversion6() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.INTEGER, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
-			} );
-	}
-
-	@Test public void testFind3ArgConversion7() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_NULL, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
-				null,
-				null }
-			);
-	}
-
-	@Test public void testFind3ArgConversion8() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_NULL, T_NULL, T_INTEGER }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
-				null }
-			);
-	}
-
-	@Test public void testFind3ArgConversion9() { 	
-		helpFindConversions(
-			"substring", new Class[] { T_NULL, T_NULL, T_NULL }, //$NON-NLS-1$
-			new FunctionDescriptor[] {
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
-				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) }
-			);
-	}
-
-    // Walk through all functions by metadata 
-    @Test public void testEnumerateForms() {
-        Collection categories = library.getFunctionCategories();
-        Iterator catIter = categories.iterator();
-        while(catIter.hasNext()) { 
-            String category = (String) catIter.next();
-            //System.out.println("Category: " + category);
-            
-            Collection functions = library.getFunctionForms(category);
-            Iterator functionIter = functions.iterator();
-            while(functionIter.hasNext()) { 
-                FunctionForm form = (FunctionForm) functionIter.next();
-                //System.out.println("\tFunction: " + form.getDisplayString());                
-                
-                // Lookup this form
-                helpFindForm(form.getName(), form.getArgNames().size());
-            }            
-        }        
-    }
-
-	@Test public void testFindForm1() { 
-		helpFindForm("convert", 2); //$NON-NLS-1$
-	}
- 
-	@Test public void testFindForm2() { 
-		helpFindForm("locate", 2); //$NON-NLS-1$
-	}
-    
-	@Test public void testFindForm3() { 
-		helpFindForm("locate", 3); //$NON-NLS-1$
-	}
-
-    @Test public void testFindForm4() { 
-        helpFindForm("substring", 2); //$NON-NLS-1$
-    }
-    
-    @Test public void testFindForm5() { 
-        helpFindForm("substring", 3); //$NON-NLS-1$
-    }
- 
-	@Test public void testFindForm6() { 
-		helpFindForm("now", 0); //$NON-NLS-1$
-	}
-    
-    @Test public void testInvokePlus1() { 
-    	helpInvokeMethod("+", new Object[] { new Integer(3), new Integer(2) }, new Integer(5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokePlus2() {
-        helpInvokeMethod("+", new Object[] { new Long(3), new Long(2) }, new Long(5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokePlus3() {
-        helpInvokeMethod("+", new Object[] { new Float(3), new Float(2) }, new Float(5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokePlus4() {
-        helpInvokeMethod("+", new Object[] { new Double(3), new Double(2) }, new Double(5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokePlus5() {
-        helpInvokeMethod("+", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokePlus6() {
-        helpInvokeMethod("+", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeMinus1() {
-        helpInvokeMethod("-", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMinus2() {
-        helpInvokeMethod("-", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMinus3() {
-        helpInvokeMethod("-", new Object[] { new Float(3), new Float(2) }, new Float(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMinus4() {
-        helpInvokeMethod("-", new Object[] { new Double(3), new Double(2) }, new Double(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMinus5() {
-        helpInvokeMethod("-", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeMinus6() {
-        helpInvokeMethod("-", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeMultiply1() {
-        helpInvokeMethod("*", new Object[] { new Integer(3), new Integer(2) }, new Integer(6)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMultiply2() {
-        helpInvokeMethod("*", new Object[] { new Long(3), new Long(2) }, new Long(6)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMultiply3() {
-        helpInvokeMethod("*", new Object[] { new Float(3), new Float(2) }, new Float(6)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMultiply4() {
-        helpInvokeMethod("*", new Object[] { new Double(3), new Double(2) }, new Double(6)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeMultiply5() {
-        helpInvokeMethod("*", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeMultiply6() {
-        helpInvokeMethod("*", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeDivide1() {
-        helpInvokeMethod("/", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeDivide2() {
-        helpInvokeMethod("/", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeDivide3() {
-        helpInvokeMethod("/", new Object[] { new Float(3), new Float(2) }, new Float(1.5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeDivide4() {
-        helpInvokeMethod("/", new Object[] { new Double(3), new Double(2) }, new Double(1.5)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeDivide5() {
-        helpInvokeMethod("/", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    // one digit precision
-    @Test public void testInvokeDivide6() {
-        helpInvokeMethod("/", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1.5"));   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-    
-    @Test public void testInvokeDivide7() throws Exception {
-        helpInvokeMethodFail("/", new Object[] { new Float("3"), new Float("0") });   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-    
-    @Test public void testInvokeDivideMod() {
-        helpInvokeMethod("mod", new Object[] { new BigDecimal("3.1"), new BigDecimal("2") }, new BigDecimal("1.1"));   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeAbs1() {
-        helpInvokeMethod("abs", new Object[] { new Integer(-3) }, new Integer(3)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeAbs2() {
-        helpInvokeMethod("abs", new Object[] { new Long(-3) }, new Long(3)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeAbs3() {
-        helpInvokeMethod("abs", new Object[] { new Float(-3) }, new Float(3)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeAbs4() {
-        helpInvokeMethod("abs", new Object[] { new Double(-3) }, new Double(3)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeAbs5() {
-        helpInvokeMethod("abs", new Object[] { new BigInteger("-3") }, new BigInteger("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    @Test public void testInvokeAbs6() {
-        helpInvokeMethod("abs", new Object[] { new BigDecimal("-3") }, new BigDecimal("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-	@Test public void testInvokeAcos() {
-		helpInvokeMethod("acos", new Object[] { new Double(0.05) }, new Double(1.5207754699891267)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeAsin() {
-		helpInvokeMethod("asin", new Object[] { new Double(0.05) }, new Double(0.050020856805770016)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeAtan() {
-		helpInvokeMethod("atan", new Object[] { new Double(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeAtan2() {
-		helpInvokeMethod("atan2", new Object[] { new Double(0.05), new Double(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeAtanBigDecimal() {
-		helpInvokeMethod("atan", new Object[] { new BigDecimal(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeAtan2BigDecimal() {
-		helpInvokeMethod("atan2", new Object[] { new BigDecimal(0.05), new BigDecimal(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeCos() {
-		helpInvokeMethod("cos", new Object[] { new Double(1.57) }, new Double(7.963267107332633E-4)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeCot() {
-		helpInvokeMethod("cot", new Object[] { new Double(1.57) }, new Double(7.963269632231926E-4)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeDegrees() {
-		helpInvokeMethod("degrees", new Object[] { new Double(1.57) }, new Double(89.95437383553926)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokePI() {
-		helpInvokeMethod("pi", new Object[] { }, new Double(3.141592653589793)); //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeRadians() {
-		helpInvokeMethod("radians", new Object[] { new Double(89.95437383553926) }, new Double(1.57)); //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeSin() {
-		helpInvokeMethod("sin", new Object[] { new Double(1.57) }, new Double(0.9999996829318346)); //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeTan() {
-		helpInvokeMethod("tan", new Object[] { new Double(0.785) }, new Double(0.9992039901050427)); //$NON-NLS-1$
-	}
-							
-    @Test public void testInvokeAscii() {
-        helpInvokeMethod("ascii", new Object[] { " " }, new Integer(32)); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvokeChr() {
-        helpInvokeMethod("chr", new Object[] { new Integer(32) }, new Character(' ')); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvokeNvl() {
-        helpInvokeMethod("nvl", new Object[] { new Integer(5), new Integer(10) }, new Integer(5) ); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeConcatOperator() {
-        helpInvokeMethod("||", new Object[] { "a", "b" }, "ab" );         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-
-    @Test public void testInvokeInitcap() {
-        helpInvokeMethod("initcap", new Object[] { "my test\ndata" }, "My Test\nData" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    @Test public void testInvokeLpad1() {
-        helpInvokeMethod("lpad", new Object[] { "x", new Integer(3) }, "  x" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    @Test public void testInvokeLpad2() {
-        helpInvokeMethod("lpad", new Object[] { "x", new Integer(3), "y" }, "yyx" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-    
-    @Test public void testInvokeRpad1() {
-        helpInvokeMethod("rpad", new Object[] { "x", new Integer(3) }, "x  " ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    @Test public void testInvokeRpad2() {
-        helpInvokeMethod("rpad", new Object[] { "x", new Integer(3), "y" }, "xyy" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-    }
-
-    @Test public void testInvokeTranslate() {
-        helpInvokeMethod("translate", new Object[] { "ababcd", "ad", "da" }, "dbdbca" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    }
-    
-	@Test public void testFindFunction13() { 
-		helpFindFunction("formatTime", new Class[] { T_TIME, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatTime", new Class[] { T_TIME, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFunction14() { 
-		helpFindFunction("formatDate", new Class[] { T_DATE, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatDate", new Class[] { T_DATE, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFunction15() { 
-		helpFindFunction("formatTimestamp", new Class[] { T_TIMESTAMP, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatTimestamp", new Class[] { T_TIMESTAMP, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFunction16() { 
-		helpFindFunction("parseTime", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseTime", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFunction17() { 
-		helpFindFunction("parseDate", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseDate", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFunction18() { 
-		helpFindFunction("parseTimestamp", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-				helpCreateDescriptor("parseTimestamp", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
-	}
-	
-    @Test public void testFindFunction19() {
-        helpFindFunction("env", new Class[] {T_STRING}, //$NON-NLS-1$
-                         helpCreateDescriptor("env", new Class[] {T_STRING})); //$NON-NLS-1$
-    }
-
-	@Test public void testInvokeFormatTimestamp1() {
-		helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/yy h:mm a") }, "04/05/03 3:04 AM");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatTimestamp2() {
-		helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd k:mm a z") }, "2003-04-05 3:04 AM GMT-06:00");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatTimestamp3() {
-			helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd hh:mm:ss.SSSS") }, "2003-04-05 03:04:12.0000");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-		
-	@Test public void testInvokeFormatTimestampFail() throws Exception {
-		helpInvokeMethodFail("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/nn h:mm a") }); //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeParseTimestamp1() {
-		helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23 CST"), new String("dd MMM yyyy HH:mm:ss z") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 0));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeParseTimestamp2() {
-		helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23.333"), new String("dd MMM yyyy HH:mm:ss.SSS") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 333*1000000));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-
-	@Test public void testFindFormatInteger() { 
-		helpFindFunction("formatInteger", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatInteger", new Class[] { T_INTEGER, T_STRING}) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFormatFloat() { 
-		helpFindFunction("formatFloat", new Class[] { T_FLOAT, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatFloat", new Class[] { T_FLOAT, T_STRING}) ); //$NON-NLS-1$
-	}
-
-	@Test public void testFindFormatDouble() { 
-		helpFindFunction("formatDouble", new Class[] { T_DOUBLE, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatDouble", new Class[] { T_DOUBLE, T_STRING}) ); //$NON-NLS-1$
-	}
-		
-	@Test public void testFindFormatLong() { 
-		helpFindFunction("formatLong", new Class[] { T_LONG, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatLong", new Class[] { T_LONG, T_STRING}) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindFormatBigInteger() { 
-		helpFindFunction("formatBigInteger", new Class[] { T_BIG_INTEGER, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatBigInteger", new Class[] { T_BIG_INTEGER, T_STRING}) ); //$NON-NLS-1$
-	}
-
-	@Test public void testFindFormatBigDecimal() { 
-		helpFindFunction("formatBigDecimal", new Class[] { T_BIG_DECIMAL, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("formatBigDecimal", new Class[] { T_BIG_DECIMAL, T_STRING}) ); //$NON-NLS-1$
-	}
-			
-	@Test public void testFindParseInteger() { 
-		helpFindFunction("parseInteger", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseInteger", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindParseLong() { 
-		helpFindFunction("parseLong", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseLong", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}
-
-	@Test public void testFindParseDouble() { 
-		helpFindFunction("parseDouble", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseDouble", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}	
-	@Test public void testFindParseFloat() { 
-		helpFindFunction("parseFloat", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseFloat", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}
-	
-	@Test public void testFindParseBigInteger() { 
-		helpFindFunction("parseBigInteger", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseBigInteger", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}
-
-	@Test public void testFindParseBigDecimal() { 
-		helpFindFunction("parseBigDecimal", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
-			helpCreateDescriptor("parseBigDecimal", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
-	}	
-			
-	@Test public void testInvokeParseInteger() {
-		helpInvokeMethod("parseInteger", new Object[] {new String("-1234"), new String("######")}, new Integer(-1234));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeParseLong() {
-		helpInvokeMethod("parseLong", new Object[] {new String("123456"), new String("######.##")}, new Long(123456));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeParseDouble() {
-		helpInvokeMethod("parseDouble", new Object[] {new String("123456.78"), new String("#####.#")}, new Double(123456.78));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeParseFloat() {
-		helpInvokeMethod("parseFloat", new Object[] {new String("1234.56"), new String("####.###")}, new Float(1234.56));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeParseBigInteger() {
-		helpInvokeMethod("parseBigInteger", new Object[] {new String("12345678"), new String("###,###")}, new BigInteger("12345678"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-	
-	@Test public void testInvokeParseBigDecimal() {
-		helpInvokeMethod("parseBigDecimal", new Object[] {new String("1234.56"), new String("#####")}, new BigDecimal("1234.56"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-
-	@Test public void testInvokeFormatInteger() {
-		helpInvokeMethod("formatInteger", new Object[] {new Integer(-1234), new String("######")}, "-1234");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatLong() {
-		helpInvokeMethod("formatLong", new Object[] {new Long(123456788), new String("##,###,#")}, "1,2,3,4,5,6,7,8,8");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatDouble() {
-		helpInvokeMethod("formatDouble", new Object[] {new Double(1234.67), new String("####.##")}, "1234.67");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatFloat() {
-		helpInvokeMethod("formatFloat", new Object[] {new Float(1234.67), new String("###.###")}, "1234.67");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeFormatBigInteger() {
-		helpInvokeMethod("formatBigInteger", new Object[] {new BigInteger("45"), new String("###.###")}, "45");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}
-	
-	@Test public void testInvokeFormatBigDecimal() {
-		helpInvokeMethod("formatBigDecimal", new Object[] {new BigDecimal("1234.56"), new String("###.###")}, "1234.56");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-	}	
-
-	@Test public void testInvokeQuarter1() {
-		//		2003-5-15
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 4, 15)}, new Integer(2));	 //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeQuarter2() {
-		//		2003-5-1
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 3, 31)}, new Integer(2));	 //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeQuarter3() {
-		//		2003-1-31
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 0, 31)}, new Integer(1));	 //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeQuarter4() {
-	//		2003-9-30
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 8, 30)}, new Integer(3));	 //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeQuarter5() {
-	//		2003-12-31
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 11, 31)}, new Integer(4));	 //$NON-NLS-1$
-	}		
-	
-	@Test public void testInvokeQuarter6() {
-		//bad date such as 2003-13-45
-		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 12, 45)}, new Integer(1));	 //$NON-NLS-1$
-	}
-	
-	@Test public void testInvokeIfNull() {
-		helpInvokeMethod("ifnull", new Object[] {new Integer(5), new Integer(10)}, new Integer(5));	 //$NON-NLS-1$
-	}
-
-	@Test public void testInvokeLower() {
-		helpInvokeMethod("lower", new Object[] {new String("LOWER")}, new String("lower"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	
-	@Test public void testInvokeUpper() {
-		helpInvokeMethod("upper", new Object[] {new String("upper")}, new String("UPPER"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-
-	@Test public void testInvokeRepeat() {
-		helpInvokeMethod("repeat", new Object[] {new String("cat"), new Integer(3)}, new String("catcatcat"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-
-	@Test public void testInvokeChar() {
-		helpInvokeMethod("char", new Object[] {new Integer(32) }, new Character(' ')); //$NON-NLS-1$
-	}
-
-	/** normal input */
-	@Test public void testInvokeInsert1() {
-		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(2), new String("cat")}, new String("Dowcatown"));	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	/** empty string2 */	
-	@Test public void testInvokeInsert2() {
-		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(2), new String("")}, new String("Dowown"));	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	/** empty string1 with start = 1 and length = 0, so result is just string2 */	
-	@Test public void testInvokeInsert3() {
-		helpInvokeMethod("insert", new Object[] {new String(""), new Integer(1),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(0), new String("cat")}, new String("cat"));	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	/** should fail, with start > string1.length() */
-	@Test public void testInvokeInsert4() throws Exception {
-		helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(2),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(0), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	/** should fail, with length > 0 and input string1.length() = 0 */
-	@Test public void testInvokeInsert5() throws Exception {
-		helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(1),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(1), new String("cat")});	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	/**  (length + start) > string1.length(), then just append str2 starting at start position */
-	@Test public void testInvokeInsert6() {
-		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(7),  //$NON-NLS-1$ //$NON-NLS-2$
-			new Integer(5), new String("cat")}, new String("Downtocat"));	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-    @Test public void testInvokeTimestampAddDate_ignore_case() {
-        helpInvokeMethod("timestampAdd", new Object[] {"sql_TSI_day",  //$NON-NLS-1$ //$NON-NLS-2$
-            new Integer(28), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 5, 12).getTime()));    
-    }   
-    
-	/** date + month --> count=18, inteval=month, result should be 2004-11-15 */
-	@Test public void testInvokeTimestampAddDate2() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH,  //$NON-NLS-1$
-			new Integer(18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 10, 15).getTime()));	
-	}
-
-	/** date + month --> count=-18, inteval=month, result should be 2001-11-15 */
-	@Test public void testInvokeTimestampAddDate2a() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH,  //$NON-NLS-1$
-			new Integer(-18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(101, 10, 15).getTime()));	
-	}
-	
-	/** date + week --> count=6, inteval=week, result should be 2003-04-03 */
-	@Test public void testInvokeTimestampAddDate3() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_WEEK,  //$NON-NLS-1$
-			new Integer(-6), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 3, 3).getTime()));	
-	}
-
-	/** date + quarter --> count=3, inteval=quarter, result should be 2004-2-15 */
-	@Test public void testInvokeTimestampAddDate4() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_QUARTER,  //$NON-NLS-1$
-			new Integer(3), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 1, 15).getTime()));	
-	}
-
-	/** date + year --> count=-1, inteval=year, result should be 2002-5-15 */
-	@Test public void testInvokeTimestampAddDate5() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_YEAR,  //$NON-NLS-1$
-			new Integer(-1), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(102, 4, 15).getTime()));	
-	}
-			
-	/** time + minute --> count=23, inteval=3, result should be 03:32:12 */
-	@Test public void testInvokeTimestampAddTime1() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MINUTE,  //$NON-NLS-1$
-			new Integer(23), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 32, 12).getTime()));	
-	}
-
-	/** time + hour --> count=21, inteval=4, result should be 00:09:12 and overflow */
-	@Test public void testInvokeTimestampAddTime2() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
-			new Integer(21), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 0, 9, 12, 0));	
-	}
-
-	/** time + hour --> count=2, inteval=4, result should be 01:12:12*/
-	@Test public void testInvokeTimestampAddTime3() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
-			new Integer(2), new Timestamp(TimestampUtil.createTime(23, 12, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 1, 12, 12, 0));	
-	}
-	
-	/** time + second --> count=23, inteval=2, result should be 03:10:01 */
-	@Test public void testInvokeTimestampAddTime4() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND,  //$NON-NLS-1$
-			new Integer(49), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 10, 1).getTime()));	
-	}
-
-	/** timestamp + second --> count=23, inteval=2, result should be 2003-05-15 03:09:35.100  */
-	@Test public void testInvokeTimestampAddTimestamp1() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND,  //$NON-NLS-1$
-			new Integer(23), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)}, 
-			TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 35, 100));	
-	}
-
-	/** timestamp + nanos --> count=1, inteval=1, result should be 2003-05-15 03:09:12.000000101  */
-	@Test public void testInvokeTimestampAddTimestamp2() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
-			new Integer(1), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)}, 
-			TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 101));	
-	}
-
-	/** timestamp + nanos --> count=2100000000, inteval=1, result should be 2003-05-15 03:10:01.100000003
-	 *  with increase in second and minutes, because second already at 59 sec originally
-	 */
-	@Test public void testInvokeTimestampAddTimestamp3() {
-		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
-			new Integer(2100000000), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 59, 1)}, 
-			TimestampUtil.createTimestamp(103, 4, 15, 3, 10, 1, 100000003));	
-	}
-			
-	/** time --> interval=hour, time1 = 03:04:45, time2= 05:05:36 return = 2  */
-	@Test public void testInvokeTimestampDiffTime1() {
-		helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
-				new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) }, 
-			new Long(2));	
-	}
-	
-    @Test public void testInvokeTimestampDiffTime1_ignorecase() {
-        helpInvokeMethod("timestampDiff", new Object[] {"SQL_tsi_HOUR",  //$NON-NLS-1$ //$NON-NLS-2$
-        		new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) }, 
-            new Long(2));   
-    }
-    
-	/** 
-	 * timestamp --> interval=week, time1 = 2002-06-21 03:09:35.100,
-	 * time2= 2003-05-02 05:19:35.500 return = 45
-	 */
-	@Test public void testInvokeTimestampDiffTimestamp1() {
-		helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_WEEK,  //$NON-NLS-1$
-			TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100), TimestampUtil.createTimestamp(103, 4, 2, 5, 19, 35, 500) }, 
-			new Long(45));	
-	}
-
-    /** 
-     * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000001,
-     * time2= 2002-06-21 03:09:35.100000000 return = 999999999
-     */
-    @Test public void testInvokeTimestampDiffTimestamp2() {
-        helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
-            TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 1), TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100000000) }, 
-            new Long(99999999));  
-    }
-
-    /** 
-     * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000002,
-     * time2= 2002-06-22 03:09:35.000000001 return = 
-     */
-    @Test public void testInvokeTimestampDiffTimestamp3() {
-        helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
-            TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 2), TimestampUtil.createTimestamp(102, 5, 22, 3, 9, 35, 1) }, 
-            new Long(86399999999999L));  
-    }
-
-    @Test public void testInvokeTimestampCreate1() {
-        helpInvokeMethod("timestampCreate", new Object[] {TimestampUtil.createDate(103, 4, 15), //$NON-NLS-1$
-                                                          TimestampUtil.createTime(23, 59, 59)},
-                                                          TimestampUtil.createTimestamp(103, 4, 15, 23, 59, 59, 0));    
-    }   
-    
-    @Test public void testInvokeBitand() {
-        helpInvokeMethod("bitand", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0x0F0)); //$NON-NLS-1$
-    }
-    @Test public void testInvokeBitor() {
-        helpInvokeMethod("bitor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xFFF)); //$NON-NLS-1$
-    }
-    @Test public void testInvokeBitxor() {
-        helpInvokeMethod("bitxor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xF0F)); //$NON-NLS-1$
-    }
-    @Test public void testInvokeBitnot() {
-        helpInvokeMethod("bitnot", new Object[] {new Integer(0xF0F)}, new Integer(0xFFFFF0F0)); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvokeRound1() {
-        helpInvokeMethod("round", new Object[] {new Integer(123), new Integer(-1)}, new Integer(120)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeRound2() {
-        helpInvokeMethod("round", new Object[] {new Float(123.456), new Integer(2)}, new Float(123.46)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeRound3() {
-        helpInvokeMethod("round", new Object[] {new Double(123.456), new Integer(2)}, new Double(123.46)); //$NON-NLS-1$
-    }
-
-    @Test public void testInvokeRound4() {
-        helpInvokeMethod("round", new Object[] {new BigDecimal("123.456"), new Integer(2)}, new BigDecimal("123.460")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    /** defect 10941 */
-    @Test public void testInvokeConvertTime() {
-        helpInvokeMethod("convert", new Object[] {"05:00:00", "time"}, TimestampUtil.createTime(5, 0, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$                    
-    }
-
-    @Test public void testInvokeXpath1() {
-        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
-                         new Object[] {
-                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>", //$NON-NLS-1$
-                                       "a/b/c"}, //$NON-NLS-1$ 
-                         "test"); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeXpathWithNill() {
-        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
-                         new Object[] {
-                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><b xsi:nil=\"true\"/></a>", //$NON-NLS-1$
-                                       "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$ 
-                         null);
-    }
-    
-    @Test public void testInvokeXpathWithNill1() {
-        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
-                         new Object[] {
-                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b>value</b></a>", //$NON-NLS-1$
-                                       "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$ 
-                         "value"); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvokeModifyTimeZone() {
-        Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
-        Timestamp out = Timestamp.valueOf("2004-10-03 22:59:59.123"); //$NON-NLS-1$
-        helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/Chicago", "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    // TimestampWithTimezone has a static copy the default timezone object which makes this test not execute properly
-    public void defer_testInvokeModifyTimeZoneFromLocal() {
-        Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
-        Timestamp out = Timestamp.valueOf("2004-10-03 21:59:59.123"); //$NON-NLS-1$
-        helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvokeRand() throws Exception {
-        helpInvokeMethod("rand", new Object[] {new Integer(100)}, new Double(0.7220096548596434)); //$NON-NLS-1$ 
-        // this does not actually fail but returns a result
-        assertNotNull(helpInvokeMethod("rand", new Class[] {Integer.class}, new Object[] {null}, null)); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvokeUser() throws Exception {
-        CommandContext c = new CommandContext();
-        c.setUserName("foodude"); //$NON-NLS-1$
-        helpInvokeMethod("user", new Class[] {}, new Object[] {}, c, "foodude"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvokeEnv() throws Exception {
-        CommandContext c = new CommandContext();
-        Properties props = new Properties();
-        props.setProperty("env_test", "env_value"); //$NON-NLS-1$ //$NON-NLS-2$
-        c.setEnvironmentProperties(props);
-        helpInvokeMethod("env", new Class[] {String.class}, new Object[] {"env_test"}, c, "env_value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$        
-        helpInvokeMethod("env", new Class[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeCommandPayload() throws Exception {
-        CommandContext c = new CommandContext();        
-        c.setCommandPayload("payload_too heavy"); //$NON-NLS-1$
-        helpInvokeMethod("commandpayload", new Class[] {}, new Object[] {}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        helpInvokeMethod("commandpayload", new Class[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$ 
-        Properties props = new Properties();
-        props.setProperty("payload", "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
-        c.setCommandPayload(props);
-        helpInvokeMethod("commandpayload", new Class[] {String.class}, new Object[] {"payload"}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }    
-    
-    @Test public void testNullDependent() {
-        FunctionDescriptor actual = library.findFunction("concat2", new Class[] {String.class, String.class}); //$NON-NLS-1$
-        assertTrue(actual.isNullDependent());
-        
-        actual = library.findFunction("concat", new Class[] {String.class, String.class}); //$NON-NLS-1$
-        assertFalse(actual.isNullDependent());
-    }
-    
-    @Test public void testInvokeCeiling() {
-        helpInvokeMethod("ceiling", new Object[] { new Double("3.14") }, new Double("4")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeFloor() {
-        helpInvokeMethod("floor", new Object[] { new Double("3.14") }, new Double("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeExp() {
-        helpInvokeMethod("exp", new Object[] { new Double("0") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeLog() {
-        helpInvokeMethod("log", new Object[] { new Double("1") }, new Double("0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeLog10() {
-        helpInvokeMethod("log10", new Object[] { new Double("10") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeLog10Error() throws Exception {
-        helpInvokeMethodFail("log10", new Object[] { new Double("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokePower() {
-        helpInvokeMethod("power", new Object[] { new Double("10"), new Double("2") }, new Double("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-    }
-    
-    @Test public void testInvokePower1() {
-        helpInvokeMethod("power", new Object[] { new BigDecimal("10"), new Integer(2) }, new BigDecimal("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeSqrt() {
-        helpInvokeMethod("sqrt", new Object[] { new Double("4")}, new Double("2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testInvokeDayName() {
-        for (int i = 0; i < FunctionMethods.dayNames.length; i++) {
-            Date time = TimestampUtil.createDate(100, 0, i + 2);
-            helpInvokeMethod("dayName", new Object[] { time }, FunctionMethods.dayNames[i]); //$NON-NLS-1$ 
-        }
-    }
-    
-    @Test public void testInvokeDayOfMonth() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("dayOfMonth", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeDayOfWeek() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("dayOfWeek", new Object[] { time }, new Integer(7)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeDayOfYear() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 2, 1, 2, 3, 4);
-        helpInvokeMethod("dayOfYear", new Object[] { time }, new Integer(2)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeMonth() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("month", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeMonthName() {
-        for (int i = 0; i < FunctionMethods.monthNames.length; i++) {
-            Date time = TimestampUtil.createDate(100, i, 1);
-            helpInvokeMethod("monthName", new Object[] { time }, FunctionMethods.monthNames[i]); //$NON-NLS-1$ 
-        }
-    }
-    
-    @Test public void testInvokeMinute() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("minute", new Object[] { time }, new Integer(2)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeSecond() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("second", new Object[] { time }, new Integer(3)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeWeek() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("week", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeYear() {
-        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
-        helpInvokeMethod("year", new Object[] { time }, new Integer(2000)); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testInvokeCoalesce() {
-    	helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }, Integer.valueOf(0));
-    }
-    
-    @Test public void testInvokeCoalesce1() {
-    	helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { null, null}, null);
-    }
-    
-    @Test public void testInvokeNull() throws Exception {
-        helpInvokeMethod(SourceSystemFunctions.LTRIM, new Class[] {DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null }, null, null);  
-    }
-    
-    @Test public void testInvokeNull1() throws Exception {
-        helpInvokeMethod(SourceSystemFunctions.CONCAT, new Class[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null, String.valueOf(1) }, null, null);  
-    }  
-    
-	@Test public void testInvokeXslTransform() throws Exception {
-        CommandContext c = new CommandContext();
-        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
-        ClobType result = (ClobType)helpInvokeMethod("xsltransform", new Class[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML}, 
-        		new Object[] {DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML), 
-        		DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template><xsl:template match=\"Quantity\"/></xsl:stylesheet>", DataTypeManager.DefaultDataClasses.XML)}, c);
-        
-        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
-        assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name></Item></Items></Catalog></Catalogs>", xml);
-    }
-	
-	@Test public void testInvokeXmlConcat() throws Exception {
-        CommandContext c = new CommandContext();
-        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
-        XMLType result = (XMLType)helpInvokeMethod("xmlconcat", new Class[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML}, 
-        		new Object[] {DataTypeManager.transformValue("<bar/>", DataTypeManager.DefaultDataClasses.XML), DataTypeManager.transformValue("<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML)}, c);
-        
-        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
-        assertEquals("<bar/><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", xml);
-    }
-	
-	@Test public void testInvokeXmlComment() throws Exception {
-        CommandContext c = new CommandContext();
-        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
-        XMLType result = (XMLType)helpInvokeMethod("xmlcomment", new Class[] {DataTypeManager.DefaultDataClasses.STRING}, 
-        		new Object[] {"comment"}, c);
-        
-        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
-        assertEquals("<!--comment-->", xml);
-    }
-	
-	@Test public void testToChars() throws Exception {
-		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "ASCII" }, null); //$NON-NLS-1$
-		String string = result.getSubString(1, (int)result.length());
-		assertEquals("hello world", string);
-	}
-	
-	@Test public void testToBytes() throws Exception {
-		Blob result = (Blob)helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("hello world".toCharArray())), "UTF32" }, null); //$NON-NLS-1$
-		assertEquals(44, result.length()); //4 bytes / char
-	}
-	
-	@Test public void testToChars1() throws Exception {
-		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "BASE64" }, null); //$NON-NLS-1$
-		String string = result.getSubString(1, (int)result.length());
-		assertEquals("hello world", new String(Base64.decode(string), "ASCII"));
-	}
-	
-	@Test public void testToChars2() throws Exception {
-		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "HEX" }, null); //$NON-NLS-1$
-		String string = result.getSubString(1, (int)result.length());
-		assertEquals("68656C6C6F20776F726C64", string);
-	}
-	
-	@Test public void testToBytes2() throws Exception {
-		Blob result = (Blob)helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("68656C6C6F20776F726C64".toCharArray())), "HEX" }, null); //$NON-NLS-1$
-		assertEquals("hello world", new String(ObjectConverterUtil.convertToCharArray(result.getBinaryStream(), -1, "ASCII")));
-	}
-	
-	@Test(expected=FunctionExecutionException.class) public void testToBytes3() throws Exception {
-		helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("a".toCharArray())), "BASE64" }, null); //$NON-NLS-1$
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java (from rev 2764, trunk/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1414 @@
+/*
+ * 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.function;
+
+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.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.TimeZone;
+
+import javax.sql.rowset.serial.SerialBlob;
+import javax.sql.rowset.serial.SerialClob;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.types.BlobType;
+import org.teiid.core.types.ClobType;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.NullType;
+import org.teiid.core.types.XMLType;
+import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
+import org.teiid.core.util.Base64;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.metadata.FunctionMethod.PushDown;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.TimestampUtil;
+import org.teiid.query.util.CommandContext;
+import org.teiid.translator.SourceSystemFunctions;
+
+
+ at SuppressWarnings("nls")
+public class TestFunctionLibrary {
+
+	// These are just used as shorthand convenience to make unit tests more readable below
+	private static final Class<String> T_STRING = DataTypeManager.DefaultDataClasses.STRING;
+	private static final Class<Integer> T_INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
+	private static final Class<BigInteger> T_BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
+	private static final Class<BigDecimal> T_BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;		
+    private static final Class<Long> T_LONG = DataTypeManager.DefaultDataClasses.LONG;
+	private static final Class<Float> T_FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
+    private static final Class<Double> T_DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
+	private static final Class<NullType> T_NULL = DataTypeManager.DefaultDataClasses.NULL;
+	private static final Class<Time> T_TIME = DataTypeManager.DefaultDataClasses.TIME;
+	private static final Class<Date> T_DATE = DataTypeManager.DefaultDataClasses.DATE;
+	private static final Class<Timestamp> T_TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
+	
+	private FunctionLibrary library = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree(new UDFSource(Collections.EMPTY_LIST)));
+
+	@Before public void setUp() { 
+		TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$ 
+	}
+	
+	@After public void tearDown() { 
+		TimestampWithTimezone.resetCalendar(null);
+	}
+	
+	// ################################## TEST HELPERS ################################
+	
+    private FunctionDescriptor helpCreateDescriptor(String name, Class[] types) { 
+        final String fname = name;
+        final Class[] ftypes = types;
+        return new FunctionDescriptor() {
+            public String getName() {
+                return fname;
+            }
+            public PushDown getPushdown() {
+                return PushDown.CAN_PUSHDOWN;
+            }
+            public Class[] getTypes() { 
+                return ftypes;
+            }
+            public Class getReturnType() { 
+                return null;
+            }
+            
+            public String toString() {
+                StringBuffer str = new StringBuffer(fname);
+                str.append("("); //$NON-NLS-1$
+                for(int i=0; i<ftypes.length; i++) {
+                    if(ftypes[i] != null) { 
+                        str.append(ftypes[i].getName());
+                    } else {
+                        str.append("null"); //$NON-NLS-1$
+                    }       
+                    if(i<(ftypes.length-1)) {
+                        str.append(", "); //$NON-NLS-1$
+                    }
+                }
+                return str.toString();
+            }
+            public boolean requiresContext() {
+                return false;
+            }
+            public boolean isNullDependent() {
+                return true;
+            }
+            
+        };
+    }
+    
+	private void helpFindFunction(String fname, Class[] types, FunctionDescriptor expected) {
+		FunctionDescriptor actual =  library.findFunction(fname, types);
+	
+        assertEquals("Function names do not match: ", expected.getName().toLowerCase(), actual.getName().toLowerCase());             //$NON-NLS-1$
+        assertEquals("Arg lengths do not match: ", expected.getTypes().length, actual.getTypes().length); //$NON-NLS-1$
+	}
+
+	private void helpFindFunctionFail(String fname, Class[] types) {
+		FunctionDescriptor actual =  library.findFunction(fname, types);
+		assertNull("Function was found but should not have been: " + actual, actual); //$NON-NLS-1$
+	}
+    
+	private void helpFindConversions(String fname, Class[] types, FunctionDescriptor[] expected) {
+
+		FunctionDescriptor[] actual = library.determineNecessaryConversions(fname, null, types, false);
+		
+		if(expected == null) {
+			if(actual != null) { 
+				fail("Expected to find no conversion for " + fname + Arrays.asList(types) + " but found: " + Arrays.asList(actual)); //$NON-NLS-1$ //$NON-NLS-2$
+			}	
+		} else {
+			if(actual == null) { 
+				fail("Expected to find conversion for " + fname + Arrays.asList(types) + " but found none"); //$NON-NLS-1$ //$NON-NLS-2$
+			} else {
+				// Compare returned descriptors with expected descriptor
+				for(int i=0; i<expected.length; i++) { 
+                    if(expected[i] == null) { 
+                        if(actual[i] != null) { 
+                            fail("Expected no conversion at index " + i + ", but found: " + actual[i]); //$NON-NLS-1$ //$NON-NLS-2$
+                        }
+                    } else {
+                        if(actual[i] == null) { 
+                            fail("Expected conversion at index " + i + ", but found none.");                             //$NON-NLS-1$ //$NON-NLS-2$
+                        } else {
+                            assertEquals("Expected conversion function names do not match: ", expected[i].getName(), actual[i].getName());             //$NON-NLS-1$
+                            assertEquals("Expected conversion arg lengths do not match: ", expected[i].getTypes().length, actual[i].getTypes().length);                         //$NON-NLS-1$
+                        }        
+                    }        
+				}			
+			}			
+		}
+	}	
+	
+	private void helpFindForm(String fname, int numArgs) {
+		FunctionForm form = library.findFunctionForm(fname, numArgs);
+        assertNotNull("Failed to find function '" + fname + "' with " + numArgs + " args", form); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        assertEquals("Function names do not match: ", fname.toUpperCase(), form.getName().toUpperCase());             //$NON-NLS-1$
+        assertEquals("Arg lengths do not match: ", numArgs, form.getArgNames().size()); //$NON-NLS-1$
+	}
+
+	private void helpInvokeMethod(String fname, Object[] inputs, Object expectedOutput) {
+        try {
+            helpInvokeMethod(fname, null, inputs, null, expectedOutput);
+        } catch (Exception err) {
+            throw new RuntimeException(err);
+        } 
+	}
+    
+    private void helpInvokeMethod(String fname, Class[] types, Object[] inputs, CommandContext context, Object expectedOutput) throws FunctionExecutionException {
+    	Object actualOutput = helpInvokeMethod(fname, types, inputs, context);
+        assertEquals("Actual function output not equal to expected: ", expectedOutput, actualOutput); //$NON-NLS-1$
+    }
+
+	private Object helpInvokeMethod(String fname, Class[] types,
+			Object[] inputs, CommandContext context)
+			throws FunctionExecutionException {
+		if (types == null) {
+            // Build type signature
+            types = new Class[inputs.length];
+            for(int i=0; i<inputs.length; i++) { 
+                types[i] = DataTypeManager.determineDataTypeClass(inputs[i]);   
+            }        
+    	}
+    	if (context == null) {
+    		context = new CommandContext();
+    	}
+        Object actualOutput = null;
+        // Find function descriptor
+        FunctionDescriptor descriptor = library.findFunction(fname, types);         
+        if (descriptor.requiresContext()) {
+            // Invoke function with inputs
+            Object[] in = new Object[inputs.length+1];
+            in[0] = context;
+            for (int i = 0; i < inputs.length; i++) {
+                in[i+1] = inputs[i];
+            }
+            actualOutput = descriptor.invokeFunction(in);
+        }
+        else {
+            // Invoke function with inputs
+            actualOutput = descriptor.invokeFunction(inputs);                
+        }
+		return actualOutput;
+	}
+    	    
+	private void helpInvokeMethodFail(String fname, Object[] inputs) {
+		   helpInvokeMethodFail(fname, null, inputs);
+	}	
+    	
+    private void helpInvokeMethodFail(String fname, Class<?> types[], Object[] inputs) {
+    	try {
+            helpInvokeMethod(fname, types, inputs, null);
+            fail("expected exception"); //$NON-NLS-1$
+        } catch (FunctionExecutionException err) {
+        }    
+    }    
+	// ################################## ACTUAL TESTS ################################
+	
+	@Test public void testFindFunction1() { 
+		helpFindFunction("convert", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+            helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }) );
+	}
+	
+	@Test public void testFindFunction2() { 
+		helpFindFunction("cast", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+            helpCreateDescriptor(FunctionLibrary.CAST, new Class[] { T_INTEGER, T_STRING }) );
+	}
+	
+    @Test public void testFindFunction3() {
+        helpFindFunction("curdate", new Class[0], //$NON-NLS-1$
+        	helpCreateDescriptor("curdate", new Class[0])); //$NON-NLS-1$
+    }
+   
+    @Test public void testFindFunction4() {
+        helpFindFunctionFail("curdate", new Class[] { T_INTEGER }); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindFunction5() {
+        helpFindFunction("+", new Class[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+        	helpCreateDescriptor("+", new Class[] { T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindFunction6() {
+        helpFindFunctionFail("+", new Class[] {T_INTEGER, T_FLOAT}); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindFunction7() {
+        helpFindFunctionFail("+", new Class[] {T_INTEGER, T_FLOAT, T_INTEGER}); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindFunction8() {
+        helpFindFunctionFail("+", new Class[] {T_INTEGER}); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindFunction9() {        
+		helpFindFunctionFail("+", new Class[] {T_INTEGER, T_NULL });     //$NON-NLS-1$
+    }
+
+    @Test public void testFindFunction10() {
+        helpFindFunction("substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+            helpCreateDescriptor("substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }) ); //$NON-NLS-1$
+    }
+
+    @Test public void testFindFunction11() {
+        helpFindFunction("substring", new Class[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
+            helpCreateDescriptor("substring", new Class[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
+    }
+
+    @Test public void testFindFunction12() {
+        helpFindFunction("context", new Class[] { T_STRING, T_INTEGER }, //$NON-NLS-1$
+            helpCreateDescriptor("context", new Class[] { T_STRING, T_INTEGER }) ); //$NON-NLS-1$
+    }
+
+    @Test public void testFindFunction12a() {
+        helpFindFunction("rowlimit", new Class[] { T_STRING }, //$NON-NLS-1$
+            helpCreateDescriptor("rowlimit", new Class[] { T_STRING }) ); //$NON-NLS-1$
+    }
+
+    @Test public void testFindFunction12b() {
+        helpFindFunction("rowlimitexception", new Class[] { T_STRING }, //$NON-NLS-1$
+            helpCreateDescriptor("rowlimitexception", new Class[] { T_STRING }) ); //$NON-NLS-1$
+    }
+    
+	@Test public void testFind0ArgConversion1() { 	
+		helpFindConversions(
+			"curdate", new Class[] {}, //$NON-NLS-1$
+			new FunctionDescriptor[0] );
+	}
+
+	@Test public void testFind0ArgConversion2() { 	
+		helpFindConversions(
+			"curdate", new Class[] { T_INTEGER }, //$NON-NLS-1$
+			null );
+	}
+
+	@Test public void testFind1ArgConversion1() { 	
+		helpFindConversions(
+			"length", new Class[] { T_STRING }, //$NON-NLS-1$
+			new FunctionDescriptor[1] );
+	}
+
+	@Test public void testFind1ArgConversion2() { 	
+		helpFindConversions(
+			"length", new Class[] { T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING })
+			} );
+	}
+
+	@Test public void testFind1ArgConversion3() { 	
+		helpFindConversions(
+			"length", new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.TIMESTAMP, T_STRING })
+			} );
+	}
+
+	@Test public void testFind2ArgConversion1() { 	
+		helpFindConversions(
+			"+", new Class[] { T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[2] );
+	}
+
+	@Test public void testFind2ArgConversion2() { 	
+		helpFindConversions(
+			"+", new Class[] { T_INTEGER, T_FLOAT }, //$NON-NLS-1$
+			new FunctionDescriptor[] { 
+                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }), 
+                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_FLOAT, T_STRING }) } );
+	}
+
+	@Test public void testFind2ArgConversion3() { 	
+		helpFindConversions(
+			"+", new Class[] { T_FLOAT, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] { 
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_FLOAT, T_STRING }), 
+                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }) } );
+	}
+
+	@Test public void testFind2ArgConversion4() { 	
+		helpFindConversions(
+			"+", new Class[] { T_STRING, T_FLOAT }, //$NON-NLS-1$
+			null );
+	}
+
+	@Test public void testFind2ArgConversion5() { 	
+		helpFindConversions(
+			"+", new Class[] { T_NULL, T_NULL }, //$NON-NLS-1$
+			new FunctionDescriptor[] { 
+			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }), 
+                helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) } );
+	}
+
+	@Test public void testFind2ArgConversion6() { 	
+		helpFindConversions(
+			"+", new Class[] { T_NULL, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] { 
+			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }), 
+				null } );
+	}
+
+	@Test public void testFind2ArgConversion7() { 	
+		helpFindConversions(
+			"+", new Class[] { T_INTEGER, T_NULL }, //$NON-NLS-1$
+			new FunctionDescriptor[] { 
+			    null, 
+			    helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) } );
+	}
+
+	@Test public void testFind3ArgConversion1() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_STRING, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[3] );
+	}
+
+	@Test public void testFind3ArgConversion2() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_INTEGER, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }),
+				null,
+				null    
+			} );
+	}
+
+	@Test public void testFind3ArgConversion3() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_INTEGER, T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_INTEGER, T_STRING }),
+				null,
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
+			} );
+	}
+
+	@Test public void testFind3ArgConversion4() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_STRING, T_INTEGER, DataTypeManager.DefaultDataClasses.TIMESTAMP }, //$NON-NLS-1$
+			null );
+	}
+
+	@Test public void testFind3ArgConversion5() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_STRING, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+			    null,
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
+			} );
+	}
+
+	@Test public void testFind3ArgConversion6() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_INTEGER, DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.SHORT }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.INTEGER, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { DataTypeManager.DefaultDataClasses.SHORT, T_STRING })    
+			} );
+	}
+
+	@Test public void testFind3ArgConversion7() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_NULL, T_INTEGER, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
+				null,
+				null }
+			);
+	}
+
+	@Test public void testFind3ArgConversion8() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_NULL, T_NULL, T_INTEGER }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
+				null }
+			);
+	}
+
+	@Test public void testFind3ArgConversion9() { 	
+		helpFindConversions(
+			"substring", new Class[] { T_NULL, T_NULL, T_NULL }, //$NON-NLS-1$
+			new FunctionDescriptor[] {
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }),    
+				helpCreateDescriptor(FunctionLibrary.CONVERT, new Class[] { T_NULL, T_STRING }) }
+			);
+	}
+
+    // Walk through all functions by metadata 
+    @Test public void testEnumerateForms() {
+        Collection categories = library.getFunctionCategories();
+        Iterator catIter = categories.iterator();
+        while(catIter.hasNext()) { 
+            String category = (String) catIter.next();
+            //System.out.println("Category: " + category);
+            
+            Collection functions = library.getFunctionForms(category);
+            Iterator functionIter = functions.iterator();
+            while(functionIter.hasNext()) { 
+                FunctionForm form = (FunctionForm) functionIter.next();
+                //System.out.println("\tFunction: " + form.getDisplayString());                
+                
+                // Lookup this form
+                helpFindForm(form.getName(), form.getArgNames().size());
+            }            
+        }        
+    }
+
+	@Test public void testFindForm1() { 
+		helpFindForm("convert", 2); //$NON-NLS-1$
+	}
+ 
+	@Test public void testFindForm2() { 
+		helpFindForm("locate", 2); //$NON-NLS-1$
+	}
+    
+	@Test public void testFindForm3() { 
+		helpFindForm("locate", 3); //$NON-NLS-1$
+	}
+
+    @Test public void testFindForm4() { 
+        helpFindForm("substring", 2); //$NON-NLS-1$
+    }
+    
+    @Test public void testFindForm5() { 
+        helpFindForm("substring", 3); //$NON-NLS-1$
+    }
+ 
+	@Test public void testFindForm6() { 
+		helpFindForm("now", 0); //$NON-NLS-1$
+	}
+    
+    @Test public void testInvokePlus1() { 
+    	helpInvokeMethod("+", new Object[] { new Integer(3), new Integer(2) }, new Integer(5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokePlus2() {
+        helpInvokeMethod("+", new Object[] { new Long(3), new Long(2) }, new Long(5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokePlus3() {
+        helpInvokeMethod("+", new Object[] { new Float(3), new Float(2) }, new Float(5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokePlus4() {
+        helpInvokeMethod("+", new Object[] { new Double(3), new Double(2) }, new Double(5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokePlus5() {
+        helpInvokeMethod("+", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokePlus6() {
+        helpInvokeMethod("+", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeMinus1() {
+        helpInvokeMethod("-", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMinus2() {
+        helpInvokeMethod("-", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMinus3() {
+        helpInvokeMethod("-", new Object[] { new Float(3), new Float(2) }, new Float(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMinus4() {
+        helpInvokeMethod("-", new Object[] { new Double(3), new Double(2) }, new Double(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMinus5() {
+        helpInvokeMethod("-", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeMinus6() {
+        helpInvokeMethod("-", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeMultiply1() {
+        helpInvokeMethod("*", new Object[] { new Integer(3), new Integer(2) }, new Integer(6)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMultiply2() {
+        helpInvokeMethod("*", new Object[] { new Long(3), new Long(2) }, new Long(6)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMultiply3() {
+        helpInvokeMethod("*", new Object[] { new Float(3), new Float(2) }, new Float(6)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMultiply4() {
+        helpInvokeMethod("*", new Object[] { new Double(3), new Double(2) }, new Double(6)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeMultiply5() {
+        helpInvokeMethod("*", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeMultiply6() {
+        helpInvokeMethod("*", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("6")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeDivide1() {
+        helpInvokeMethod("/", new Object[] { new Integer(3), new Integer(2) }, new Integer(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeDivide2() {
+        helpInvokeMethod("/", new Object[] { new Long(3), new Long(2) }, new Long(1)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeDivide3() {
+        helpInvokeMethod("/", new Object[] { new Float(3), new Float(2) }, new Float(1.5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeDivide4() {
+        helpInvokeMethod("/", new Object[] { new Double(3), new Double(2) }, new Double(1.5)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeDivide5() {
+        helpInvokeMethod("/", new Object[] { new BigInteger("3"), new BigInteger("2") }, new BigInteger("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    // one digit precision
+    @Test public void testInvokeDivide6() {
+        helpInvokeMethod("/", new Object[] { new BigDecimal("3"), new BigDecimal("2") }, new BigDecimal("1.5"));   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+    
+    @Test public void testInvokeDivide7() throws Exception {
+        helpInvokeMethodFail("/", new Object[] { new Float("3"), new Float("0") });   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+    
+    @Test public void testInvokeDivideMod() {
+        helpInvokeMethod("mod", new Object[] { new BigDecimal("3.1"), new BigDecimal("2") }, new BigDecimal("1.1"));   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeAbs1() {
+        helpInvokeMethod("abs", new Object[] { new Integer(-3) }, new Integer(3)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeAbs2() {
+        helpInvokeMethod("abs", new Object[] { new Long(-3) }, new Long(3)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeAbs3() {
+        helpInvokeMethod("abs", new Object[] { new Float(-3) }, new Float(3)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeAbs4() {
+        helpInvokeMethod("abs", new Object[] { new Double(-3) }, new Double(3)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeAbs5() {
+        helpInvokeMethod("abs", new Object[] { new BigInteger("-3") }, new BigInteger("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    @Test public void testInvokeAbs6() {
+        helpInvokeMethod("abs", new Object[] { new BigDecimal("-3") }, new BigDecimal("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+	@Test public void testInvokeAcos() {
+		helpInvokeMethod("acos", new Object[] { new Double(0.05) }, new Double(1.5207754699891267)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeAsin() {
+		helpInvokeMethod("asin", new Object[] { new Double(0.05) }, new Double(0.050020856805770016)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeAtan() {
+		helpInvokeMethod("atan", new Object[] { new Double(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeAtan2() {
+		helpInvokeMethod("atan2", new Object[] { new Double(0.05), new Double(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeAtanBigDecimal() {
+		helpInvokeMethod("atan", new Object[] { new BigDecimal(0.05) }, new Double(0.049958395721942765)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeAtan2BigDecimal() {
+		helpInvokeMethod("atan2", new Object[] { new BigDecimal(0.05), new BigDecimal(0.07) }, new Double(0.6202494859828215)); //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeCos() {
+		helpInvokeMethod("cos", new Object[] { new Double(1.57) }, new Double(7.963267107332633E-4)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeCot() {
+		helpInvokeMethod("cot", new Object[] { new Double(1.57) }, new Double(7.963269632231926E-4)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeDegrees() {
+		helpInvokeMethod("degrees", new Object[] { new Double(1.57) }, new Double(89.95437383553926)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokePI() {
+		helpInvokeMethod("pi", new Object[] { }, new Double(3.141592653589793)); //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeRadians() {
+		helpInvokeMethod("radians", new Object[] { new Double(89.95437383553926) }, new Double(1.57)); //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeSin() {
+		helpInvokeMethod("sin", new Object[] { new Double(1.57) }, new Double(0.9999996829318346)); //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeTan() {
+		helpInvokeMethod("tan", new Object[] { new Double(0.785) }, new Double(0.9992039901050427)); //$NON-NLS-1$
+	}
+							
+    @Test public void testInvokeAscii() {
+        helpInvokeMethod("ascii", new Object[] { " " }, new Integer(32)); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvokeChr() {
+        helpInvokeMethod("chr", new Object[] { new Integer(32) }, new Character(' ')); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvokeNvl() {
+        helpInvokeMethod("nvl", new Object[] { new Integer(5), new Integer(10) }, new Integer(5) ); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeConcatOperator() {
+        helpInvokeMethod("||", new Object[] { "a", "b" }, "ab" );         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+
+    @Test public void testInvokeInitcap() {
+        helpInvokeMethod("initcap", new Object[] { "my test\ndata" }, "My Test\nData" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    @Test public void testInvokeLpad1() {
+        helpInvokeMethod("lpad", new Object[] { "x", new Integer(3) }, "  x" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    @Test public void testInvokeLpad2() {
+        helpInvokeMethod("lpad", new Object[] { "x", new Integer(3), "y" }, "yyx" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+    
+    @Test public void testInvokeRpad1() {
+        helpInvokeMethod("rpad", new Object[] { "x", new Integer(3) }, "x  " ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    @Test public void testInvokeRpad2() {
+        helpInvokeMethod("rpad", new Object[] { "x", new Integer(3), "y" }, "xyy" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+    }
+
+    @Test public void testInvokeTranslate() {
+        helpInvokeMethod("translate", new Object[] { "ababcd", "ad", "da" }, "dbdbca" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    }
+    
+	@Test public void testFindFunction13() { 
+		helpFindFunction("formatTime", new Class[] { T_TIME, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatTime", new Class[] { T_TIME, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFunction14() { 
+		helpFindFunction("formatDate", new Class[] { T_DATE, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatDate", new Class[] { T_DATE, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFunction15() { 
+		helpFindFunction("formatTimestamp", new Class[] { T_TIMESTAMP, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatTimestamp", new Class[] { T_TIMESTAMP, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFunction16() { 
+		helpFindFunction("parseTime", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseTime", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFunction17() { 
+		helpFindFunction("parseDate", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseDate", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFunction18() { 
+		helpFindFunction("parseTimestamp", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+				helpCreateDescriptor("parseTimestamp", new Class[] { T_STRING, T_STRING }) ); //$NON-NLS-1$
+	}
+	
+    @Test public void testFindFunction19() {
+        helpFindFunction("env", new Class[] {T_STRING}, //$NON-NLS-1$
+                         helpCreateDescriptor("env", new Class[] {T_STRING})); //$NON-NLS-1$
+    }
+
+	@Test public void testInvokeFormatTimestamp1() {
+		helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/yy h:mm a") }, "04/05/03 3:04 AM");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatTimestamp2() {
+		helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd k:mm a z") }, "2003-04-05 3:04 AM GMT-06:00");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatTimestamp3() {
+			helpInvokeMethod("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("yyyy-mm-dd hh:mm:ss.SSSS") }, "2003-04-05 03:04:12.0000");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+		
+	@Test public void testInvokeFormatTimestampFail() throws Exception {
+		helpInvokeMethodFail("formatTimestamp", new Object[] {TimestampUtil.createTimestamp(103, 2, 5, 3, 4, 12, 255), new String("mm/dd/nn h:mm a") }); //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeParseTimestamp1() {
+		helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23 CST"), new String("dd MMM yyyy HH:mm:ss z") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 0));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeParseTimestamp2() {
+		helpInvokeMethod("parseTimestamp", new Object[] {new String("05 Mar 2003 03:12:23.333"), new String("dd MMM yyyy HH:mm:ss.SSS") }, TimestampUtil.createTimestamp(103, 2, 5, 3, 12, 23, 333*1000000));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+
+	@Test public void testFindFormatInteger() { 
+		helpFindFunction("formatInteger", new Class[] { T_INTEGER, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatInteger", new Class[] { T_INTEGER, T_STRING}) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFormatFloat() { 
+		helpFindFunction("formatFloat", new Class[] { T_FLOAT, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatFloat", new Class[] { T_FLOAT, T_STRING}) ); //$NON-NLS-1$
+	}
+
+	@Test public void testFindFormatDouble() { 
+		helpFindFunction("formatDouble", new Class[] { T_DOUBLE, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatDouble", new Class[] { T_DOUBLE, T_STRING}) ); //$NON-NLS-1$
+	}
+		
+	@Test public void testFindFormatLong() { 
+		helpFindFunction("formatLong", new Class[] { T_LONG, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatLong", new Class[] { T_LONG, T_STRING}) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindFormatBigInteger() { 
+		helpFindFunction("formatBigInteger", new Class[] { T_BIG_INTEGER, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatBigInteger", new Class[] { T_BIG_INTEGER, T_STRING}) ); //$NON-NLS-1$
+	}
+
+	@Test public void testFindFormatBigDecimal() { 
+		helpFindFunction("formatBigDecimal", new Class[] { T_BIG_DECIMAL, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("formatBigDecimal", new Class[] { T_BIG_DECIMAL, T_STRING}) ); //$NON-NLS-1$
+	}
+			
+	@Test public void testFindParseInteger() { 
+		helpFindFunction("parseInteger", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseInteger", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindParseLong() { 
+		helpFindFunction("parseLong", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseLong", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}
+
+	@Test public void testFindParseDouble() { 
+		helpFindFunction("parseDouble", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseDouble", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}	
+	@Test public void testFindParseFloat() { 
+		helpFindFunction("parseFloat", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseFloat", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}
+	
+	@Test public void testFindParseBigInteger() { 
+		helpFindFunction("parseBigInteger", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseBigInteger", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}
+
+	@Test public void testFindParseBigDecimal() { 
+		helpFindFunction("parseBigDecimal", new Class[] { T_STRING, T_STRING }, //$NON-NLS-1$
+			helpCreateDescriptor("parseBigDecimal", new Class[] { T_STRING, T_STRING}) ); //$NON-NLS-1$
+	}	
+			
+	@Test public void testInvokeParseInteger() {
+		helpInvokeMethod("parseInteger", new Object[] {new String("-1234"), new String("######")}, new Integer(-1234));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeParseLong() {
+		helpInvokeMethod("parseLong", new Object[] {new String("123456"), new String("######.##")}, new Long(123456));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeParseDouble() {
+		helpInvokeMethod("parseDouble", new Object[] {new String("123456.78"), new String("#####.#")}, new Double(123456.78));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeParseFloat() {
+		helpInvokeMethod("parseFloat", new Object[] {new String("1234.56"), new String("####.###")}, new Float(1234.56));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeParseBigInteger() {
+		helpInvokeMethod("parseBigInteger", new Object[] {new String("12345678"), new String("###,###")}, new BigInteger("12345678"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+	
+	@Test public void testInvokeParseBigDecimal() {
+		helpInvokeMethod("parseBigDecimal", new Object[] {new String("1234.56"), new String("#####")}, new BigDecimal("1234.56"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+
+	@Test public void testInvokeFormatInteger() {
+		helpInvokeMethod("formatInteger", new Object[] {new Integer(-1234), new String("######")}, "-1234");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatLong() {
+		helpInvokeMethod("formatLong", new Object[] {new Long(123456788), new String("##,###,#")}, "1,2,3,4,5,6,7,8,8");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatDouble() {
+		helpInvokeMethod("formatDouble", new Object[] {new Double(1234.67), new String("####.##")}, "1234.67");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatFloat() {
+		helpInvokeMethod("formatFloat", new Object[] {new Float(1234.67), new String("###.###")}, "1234.67");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeFormatBigInteger() {
+		helpInvokeMethod("formatBigInteger", new Object[] {new BigInteger("45"), new String("###.###")}, "45");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}
+	
+	@Test public void testInvokeFormatBigDecimal() {
+		helpInvokeMethod("formatBigDecimal", new Object[] {new BigDecimal("1234.56"), new String("###.###")}, "1234.56");	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	}	
+
+	@Test public void testInvokeQuarter1() {
+		//		2003-5-15
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 4, 15)}, new Integer(2));	 //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeQuarter2() {
+		//		2003-5-1
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 3, 31)}, new Integer(2));	 //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeQuarter3() {
+		//		2003-1-31
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 0, 31)}, new Integer(1));	 //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeQuarter4() {
+	//		2003-9-30
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 8, 30)}, new Integer(3));	 //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeQuarter5() {
+	//		2003-12-31
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 11, 31)}, new Integer(4));	 //$NON-NLS-1$
+	}		
+	
+	@Test public void testInvokeQuarter6() {
+		//bad date such as 2003-13-45
+		helpInvokeMethod("quarter", new Object[] {TimestampUtil.createDate(103, 12, 45)}, new Integer(1));	 //$NON-NLS-1$
+	}
+	
+	@Test public void testInvokeIfNull() {
+		helpInvokeMethod("ifnull", new Object[] {new Integer(5), new Integer(10)}, new Integer(5));	 //$NON-NLS-1$
+	}
+
+	@Test public void testInvokeLower() {
+		helpInvokeMethod("lower", new Object[] {new String("LOWER")}, new String("lower"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	
+	@Test public void testInvokeUpper() {
+		helpInvokeMethod("upper", new Object[] {new String("upper")}, new String("UPPER"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+
+	@Test public void testInvokeRepeat() {
+		helpInvokeMethod("repeat", new Object[] {new String("cat"), new Integer(3)}, new String("catcatcat"));	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+
+	@Test public void testInvokeChar() {
+		helpInvokeMethod("char", new Object[] {new Integer(32) }, new Character(' ')); //$NON-NLS-1$
+	}
+
+	/** normal input */
+	@Test public void testInvokeInsert1() {
+		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(2), new String("cat")}, new String("Dowcatown"));	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	/** empty string2 */	
+	@Test public void testInvokeInsert2() {
+		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(4),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(2), new String("")}, new String("Dowown"));	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	/** empty string1 with start = 1 and length = 0, so result is just string2 */	
+	@Test public void testInvokeInsert3() {
+		helpInvokeMethod("insert", new Object[] {new String(""), new Integer(1),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(0), new String("cat")}, new String("cat"));	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	/** should fail, with start > string1.length() */
+	@Test public void testInvokeInsert4() throws Exception {
+		helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(2),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(0), new String("cat")}); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	/** should fail, with length > 0 and input string1.length() = 0 */
+	@Test public void testInvokeInsert5() throws Exception {
+		helpInvokeMethodFail("insert", new Object[] {new String(""), new Integer(1),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(1), new String("cat")});	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	/**  (length + start) > string1.length(), then just append str2 starting at start position */
+	@Test public void testInvokeInsert6() {
+		helpInvokeMethod("insert", new Object[] {new String("Downtown"), new Integer(7),  //$NON-NLS-1$ //$NON-NLS-2$
+			new Integer(5), new String("cat")}, new String("Downtocat"));	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+    @Test public void testInvokeTimestampAddDate_ignore_case() {
+        helpInvokeMethod("timestampAdd", new Object[] {"sql_TSI_day",  //$NON-NLS-1$ //$NON-NLS-2$
+            new Integer(28), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 5, 12).getTime()));    
+    }   
+    
+	/** date + month --> count=18, inteval=month, result should be 2004-11-15 */
+	@Test public void testInvokeTimestampAddDate2() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH,  //$NON-NLS-1$
+			new Integer(18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 10, 15).getTime()));	
+	}
+
+	/** date + month --> count=-18, inteval=month, result should be 2001-11-15 */
+	@Test public void testInvokeTimestampAddDate2a() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MONTH,  //$NON-NLS-1$
+			new Integer(-18), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(101, 10, 15).getTime()));	
+	}
+	
+	/** date + week --> count=6, inteval=week, result should be 2003-04-03 */
+	@Test public void testInvokeTimestampAddDate3() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_WEEK,  //$NON-NLS-1$
+			new Integer(-6), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(103, 3, 3).getTime()));	
+	}
+
+	/** date + quarter --> count=3, inteval=quarter, result should be 2004-2-15 */
+	@Test public void testInvokeTimestampAddDate4() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_QUARTER,  //$NON-NLS-1$
+			new Integer(3), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(104, 1, 15).getTime()));	
+	}
+
+	/** date + year --> count=-1, inteval=year, result should be 2002-5-15 */
+	@Test public void testInvokeTimestampAddDate5() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_YEAR,  //$NON-NLS-1$
+			new Integer(-1), new Timestamp(TimestampUtil.createDate(103, 4, 15).getTime())}, new Timestamp(TimestampUtil.createDate(102, 4, 15).getTime()));	
+	}
+			
+	/** time + minute --> count=23, inteval=3, result should be 03:32:12 */
+	@Test public void testInvokeTimestampAddTime1() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_MINUTE,  //$NON-NLS-1$
+			new Integer(23), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 32, 12).getTime()));	
+	}
+
+	/** time + hour --> count=21, inteval=4, result should be 00:09:12 and overflow */
+	@Test public void testInvokeTimestampAddTime2() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
+			new Integer(21), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 0, 9, 12, 0));	
+	}
+
+	/** time + hour --> count=2, inteval=4, result should be 01:12:12*/
+	@Test public void testInvokeTimestampAddTime3() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
+			new Integer(2), new Timestamp(TimestampUtil.createTime(23, 12, 12).getTime())}, TimestampUtil.createTimestamp(70, 0, 2, 1, 12, 12, 0));	
+	}
+	
+	/** time + second --> count=23, inteval=2, result should be 03:10:01 */
+	@Test public void testInvokeTimestampAddTime4() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND,  //$NON-NLS-1$
+			new Integer(49), new Timestamp(TimestampUtil.createTime(3, 9, 12).getTime())}, new Timestamp(TimestampUtil.createTime(3, 10, 1).getTime()));	
+	}
+
+	/** timestamp + second --> count=23, inteval=2, result should be 2003-05-15 03:09:35.100  */
+	@Test public void testInvokeTimestampAddTimestamp1() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_SECOND,  //$NON-NLS-1$
+			new Integer(23), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)}, 
+			TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 35, 100));	
+	}
+
+	/** timestamp + nanos --> count=1, inteval=1, result should be 2003-05-15 03:09:12.000000101  */
+	@Test public void testInvokeTimestampAddTimestamp2() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
+			new Integer(1), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 100)}, 
+			TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 12, 101));	
+	}
+
+	/** timestamp + nanos --> count=2100000000, inteval=1, result should be 2003-05-15 03:10:01.100000003
+	 *  with increase in second and minutes, because second already at 59 sec originally
+	 */
+	@Test public void testInvokeTimestampAddTimestamp3() {
+		helpInvokeMethod("timestampAdd", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
+			new Integer(2100000000), TimestampUtil.createTimestamp(103, 4, 15, 3, 9, 59, 1)}, 
+			TimestampUtil.createTimestamp(103, 4, 15, 3, 10, 1, 100000003));	
+	}
+			
+	/** time --> interval=hour, time1 = 03:04:45, time2= 05:05:36 return = 2  */
+	@Test public void testInvokeTimestampDiffTime1() {
+		helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_HOUR,  //$NON-NLS-1$
+				new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) }, 
+			new Long(2));	
+	}
+	
+    @Test public void testInvokeTimestampDiffTime1_ignorecase() {
+        helpInvokeMethod("timestampDiff", new Object[] {"SQL_tsi_HOUR",  //$NON-NLS-1$ //$NON-NLS-2$
+        		new Timestamp(TimestampUtil.createTime(3, 4, 45).getTime()), new Timestamp(TimestampUtil.createTime(5, 5, 36).getTime()) }, 
+            new Long(2));   
+    }
+    
+	/** 
+	 * timestamp --> interval=week, time1 = 2002-06-21 03:09:35.100,
+	 * time2= 2003-05-02 05:19:35.500 return = 45
+	 */
+	@Test public void testInvokeTimestampDiffTimestamp1() {
+		helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_WEEK,  //$NON-NLS-1$
+			TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100), TimestampUtil.createTimestamp(103, 4, 2, 5, 19, 35, 500) }, 
+			new Long(45));	
+	}
+
+    /** 
+     * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000001,
+     * time2= 2002-06-21 03:09:35.100000000 return = 999999999
+     */
+    @Test public void testInvokeTimestampDiffTimestamp2() {
+        helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
+            TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 1), TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 100000000) }, 
+            new Long(99999999));  
+    }
+
+    /** 
+     * timestamp --> interval=frac_second, time1 = 2002-06-21 03:09:35.000000002,
+     * time2= 2002-06-22 03:09:35.000000001 return = 
+     */
+    @Test public void testInvokeTimestampDiffTimestamp3() {
+        helpInvokeMethod("timestampDiff", new Object[] {NonReserved.SQL_TSI_FRAC_SECOND,  //$NON-NLS-1$
+            TimestampUtil.createTimestamp(102, 5, 21, 3, 9, 35, 2), TimestampUtil.createTimestamp(102, 5, 22, 3, 9, 35, 1) }, 
+            new Long(86399999999999L));  
+    }
+
+    @Test public void testInvokeTimestampCreate1() {
+        helpInvokeMethod("timestampCreate", new Object[] {TimestampUtil.createDate(103, 4, 15), //$NON-NLS-1$
+                                                          TimestampUtil.createTime(23, 59, 59)},
+                                                          TimestampUtil.createTimestamp(103, 4, 15, 23, 59, 59, 0));    
+    }   
+    
+    @Test public void testInvokeBitand() {
+        helpInvokeMethod("bitand", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0x0F0)); //$NON-NLS-1$
+    }
+    @Test public void testInvokeBitor() {
+        helpInvokeMethod("bitor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xFFF)); //$NON-NLS-1$
+    }
+    @Test public void testInvokeBitxor() {
+        helpInvokeMethod("bitxor", new Object[] {new Integer(0xFFF), new Integer(0x0F0)}, new Integer(0xF0F)); //$NON-NLS-1$
+    }
+    @Test public void testInvokeBitnot() {
+        helpInvokeMethod("bitnot", new Object[] {new Integer(0xF0F)}, new Integer(0xFFFFF0F0)); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvokeRound1() {
+        helpInvokeMethod("round", new Object[] {new Integer(123), new Integer(-1)}, new Integer(120)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeRound2() {
+        helpInvokeMethod("round", new Object[] {new Float(123.456), new Integer(2)}, new Float(123.46)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeRound3() {
+        helpInvokeMethod("round", new Object[] {new Double(123.456), new Integer(2)}, new Double(123.46)); //$NON-NLS-1$
+    }
+
+    @Test public void testInvokeRound4() {
+        helpInvokeMethod("round", new Object[] {new BigDecimal("123.456"), new Integer(2)}, new BigDecimal("123.460")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    /** defect 10941 */
+    @Test public void testInvokeConvertTime() {
+        helpInvokeMethod("convert", new Object[] {"05:00:00", "time"}, TimestampUtil.createTime(5, 0, 0)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$                    
+    }
+
+    @Test public void testInvokeXpath1() {
+        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
+                         new Object[] {
+                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>", //$NON-NLS-1$
+                                       "a/b/c"}, //$NON-NLS-1$ 
+                         "test"); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeXpathWithNill() {
+        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
+                         new Object[] {
+                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><b xsi:nil=\"true\"/></a>", //$NON-NLS-1$
+                                       "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$ 
+                         null);
+    }
+    
+    @Test public void testInvokeXpathWithNill1() {
+        helpInvokeMethod("xpathValue",  //$NON-NLS-1$
+                         new Object[] {
+                                       "<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b>value</b></a>", //$NON-NLS-1$
+                                       "//*[local-name()='b' and not(@*[local-name()='nil' and string()='true'])]"}, //$NON-NLS-1$ 
+                         "value"); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvokeModifyTimeZone() {
+        Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
+        Timestamp out = Timestamp.valueOf("2004-10-03 22:59:59.123"); //$NON-NLS-1$
+        helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/Chicago", "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    // TimestampWithTimezone has a static copy the default timezone object which makes this test not execute properly
+    public void defer_testInvokeModifyTimeZoneFromLocal() {
+        Timestamp ts = Timestamp.valueOf("2004-10-03 23:59:59.123"); //$NON-NLS-1$
+        Timestamp out = Timestamp.valueOf("2004-10-03 21:59:59.123"); //$NON-NLS-1$
+        helpInvokeMethod("modifyTimeZone", new Object[] {ts, "America/New_York" }, out); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvokeRand() throws Exception {
+        helpInvokeMethod("rand", new Object[] {new Integer(100)}, new Double(0.7220096548596434)); //$NON-NLS-1$ 
+        // this does not actually fail but returns a result
+        assertNotNull(helpInvokeMethod("rand", new Class[] {Integer.class}, new Object[] {null}, null)); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvokeUser() throws Exception {
+        CommandContext c = new CommandContext();
+        c.setUserName("foodude"); //$NON-NLS-1$
+        helpInvokeMethod("user", new Class[] {}, new Object[] {}, c, "foodude"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvokeEnv() throws Exception {
+        CommandContext c = new CommandContext();
+        Properties props = new Properties();
+        props.setProperty("env_test", "env_value"); //$NON-NLS-1$ //$NON-NLS-2$
+        c.setEnvironmentProperties(props);
+        helpInvokeMethod("env", new Class[] {String.class}, new Object[] {"env_test"}, c, "env_value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$        
+        helpInvokeMethod("env", new Class[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeCommandPayload() throws Exception {
+        CommandContext c = new CommandContext();        
+        c.setCommandPayload("payload_too heavy"); //$NON-NLS-1$
+        helpInvokeMethod("commandpayload", new Class[] {}, new Object[] {}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ 
+        helpInvokeMethod("commandpayload", new Class[] {String.class}, new Object[] {null}, c, null); //$NON-NLS-1$ 
+        Properties props = new Properties();
+        props.setProperty("payload", "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$
+        c.setCommandPayload(props);
+        helpInvokeMethod("commandpayload", new Class[] {String.class}, new Object[] {"payload"}, c, "payload_too heavy"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }    
+    
+    @Test public void testNullDependent() {
+        FunctionDescriptor actual = library.findFunction("concat2", new Class[] {String.class, String.class}); //$NON-NLS-1$
+        assertTrue(actual.isNullDependent());
+        
+        actual = library.findFunction("concat", new Class[] {String.class, String.class}); //$NON-NLS-1$
+        assertFalse(actual.isNullDependent());
+    }
+    
+    @Test public void testInvokeCeiling() {
+        helpInvokeMethod("ceiling", new Object[] { new Double("3.14") }, new Double("4")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeFloor() {
+        helpInvokeMethod("floor", new Object[] { new Double("3.14") }, new Double("3")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeExp() {
+        helpInvokeMethod("exp", new Object[] { new Double("0") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeLog() {
+        helpInvokeMethod("log", new Object[] { new Double("1") }, new Double("0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeLog10() {
+        helpInvokeMethod("log10", new Object[] { new Double("10") }, new Double("1")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeLog10Error() throws Exception {
+        helpInvokeMethodFail("log10", new Object[] { new Double("0") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokePower() {
+        helpInvokeMethod("power", new Object[] { new Double("10"), new Double("2") }, new Double("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    }
+    
+    @Test public void testInvokePower1() {
+        helpInvokeMethod("power", new Object[] { new BigDecimal("10"), new Integer(2) }, new BigDecimal("100")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeSqrt() {
+        helpInvokeMethod("sqrt", new Object[] { new Double("4")}, new Double("2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testInvokeDayName() {
+        for (int i = 0; i < FunctionMethods.dayNames.length; i++) {
+            Date time = TimestampUtil.createDate(100, 0, i + 2);
+            helpInvokeMethod("dayName", new Object[] { time }, FunctionMethods.dayNames[i]); //$NON-NLS-1$ 
+        }
+    }
+    
+    @Test public void testInvokeDayOfMonth() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("dayOfMonth", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeDayOfWeek() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("dayOfWeek", new Object[] { time }, new Integer(7)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeDayOfYear() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 2, 1, 2, 3, 4);
+        helpInvokeMethod("dayOfYear", new Object[] { time }, new Integer(2)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeMonth() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("month", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeMonthName() {
+        for (int i = 0; i < FunctionMethods.monthNames.length; i++) {
+            Date time = TimestampUtil.createDate(100, i, 1);
+            helpInvokeMethod("monthName", new Object[] { time }, FunctionMethods.monthNames[i]); //$NON-NLS-1$ 
+        }
+    }
+    
+    @Test public void testInvokeMinute() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("minute", new Object[] { time }, new Integer(2)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeSecond() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("second", new Object[] { time }, new Integer(3)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeWeek() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("week", new Object[] { time }, new Integer(1)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeYear() {
+        Timestamp time = TimestampUtil.createTimestamp(100, 0, 1, 1, 2, 3, 4);
+        helpInvokeMethod("year", new Object[] { time }, new Integer(2000)); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testInvokeCoalesce() {
+    	helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(2) }, Integer.valueOf(0));
+    }
+    
+    @Test public void testInvokeCoalesce1() {
+    	helpInvokeMethod(FunctionLibrary.COALESCE, new Object[] { null, null}, null);
+    }
+    
+    @Test public void testInvokeNull() throws Exception {
+        helpInvokeMethod(SourceSystemFunctions.LTRIM, new Class[] {DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null }, null, null);  
+    }
+    
+    @Test public void testInvokeNull1() throws Exception {
+        helpInvokeMethod(SourceSystemFunctions.CONCAT, new Class[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING}, new Object[] { null, String.valueOf(1) }, null, null);  
+    }  
+    
+	@Test public void testInvokeXslTransform() throws Exception {
+        CommandContext c = new CommandContext();
+        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+        ClobType result = (ClobType)helpInvokeMethod("xsltransform", new Class[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML}, 
+        		new Object[] {DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML), 
+        		DataTypeManager.transformValue("<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match=\"@*|node()\"><xsl:copy><xsl:apply-templates select=\"@*|node()\"/></xsl:copy></xsl:template><xsl:template match=\"Quantity\"/></xsl:stylesheet>", DataTypeManager.DefaultDataClasses.XML)}, c);
+        
+        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+        assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name></Item></Items></Catalog></Catalogs>", xml);
+    }
+	
+	@Test public void testInvokeXmlConcat() throws Exception {
+        CommandContext c = new CommandContext();
+        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+        XMLType result = (XMLType)helpInvokeMethod("xmlconcat", new Class[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML}, 
+        		new Object[] {DataTypeManager.transformValue("<bar/>", DataTypeManager.DefaultDataClasses.XML), DataTypeManager.transformValue("<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", DataTypeManager.DefaultDataClasses.XML)}, c);
+        
+        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+        assertEquals("<bar/><Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Catalog><Items><Item ItemID=\"001\"><Name>Lamp</Name><Quantity>5</Quantity></Item></Items></Catalog></Catalogs>", xml);
+    }
+	
+	@Test public void testInvokeXmlComment() throws Exception {
+        CommandContext c = new CommandContext();
+        c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+        XMLType result = (XMLType)helpInvokeMethod("xmlcomment", new Class[] {DataTypeManager.DefaultDataClasses.STRING}, 
+        		new Object[] {"comment"}, c);
+        
+        String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+        assertEquals("<!--comment-->", xml);
+    }
+	
+	@Test public void testToChars() throws Exception {
+		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "ASCII" }, null); //$NON-NLS-1$
+		String string = result.getSubString(1, (int)result.length());
+		assertEquals("hello world", string);
+	}
+	
+	@Test public void testToBytes() throws Exception {
+		Blob result = (Blob)helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("hello world".toCharArray())), "UTF32" }, null); //$NON-NLS-1$
+		assertEquals(44, result.length()); //4 bytes / char
+	}
+	
+	@Test public void testToChars1() throws Exception {
+		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "BASE64" }, null); //$NON-NLS-1$
+		String string = result.getSubString(1, (int)result.length());
+		assertEquals("hello world", new String(Base64.decode(string), "ASCII"));
+	}
+	
+	@Test public void testToChars2() throws Exception {
+		Clob result = (Clob)helpInvokeMethod("to_chars", new Class[] {DefaultDataClasses.BLOB, DefaultDataClasses.STRING}, new Object[] { new BlobType(new SerialBlob("hello world".getBytes("ASCII"))), "HEX" }, null); //$NON-NLS-1$
+		String string = result.getSubString(1, (int)result.length());
+		assertEquals("68656C6C6F20776F726C64", string);
+	}
+	
+	@Test public void testToBytes2() throws Exception {
+		Blob result = (Blob)helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("68656C6C6F20776F726C64".toCharArray())), "HEX" }, null); //$NON-NLS-1$
+		assertEquals("hello world", new String(ObjectConverterUtil.convertToCharArray(result.getBinaryStream(), -1, "ASCII")));
+	}
+	
+	@Test(expected=FunctionExecutionException.class) public void testToBytes3() throws Exception {
+		helpInvokeMethod("to_bytes", new Class[] {DefaultDataClasses.CLOB, DefaultDataClasses.STRING}, new Object[] { new ClobType(new SerialClob("a".toCharArray())), "BASE64" }, null); //$NON-NLS-1$
+	}
+	
+	@Test() public void testunescape() throws Exception {
+		assertEquals("\r\t", helpInvokeMethod("unescape", new Class[] {DefaultDataClasses.STRING}, new Object[] { "\r\\\t" }, null)); //$NON-NLS-1$
+	}
+	
+}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionMethods.java (from rev 2764, trunk/engine/src/test/java/org/teiid/query/function/TestFunctionMethods.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionMethods.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/function/TestFunctionMethods.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,40 @@
+/*
+ * 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.function;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+ at SuppressWarnings("nls")
+public class TestFunctionMethods {
+	
+	@Test public void testUnescape() {
+		assertEquals("a\t\n\n%6", FunctionMethods.unescape("a\\t\\n\\012\\456"));
+	}
+	
+	@Test public void testUnescape1() {
+		assertEquals("a\u45AA'", FunctionMethods.unescape("a\\u45Aa\'"));
+	}
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,780 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.optimizer.relational.rules;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.TestOptimizer;
-import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
-import org.teiid.query.optimizer.relational.RelationalPlanner;
-import org.teiid.query.optimizer.relational.plantree.NodeConstants;
-import org.teiid.query.optimizer.relational.plantree.NodeFactory;
-import org.teiid.query.optimizer.relational.plantree.PlanNode;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.TestVirtualDepJoin;
-import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.util.CommandContext;
-
- at SuppressWarnings("nls")
-public class TestCalculateCostUtil {
-
-    // =====================================================================
-    // HELPERS
-    // =====================================================================
-    
-    private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException{
-
-        Criteria result = QueryParser.getQueryParser().parseCriteria(critString);
-        QueryResolver.resolveCriteria(result, metadata);
-        result = QueryRewriter.rewriteCriteria(result, null, new CommandContext(), metadata);
-
-        return result;
-    }
-    
-    private static PlanNode helpGetJoinNode(float childCost1, float childCost2, JoinType joinType){
-        PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
-        PlanNode child1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-        PlanNode child2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
-        
-        joinNode.addLastChild(child1);
-        joinNode.addLastChild(child2);
-        
-        child1.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost1));
-        child2.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost2));
-
-        joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
-        
-        return joinNode;
-    }
-    
-    void helpTestEstimateCost(String critString, float childCost, float expectedResult, QueryMetadataInterface metadata) throws Exception {
-        Criteria crit = helpGetCriteria(critString, metadata);
-        PlanNode select = RelationalPlanner.createSelectNode(crit, false);
-        
-        float resultCost = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(childCost, select, crit, metadata);
-        assertEquals((int)expectedResult, (int)resultCost);
-    }
-    
-    // =====================================================================
-    // TESTS
-    // =====================================================================
-    
-    @Test public void testEstimateCostOfCriteria() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 = '3' or pm2.g3.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-
-    @Test public void testEstimateCostOfCompareCriteria() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 = '3'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);    
-    }  
-    
-    @Test public void testEstimateCostOfCompareCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 < '3'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);    
-    } 
-
-    /**
-     * usesKey = false
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfMatchCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 LIKE '#%'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 100, metadata);
-    }
-
-    /**
-     * usesKey = false
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfMatchCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 NOT LIKE '#_'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 200, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfMatchCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 LIKE '#_'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 50, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfMatchCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 NOT LIKE '#_'"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 249, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfIsNullCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 IS NULL"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 100, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfIsNullCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 IS NOT NULL"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 200, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfIsNullCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 IS NULL"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 1, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfIsNullCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 IS NOT NULL"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 299, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * known child cost = false
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfSetCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * known child cost = false
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfSetCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * known child cost = true
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfSetCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 200, metadata);
-    }
-    
-    /**
-     * usesKey = false
-     * known child cost = true
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfSetCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 300, 100, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * known child cost = false
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfSetCriteria5() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * known child cost = false
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfSetCriteria6() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * known child cost = true
-     * NOT = false
-     */
-    @Test public void testEstimateCostOfSetCriteria7() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 200, 2, metadata);
-    }
-    
-    /**
-     * usesKey = true
-     * known child cost = true
-     * NOT = true
-     */
-    @Test public void testEstimateCostOfSetCriteria8() throws Exception{
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 200, 198, metadata);
-    }
-    
-    @Test public void testEstimateJoinNodeCost() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, JoinType.JOIN_CROSS);
-        
-        float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
-        assertTrue(cost == NewCalculateCostUtil.UNKNOWN_VALUE);
-    }
-    
-    @Ignore("this logic needs to be refined to work better")
-    @Test public void testEstimateJoinNodeCostOneUnknown() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, 500, JoinType.JOIN_INNER);
-        joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, Arrays.asList(helpGetCriteria("pm1.g1.e1 = pm1.g2.e1", metadata)));
-        float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
-        assertEquals(10000, cost, 0);
-    }
-    
-    @Test public void testEstimateNdvPostJoin() throws Exception {
-    	String query = "SELECT account FROM US.Accounts, Europe.CustAccts, CustomerMaster.Customers where account + accid + CustomerMaster.Customers.id = 1000000"; //$NON-NLS-1$
-    	
-    	helpTestQuery(1E9f, query, new String[] {"SELECT g_0.accid FROM Europe.CustAccts AS g_0", "SELECT g_0.id FROM CustomerMaster.Customers AS g_0", "SELECT g_0.account FROM US.Accounts AS g_0"});
-    }
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key 
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 = '3' and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }    
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key, so an OR criteria cannot be
-     * predicted to reduce the cost of the join
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 = '3' or pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }     
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the NOT
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 = '3' and not pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }     
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the 0R
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and not pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }      
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the OR
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey5() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }    
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the OR
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey6() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "(pm4.g1.e1 = '3' and pm4.g1.e2 = 2) or pm4.g1.e4 = 2.0"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    } 
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria covers that
-     * key so the cost should be low
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey8() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }    
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the NOT
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey9() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 NOT LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }    
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria covers that
-     * key so the cost should be low
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey10() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "'3' LIKE pm4.g1.e1 and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }      
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria covers that
-     * key so the cost should be low
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey11() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 IS NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }    
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the NOT
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey12() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 IS NOT NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }      
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria covers that
-     * key so the cost should be low
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey13() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }     
-
-    /** 
-     * cases 2159 and 2160, defect 14998
-     * 
-     * e1 and e2 make up a single compound key - this criteria does not
-     * lower the cost due to the NOT
-     */
-    @Test public void testEstimateCostOfCriteriaCompoundKey14() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 NOT IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    } 
-    
-    @Test public void testEstimateCostOfCriteriaCompoundKey15() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e1 = '2') and (pm4.g1.e2 = 2 or pm4.g1.e2 = 1)"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
-    }
-    
-    /**
-     *  usesKey true
-     */
-    @Test public void testEstimateCostOfCriteriaMultiGroup() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     *  usesKey false
-     */
-    @Test public void testEstimateCostOfCriteriaMultiGroup1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
-    }
-    
-    /**
-     *  usesKey true
-     */
-    @Test public void testEstimateCostOfCriteriaMultiGroup2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 10, metadata);
-    }
-    
-    /**
-     *  usesKey false
-     */
-    @Test public void testEstimateCostOfCriteriaMultiGroup3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
-        String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 33, metadata);
-    }
-    
-    /**
-     *  Date Criteria - Case using valid max and min date strings.  In the case of date,
-     *  the valid strings are timestamp format - since that is what our costing sets them as.
-     */
-    @Test public void testEstimateCostOfCriteriaDate1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
-        String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 100, metadata);
-    }
-
-    /**
-     *  Date Criteria - Case using invalid max and min date strings.  In the case of date,
-     *  one example of invalid strings is date format - since our costing sets them to timestamp.
-     */
-    @Test public void testEstimateCostOfCriteriaDate2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
-        String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 33, metadata);
-    }
-
-    /**
-     *  Time Criteria - case using valid max and min time strings.
-     */
-    @Test public void testEstimateCostOfCriteriaTime1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"12:12:12"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"12:13:14"); //$NON-NLS-1$
-        String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 1, metadata);
-    }
-
-    /**
-     *  Time Criteria - case using invalid max and min time strings
-     */
-    @Test public void testEstimateCostOfCriteriaTime2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
-        String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 33, metadata);
-    }
-    
-    /**
-     *  Timestamp Criteria - case using valid max and min timestamp strings
-     */
-    @Test public void testEstimateCostOfCriteriaTimestamp1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 1, metadata);
-    }
-
-    /**
-     *  Timestamp Criteria - case using invalid max and min timestamp strings
-     */
-    @Test public void testEstimateCostOfCriteriaTimestamp2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
-        String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(critString, 100, 33, metadata);
-    }
-
-    @Test public void testNDVEstimate() throws Exception {
-        String crit = "US.accounts.account = 10"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testNDVEstimate1() throws Exception {
-        String crit = "US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testCompoundCriteriaEstimate() throws Exception {
-        String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 640, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-
-    @Test public void testCompoundCriteriaEstimate1() throws Exception {
-        String crit = "US.accounts.account = 10 or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testNNVEstimate() throws Exception {
-        String crit = "US.accounts.account is null"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testNNVEstimate1() throws Exception {
-        String crit = "US.accounts.account is null"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testCompoundCriteriaEstimate2() throws Exception {
-        String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testCompoundCriteriaEstimate3() throws Exception {
-        String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 801, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    //ensures that the ordering of criteria does not effect the costing calculation
-    @Test public void testCompoundCriteriaEstimate4() throws Exception {
-        String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer and US.accounts.account < 100"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 213, TestVirtualDepJoin.exampleVirtualDepJoin());
-        
-        String crit1 = "US.accounts.account = US.accounts.customer and US.accounts.account < 100 and US.accounts.account = 10"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit1, 1000, 213, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testCompoundCriteriaEstimate5() throws Exception {
-        String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testCompoundCriteriaEstimate6() throws Exception {
-        String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-        
-    //min and max are not set, so the default estimate is returned
-    @Test public void testRangeEstimate() throws Exception {
-        String crit = "US.accounts.account < 100"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 333, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate1() throws Exception {
-        String crit = "US.accounts.customer < 100"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 100, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-
-    @Test public void testRangeEstimate2() throws Exception {
-        String crit = "US.accounts.customer > 100"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 900, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate3() throws Exception {
-        String crit = "US.accounts.customer >= 1600"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate4() throws Exception {
-        String crit = "US.accounts.customer < -1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate5() throws Exception {
-        String crit = "US.accounts.customer >= -1"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate6() throws Exception {
-        String crit = "US.accounts.pennies >= -2"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testRangeEstimate7() throws Exception {
-        String crit = "US.accounts.pennies >= -6"; //$NON-NLS-1$
-        
-        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
-    }
-    
-    @Test public void testLimitWithUnknownChildCardinality() throws Exception {
-        String query = "select e1 from pm1.g1 limit 2"; //$NON-NLS-1$
-        
-        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, FakeMetadataFactory.example1Cached(), new String[] {"SELECT e1 FROM pm1.g1"}); //$NON-NLS-1$
-        
-        assertEquals(new Float(2), plan.getRootNode().getEstimateNodeCardinality());
-    }
-    
-    public void helpTestSetOp(String op, float cost) throws Exception {
-        String query = "SELECT customer as customer_id, convert(account, long) as account_id, convert(txnid, long) as transaction_id, case txn when 'DEP' then 1 when 'TFR' then 2 when 'WD' then 3 else -1 end as txn_type, (pennies + convert('0.00', bigdecimal)) / 100 as amount, 'US' as source FROM US.Accounts where txn != 'X'" +  //$NON-NLS-1$
-        op +  
-        "SELECT id, convert(accid / 10000, long), mod(accid, 10000), convert(type, integer), amount, 'EU' from Europe.CustAccts"; //$NON-NLS-1$
-        
-        String[] expected = new String[] {"SELECT g_0.customer, g_0.account, g_0.txnid, g_0.txn, g_0.pennies FROM US.Accounts AS g_0 WHERE g_0.txn <> 'X'", "SELECT g_0.id, g_0.accid, g_0.type, g_0.amount FROM Europe.CustAccts AS g_0"};
-        
-        helpTestQuery(cost, query, expected);
-    }
-
-	private void helpTestQuery(float cost, String query, String[] expected)
-			throws TeiidComponentException, TeiidProcessingException {
-		RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, TestVirtualDepJoin.exampleVirtualDepJoin(), expected, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        assertEquals(cost, plan.getRootNode().getEstimateNodeCardinality());
-	}
-    
-    @Test public void testUnion() throws Exception {
-    	helpTestSetOp("UNION ", 1375000.0f); //$NON-NLS-1$
-    }
-    
-    @Test public void testUnionALL() throws Exception {
-    	helpTestSetOp("UNION ALL ", 1750000.0f); //$NON-NLS-1$
-    }
-    
-    @Test public void testExcept() throws Exception {
-    	helpTestSetOp("EXCEPT ", 250000.0f); //$NON-NLS-1$
-    }
-    
-    @Test public void testIntersect() throws Exception {
-    	helpTestSetOp("INTERSECT ", 375000.0f); //$NON-NLS-1$
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java (from rev 2775, trunk/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,780 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership.  Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.optimizer.relational.rules;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.NodeFactory;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.TestVirtualDepJoin;
+import org.teiid.query.processor.relational.RelationalPlan;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.JoinType;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings("nls")
+public class TestCalculateCostUtil {
+
+    // =====================================================================
+    // HELPERS
+    // =====================================================================
+    
+    private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException{
+
+        Criteria result = QueryParser.getQueryParser().parseCriteria(critString);
+        QueryResolver.resolveCriteria(result, metadata);
+        result = QueryRewriter.rewriteCriteria(result, null, new CommandContext(), metadata);
+
+        return result;
+    }
+    
+    private static PlanNode helpGetJoinNode(float childCost1, float childCost2, JoinType joinType){
+        PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);
+        PlanNode child1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+        PlanNode child2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
+        
+        joinNode.addLastChild(child1);
+        joinNode.addLastChild(child2);
+        
+        child1.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost1));
+        child2.setProperty(NodeConstants.Info.EST_CARDINALITY, new Float(childCost2));
+
+        joinNode.setProperty(NodeConstants.Info.JOIN_TYPE, joinType);
+        
+        return joinNode;
+    }
+    
+    void helpTestEstimateCost(String critString, float childCost, float expectedResult, QueryMetadataInterface metadata) throws Exception {
+        Criteria crit = helpGetCriteria(critString, metadata);
+        PlanNode select = RelationalPlanner.createSelectNode(crit, false);
+        
+        float resultCost = NewCalculateCostUtil.recursiveEstimateCostOfCriteria(childCost, select, crit, metadata);
+        assertEquals((int)expectedResult, (int)resultCost);
+    }
+    
+    // =====================================================================
+    // TESTS
+    // =====================================================================
+    
+    @Test public void testEstimateCostOfCriteria() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 = '3' or pm2.g3.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+
+    @Test public void testEstimateCostOfCompareCriteria() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 = '3'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);    
+    }  
+    
+    @Test public void testEstimateCostOfCompareCriteria1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 < '3'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);    
+    } 
+
+    /**
+     * usesKey = false
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfMatchCriteria1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 LIKE '#%'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 100, metadata);
+    }
+
+    /**
+     * usesKey = false
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfMatchCriteria2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 NOT LIKE '#_'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 200, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfMatchCriteria3() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 LIKE '#_'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 50, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfMatchCriteria4() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 NOT LIKE '#_'"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 249, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfIsNullCriteria1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 IS NULL"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 100, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfIsNullCriteria2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 IS NOT NULL"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 200, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfIsNullCriteria3() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 IS NULL"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 1, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfIsNullCriteria4() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 IS NOT NULL"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 299, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * known child cost = false
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfSetCriteria1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * known child cost = false
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfSetCriteria2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * known child cost = true
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfSetCriteria3() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 200, metadata);
+    }
+    
+    /**
+     * usesKey = false
+     * known child cost = true
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfSetCriteria4() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 300, 100, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * known child cost = false
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfSetCriteria5() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * known child cost = false
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfSetCriteria6() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * known child cost = true
+     * NOT = false
+     */
+    @Test public void testEstimateCostOfSetCriteria7() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 200, 2, metadata);
+    }
+    
+    /**
+     * usesKey = true
+     * known child cost = true
+     * NOT = true
+     */
+    @Test public void testEstimateCostOfSetCriteria8() throws Exception{
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 200, 198, metadata);
+    }
+    
+    @Test public void testEstimateJoinNodeCost() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, JoinType.JOIN_CROSS);
+        
+        float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
+        assertTrue(cost == NewCalculateCostUtil.UNKNOWN_VALUE);
+    }
+    
+    @Ignore("this logic needs to be refined to work better")
+    @Test public void testEstimateJoinNodeCostOneUnknown() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, 500, JoinType.JOIN_INNER);
+        joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, Arrays.asList(helpGetCriteria("pm1.g1.e1 = pm1.g2.e1", metadata)));
+        float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
+        assertEquals(10000, cost, 0);
+    }
+    
+    @Test public void testEstimateNdvPostJoin() throws Exception {
+    	String query = "SELECT account FROM US.Accounts, Europe.CustAccts, CustomerMaster.Customers where account + accid + CustomerMaster.Customers.id = 1000000"; //$NON-NLS-1$
+    	
+    	helpTestQuery(1E9f, query, new String[] {"SELECT g_0.accid FROM Europe.CustAccts AS g_0", "SELECT g_0.id FROM CustomerMaster.Customers AS g_0", "SELECT g_0.account FROM US.Accounts AS g_0"});
+    }
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key 
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 = '3' and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }    
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key, so an OR criteria cannot be
+     * predicted to reduce the cost of the join
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 = '3' or pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }     
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the NOT
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey3() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 = '3' and not pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }     
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the 0R
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey4() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and not pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }      
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the OR
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey5() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }    
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the OR
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey6() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "(pm4.g1.e1 = '3' and pm4.g1.e2 = 2) or pm4.g1.e4 = 2.0"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    } 
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria covers that
+     * key so the cost should be low
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey8() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }    
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the NOT
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey9() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 NOT LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }    
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria covers that
+     * key so the cost should be low
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey10() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "'3' LIKE pm4.g1.e1 and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }      
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria covers that
+     * key so the cost should be low
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey11() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 IS NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }    
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the NOT
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey12() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 IS NOT NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }      
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria covers that
+     * key so the cost should be low
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey13() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }     
+
+    /** 
+     * cases 2159 and 2160, defect 14998
+     * 
+     * e1 and e2 make up a single compound key - this criteria does not
+     * lower the cost due to the NOT
+     */
+    @Test public void testEstimateCostOfCriteriaCompoundKey14() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 NOT IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    } 
+    
+    @Test public void testEstimateCostOfCriteriaCompoundKey15() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "(pm4.g1.e1 = '3' or pm4.g1.e1 = '2') and (pm4.g1.e2 = 2 or pm4.g1.e2 = 1)"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
+    }
+    
+    /**
+     *  usesKey true
+     */
+    @Test public void testEstimateCostOfCriteriaMultiGroup() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     *  usesKey false
+     */
+    @Test public void testEstimateCostOfCriteriaMultiGroup1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
+    }
+    
+    /**
+     *  usesKey true
+     */
+    @Test public void testEstimateCostOfCriteriaMultiGroup2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 10, metadata);
+    }
+    
+    /**
+     *  usesKey false
+     */
+    @Test public void testEstimateCostOfCriteriaMultiGroup3() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 33, metadata);
+    }
+    
+    /**
+     *  Date Criteria - Case using valid max and min date strings.  In the case of date,
+     *  the valid strings are timestamp format - since that is what our costing sets them as.
+     */
+    @Test public void testEstimateCostOfCriteriaDate1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
+        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
+        String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 100, metadata);
+    }
+
+    /**
+     *  Date Criteria - Case using invalid max and min date strings.  In the case of date,
+     *  one example of invalid strings is date format - since our costing sets them to timestamp.
+     */
+    @Test public void testEstimateCostOfCriteriaDate2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
+        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
+        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
+        String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 33, metadata);
+    }
+
+    /**
+     *  Time Criteria - case using valid max and min time strings.
+     */
+    @Test public void testEstimateCostOfCriteriaTime1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
+        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"12:12:12"); //$NON-NLS-1$
+        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"12:13:14"); //$NON-NLS-1$
+        String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 1, metadata);
+    }
+
+    /**
+     *  Time Criteria - case using invalid max and min time strings
+     */
+    @Test public void testEstimateCostOfCriteriaTime2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
+        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
+        String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 33, metadata);
+    }
+    
+    /**
+     *  Timestamp Criteria - case using valid max and min timestamp strings
+     */
+    @Test public void testEstimateCostOfCriteriaTimestamp1() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
+        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 1, metadata);
+    }
+
+    /**
+     *  Timestamp Criteria - case using invalid max and min timestamp strings
+     */
+    @Test public void testEstimateCostOfCriteriaTimestamp2() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
+        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
+        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
+        String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(critString, 100, 33, metadata);
+    }
+
+    @Test public void testNDVEstimate() throws Exception {
+        String crit = "US.accounts.account = 10"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testNDVEstimate1() throws Exception {
+        String crit = "US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testCompoundCriteriaEstimate() throws Exception {
+        String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 640, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+
+    @Test public void testCompoundCriteriaEstimate1() throws Exception {
+        String crit = "US.accounts.account = 10 or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testNNVEstimate() throws Exception {
+        String crit = "US.accounts.account is null"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testNNVEstimate1() throws Exception {
+        String crit = "US.accounts.account is null"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testCompoundCriteriaEstimate2() throws Exception {
+        String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testCompoundCriteriaEstimate3() throws Exception {
+        String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 801, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    //ensures that the ordering of criteria does not effect the costing calculation
+    @Test public void testCompoundCriteriaEstimate4() throws Exception {
+        String crit = "US.accounts.account = 10 and US.accounts.account = US.accounts.customer and US.accounts.customer < 100"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
+        
+        String crit1 = "US.accounts.account = US.accounts.customer and US.accounts.customer < 100 and US.accounts.account = 10"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit1, 1000, 64, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testCompoundCriteriaEstimate5() throws Exception {
+        String crit = "US.accounts.account is null and US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testCompoundCriteriaEstimate6() throws Exception {
+        String crit = "US.accounts.account is null or US.accounts.account = US.accounts.customer"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+        
+    //min and max are not set, so the default estimate is returned
+    @Test public void testRangeEstimate() throws Exception {
+        String crit = "US.accounts.account < 100"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 333, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate1() throws Exception {
+        String crit = "US.accounts.customer < 100"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 100, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+
+    @Test public void testRangeEstimate2() throws Exception {
+        String crit = "US.accounts.customer > 100"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 900, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate3() throws Exception {
+        String crit = "US.accounts.customer >= 1600"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate4() throws Exception {
+        String crit = "US.accounts.customer < -1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate5() throws Exception {
+        String crit = "US.accounts.customer >= -1"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate6() throws Exception {
+        String crit = "US.accounts.pennies >= -2"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 1000, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testRangeEstimate7() throws Exception {
+        String crit = "US.accounts.pennies >= -6"; //$NON-NLS-1$
+        
+        helpTestEstimateCost(crit, 1000, 800, TestVirtualDepJoin.exampleVirtualDepJoin());
+    }
+    
+    @Test public void testLimitWithUnknownChildCardinality() throws Exception {
+        String query = "select e1 from pm1.g1 limit 2"; //$NON-NLS-1$
+        
+        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, FakeMetadataFactory.example1Cached(), new String[] {"SELECT e1 FROM pm1.g1"}); //$NON-NLS-1$
+        
+        assertEquals(new Float(2), plan.getRootNode().getEstimateNodeCardinality());
+    }
+    
+    public void helpTestSetOp(String op, float cost) throws Exception {
+        String query = "SELECT customer as customer_id, convert(account, long) as account_id, convert(txnid, long) as transaction_id, case txn when 'DEP' then 1 when 'TFR' then 2 when 'WD' then 3 else -1 end as txn_type, (pennies + convert('0.00', bigdecimal)) / 100 as amount, 'US' as source FROM US.Accounts where txn != 'X'" +  //$NON-NLS-1$
+        op +  
+        "SELECT id, convert(accid / 10000, long), mod(accid, 10000), convert(type, integer), amount, 'EU' from Europe.CustAccts"; //$NON-NLS-1$
+        
+        String[] expected = new String[] {"SELECT g_0.customer, g_0.account, g_0.txnid, g_0.txn, g_0.pennies FROM US.Accounts AS g_0 WHERE g_0.txn <> 'X'", "SELECT g_0.id, g_0.accid, g_0.type, g_0.amount FROM Europe.CustAccts AS g_0"};
+        
+        helpTestQuery(cost, query, expected);
+    }
+
+	private void helpTestQuery(float cost, String query, String[] expected)
+			throws TeiidComponentException, TeiidProcessingException {
+		RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, TestVirtualDepJoin.exampleVirtualDepJoin(), expected, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        assertEquals(cost, plan.getRootNode().getEstimateNodeCardinality());
+	}
+    
+    @Test public void testUnion() throws Exception {
+    	helpTestSetOp("UNION ", 1375000.0f); //$NON-NLS-1$
+    }
+    
+    @Test public void testUnionALL() throws Exception {
+    	helpTestSetOp("UNION ALL ", 1750000.0f); //$NON-NLS-1$
+    }
+    
+    @Test public void testExcept() throws Exception {
+    	helpTestSetOp("EXCEPT ", 250000.0f); //$NON-NLS-1$
+    }
+    
+    @Test public void testIntersect() throws Exception {
+    	helpTestSetOp("INTERSECT ", 375000.0f); //$NON-NLS-1$
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,274 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.processor;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.Executor;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.dqp.internal.process.CachedResults;
-import org.teiid.dqp.internal.process.SessionAwareCache;
-import org.teiid.metadata.FunctionMethod.Determinism;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.tempdata.TempTableDataManager;
-import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.util.CommandContext;
-
- at SuppressWarnings({"nls", "unchecked"})
-public class TestTempTables {
-	
-	private TempMetadataAdapter metadata;
-	private TempTableDataManager dataManager;
-	private TempTableStore tempStore;
-	
-	private void execute(String sql, List[] expectedResults) throws Exception {
-		execute(TestProcessor.helpGetPlan(sql, metadata), expectedResults);
-	}
-	
-	private void execute(ProcessorPlan processorPlan, List[] expectedResults) throws Exception {
-		CommandContext cc = TestProcessor.createCommandContext();
-		cc.setTempTableStore(tempStore);
-		TestProcessor.doProcess(processorPlan, dataManager, expectedResults, cc);
-		assertTrue(Determinism.SESSION_DETERMINISTIC.isRestrictiveThanOrEqual(cc.getDeterminismLevel()));
-	}
-
-	@Before public void setUp() {
-		tempStore = new TempTableStore("1"); //$NON-NLS-1$
-		metadata = new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), tempStore.getMetadataStore());
-		FakeDataManager fdm = new FakeDataManager();
-	    TestProcessor.sampleData1(fdm);
-	    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
-	    SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
-	    cache.setBufferManager(bm);
-	    Executor executor = new Executor() {
-			@Override
-			public void execute(Runnable command) {
-				command.run();
-			}
-	    };
-		dataManager = new TempTableDataManager(fdm, bm, executor, cache, null, null);
-	}
-	
-	@Test public void testInsertWithQueryExpression() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) select e2, e1 from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
-		execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testOutofOrderInsert() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select e1, e2 from x", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testUpdate() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
-		execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
-		execute("select e1 from x where e2 > 0 order by e1", new List[] { //$NON-NLS-1$
-				Arrays.asList((String)null),
-				Arrays.asList("2"), //$NON-NLS-1$
-				Arrays.asList("3"), //$NON-NLS-1$
-				Arrays.asList("c"), //$NON-NLS-1$
-				Arrays.asList("one")}); //$NON-NLS-1$
-	}
-	
-	@Test public void testDelete() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
-		execute("delete from x where ascii(e1) > e2", new List[] {Arrays.asList(5)}); //$NON-NLS-1$
-		execute("select e1 from x order by e1", new List[] {Arrays.asList((String)null)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testDelete1() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
-		execute("delete from x", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
-		execute("select e1 from x order by e1", new List[] {}); //$NON-NLS-1$
-	}
-	
-	@Test(expected=TeiidProcessingException.class) public void testDuplicatePrimaryKey() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testAtomicUpdate() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		try {
-			execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		} catch (TeiidProcessingException e) {
-			//should be a duplicate key
-		}
-		//should revert back to original
-		execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testAtomicDelete() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		try {
-			execute("delete from x where 1/(e2 - 2) <> 4", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		} catch (TeiidProcessingException e) {
-			//should be a duplicate key
-		}
-		//should revert back to original
-		execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testPrimaryKeyMetadata() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		Collection c = metadata.getUniqueKeysInGroup(metadata.getGroupID("x"));
-		assertEquals(1, c.size());
-		assertEquals(1, (metadata.getElementIDsInKey(c.iterator().next()).size()));
-	}
-	
-	@Test public void testProjection() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e2 = 1", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
-		execute("select e2, e1 from x where e2 = 1", new List[] {Arrays.asList(1, "one")}); //$NON-NLS-1$
-	}
-	
-	@Test public void testOrderByWithIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x as y order by e2 desc", new List[] {Arrays.asList("one", 3), Arrays.asList("one", 2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testOrderByWithoutIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x order by e1", new List[] {Arrays.asList("a", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompareEqualsWithIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e2 = 3", new List[] {Arrays.asList("a", 3)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testLikeWithIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e1 like 'z%'", new List[0]); //$NON-NLS-1$
-	}
-	
-	@Test public void testIsNullWithIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, null)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e1 is null", new List[] {Arrays.asList(null, 3)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testInWithIndex() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (-1, 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e1 in ('a', 'c', 'e', 'f', 'g')", new List[] {Arrays.asList("a", 3), Arrays.asList("c", 1), Arrays.asList("e", -1)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testInWithIndexUpdate() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, e3 string, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1, e3) values (-1, 'e', 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("update x set e2 = 5 where e1 in ('a', 'c')", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
-		execute("select * from x where e1 in ('b', e3)", new List[] {Arrays.asList("b", 2, null), Arrays.asList("e", -1, "e")}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyCompareEquals() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("select * from x where e1 = 'b' and e2 = 2", new List[] {Arrays.asList("b", 2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial() throws Exception {
-		sampleTable();
-		execute("select * from x where e1 = 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial1() throws Exception {
-		sampleTable();
-		execute("select * from x where e1 < 'c'", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial2() throws Exception {
-		sampleTable();
-		execute("select * from x where e2 = 1", new List[] {Arrays.asList("a", 1), Arrays.asList("c", 1)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial3() throws Exception {
-		sampleTable();
-		execute("select * from x where e1 >= 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3), Arrays.asList("c", 1)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial4() throws Exception {
-		sampleTable();
-		execute("select * from x where e1 >= 'b' order by e1 desc, e2 desc", new List[] {Arrays.asList("c", 1), Arrays.asList("b", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial5() throws Exception {
-		sampleTable();
-		execute("select * from x where e1 in ('a', 'b')", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
-	}
-	
-	@Test public void testCompositeKeyPartial6() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("select * from x where e1 in ('a', 'b') order by e1 desc", new List[0]); //$NON-NLS-1$
-	}
-
-	private void sampleTable() throws Exception {
-		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (3, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-		execute("insert into x (e2, e1) values (1, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java (from rev 2762, trunk/engine/src/test/java/org/teiid/query/processor/TestTempTables.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.query.processor;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.dqp.internal.process.CachedResults;
+import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.tempdata.TempTableDataManager;
+import org.teiid.query.tempdata.TempTableStore;
+import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.util.CommandContext;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestTempTables {
+	
+	private TempMetadataAdapter metadata;
+	private TempTableDataManager dataManager;
+	private TempTableStore tempStore;
+	
+	private void execute(String sql, List[] expectedResults) throws Exception {
+		execute(TestProcessor.helpGetPlan(sql, metadata), expectedResults);
+	}
+	
+	private void execute(ProcessorPlan processorPlan, List[] expectedResults) throws Exception {
+		CommandContext cc = TestProcessor.createCommandContext();
+		cc.setTempTableStore(tempStore);
+		TestProcessor.doProcess(processorPlan, dataManager, expectedResults, cc);
+		assertTrue(Determinism.SESSION_DETERMINISTIC.compareTo(cc.getDeterminismLevel()) <= 0);
+	}
+
+	@Before public void setUp() {
+		tempStore = new TempTableStore("1"); //$NON-NLS-1$
+		metadata = new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), tempStore.getMetadataStore());
+		FakeDataManager fdm = new FakeDataManager();
+	    TestProcessor.sampleData1(fdm);
+	    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
+	    SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>();
+	    cache.setBufferManager(bm);
+	    Executor executor = new Executor() {
+			@Override
+			public void execute(Runnable command) {
+				command.run();
+			}
+	    };
+		dataManager = new TempTableDataManager(fdm, bm, executor, cache, null, null);
+	}
+	
+	@Test public void testInsertWithQueryExpression() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) select e2, e1 from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+		execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testOutofOrderInsert() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select e1, e2 from x", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testUpdate() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+		execute("update x set e1 = e2 where e2 > 1", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+		execute("select e1 from x where e2 > 0 order by e1", new List[] { //$NON-NLS-1$
+				Arrays.asList((String)null),
+				Arrays.asList("2"), //$NON-NLS-1$
+				Arrays.asList("3"), //$NON-NLS-1$
+				Arrays.asList("c"), //$NON-NLS-1$
+				Arrays.asList("one")}); //$NON-NLS-1$
+	}
+	
+	@Test public void testDelete() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+		execute("delete from x where ascii(e1) > e2", new List[] {Arrays.asList(5)}); //$NON-NLS-1$
+		execute("select e1 from x order by e1", new List[] {Arrays.asList((String)null)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testDelete1() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("select e1, e2 into x from pm1.g1", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+		execute("delete from x", new List[] {Arrays.asList(6)}); //$NON-NLS-1$
+		execute("select e1 from x order by e1", new List[] {}); //$NON-NLS-1$
+	}
+	
+	@Test(expected=TeiidProcessingException.class) public void testDuplicatePrimaryKey() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testAtomicUpdate() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		try {
+			execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		} catch (TeiidProcessingException e) {
+			//should be a duplicate key
+		}
+		//should revert back to original
+		execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testAtomicDelete() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		try {
+			execute("delete from x where 1/(e2 - 2) <> 4", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		} catch (TeiidProcessingException e) {
+			//should be a duplicate key
+		}
+		//should revert back to original
+		execute("select count(*) from x", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testPrimaryKeyMetadata() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		Collection c = metadata.getUniqueKeysInGroup(metadata.getGroupID("x"));
+		assertEquals(1, c.size());
+		assertEquals(1, (metadata.getElementIDsInKey(c.iterator().next()).size()));
+	}
+	
+	@Test public void testProjection() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e2 = 1", new List[] {Arrays.asList("one", 1)}); //$NON-NLS-1$
+		execute("select e2, e1 from x where e2 = 1", new List[] {Arrays.asList(1, "one")}); //$NON-NLS-1$
+	}
+	
+	@Test public void testOrderByWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x as y order by e2 desc", new List[] {Arrays.asList("one", 3), Arrays.asList("one", 2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testOrderByWithoutIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x order by e1", new List[] {Arrays.asList("a", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompareEqualsWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e2 = 3", new List[] {Arrays.asList("a", 3)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testLikeWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e1 like 'z%'", new List[0]); //$NON-NLS-1$
+	}
+	
+	@Test public void testIsNullWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, null)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e1 is null", new List[] {Arrays.asList(null, 3)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testInWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (-1, 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e1 in ('a', 'c', 'e', 'f', 'g')", new List[] {Arrays.asList("a", 3), Arrays.asList("c", 1), Arrays.asList("e", -1)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testInWithIndexUpdate() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, e3 string, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (0, 'd')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1, e3) values (-1, 'e', 'e')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("update x set e2 = 5 where e1 in ('a', 'c')", new List[] {Arrays.asList(2)}); //$NON-NLS-1$
+		execute("select * from x where e1 in ('b', e3)", new List[] {Arrays.asList("b", 2, null), Arrays.asList("e", -1, "e")}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyCompareEquals() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e1 = 'b' and e2 = 2", new List[] {Arrays.asList("b", 2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial() throws Exception {
+		sampleTable();
+		execute("select * from x where e1 = 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial1() throws Exception {
+		sampleTable();
+		execute("select * from x where e1 < 'c'", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial2() throws Exception {
+		sampleTable();
+		execute("select * from x where e2 = 1", new List[] {Arrays.asList("a", 1), Arrays.asList("c", 1)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial3() throws Exception {
+		sampleTable();
+		execute("select * from x where e1 >= 'b'", new List[] {Arrays.asList("b", 2), Arrays.asList("b", 3), Arrays.asList("c", 1)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial4() throws Exception {
+		sampleTable();
+		execute("select * from x where e1 >= 'b' order by e1 desc, e2 desc", new List[] {Arrays.asList("c", 1), Arrays.asList("b", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial5() throws Exception {
+		sampleTable();
+		execute("select * from x where e1 in ('a', 'b')", new List[] {Arrays.asList("a", 1), Arrays.asList("b", 2), Arrays.asList("b", 3)}); //$NON-NLS-1$
+	}
+	
+	@Test public void testCompositeKeyPartial6() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("select * from x where e1 in ('a', 'b') order by e1 desc", new List[0]); //$NON-NLS-1$
+	}
+
+	private void sampleTable() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1, e2))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'c')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (1, 'a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,11801 +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 static org.junit.Assert.*;
-
-import java.io.ByteArrayOutputStream;
-import java.io.FileInputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryPlannerException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingChoiceNode;
-import org.teiid.query.mapping.xml.MappingCommentNode;
-import org.teiid.query.mapping.xml.MappingCriteriaNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingNode;
-import org.teiid.query.mapping.xml.MappingNodeConstants;
-import org.teiid.query.mapping.xml.MappingRecursiveElement;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.mapping.xml.Namespace;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.QueryOptimizer;
-import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
-import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.xml.TestXMLPlanner;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.processor.BatchCollector;
-import org.teiid.query.processor.FakeDataManager;
-import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.processor.QueryProcessor;
-import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.rewriter.QueryRewriter;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.ElementSymbol;
-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.util.CommandContext;
-
-
-/**
- * Tests XML processing, which involves XMLPlanner making a ProcessorPlan
- * (XMLPlan) from a mapping document (tree of MappingNode objects) and
- * metadata, and then that XMLPlan being processed with metadata, a 
- * ProcessorDataManager and a QueryProcessor.
- */
- at SuppressWarnings("nls")
-public class TestXMLProcessor {
-    private static final boolean DEBUG = false;
-    
-    /**
-     * Construct some fake metadata.  Basic conceptual tree is:
-     * 
-     * stock (physical model)
-     *   items (physical group)
-     *     itemNum (string)
-     *     itemName (string)
-     *     itemQuantity (integer)
-     * xmltest (virtual model)
-     *   rs (virtual group / result set definition)
-     *     itemNum (string)
-     *     itemName (string)
-     *     itemQuantity (integer)
-     */
-    public static FakeMetadataFacade exampleMetadataCached() {
-        return EXAMPLE_CACHED;
-    } 
-    
-    private static final FakeMetadataFacade EXAMPLE_CACHED = exampleMetadata();
-    
-    public static FakeMetadataFacade exampleMetadata() {
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
-        
-        // Create models
-        FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
-        FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
-
-        FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
-        FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
-        FakeMetadataObject employees = FakeMetadataFactory.createPhysicalGroup("stock.employees", stock); //$NON-NLS-1$
-             
-        // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(items, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        //many-to-many join table
-        List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
-            new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-        List supplierElements = FakeMetadataFactory.createElements(suppliers, 
-            new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List stockOrders = FakeMetadataFactory.createElements(orders, 
-            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List supplierEmployees = FakeMetadataFactory.createElements(employees, 
-            new String[] { "employeeNum", "supplierNumFK", "supervisorNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-
-        
-// ======================================================================================================================
-
-        // Create virtual groups
-        // per defect 6829 - intentionally including the reserved word "group" as part of this virtual group name
-        QueryNode rsQuery = new QueryNode("xmltest.group.items", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery); //$NON-NLS-1$
-
-        // Created 2nd virtual group w/ nested result set & binding
-        QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        //QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT stock.suppliers.supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?");
-        rsQuery2.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
-
-        // Created virtual group w/ nested result set & binding
-        QueryNode rsQuery3 = new QueryNode("xmltest.orders", "SELECT orderNum, orderDate, orderQty, orderStatus FROM stock.orders WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        rsQuery3.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
-        rsQuery3.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
-
-
-// ======================================================================================================================
-
-        //create employees - not connected to any of the above
-        QueryNode rsEmployees = new QueryNode("xmltest.employees", "SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xmltest.employees", xmltest, rsEmployees); //$NON-NLS-1$
-
-        //recursive piece
-        QueryNode rsEmployeesRecursive = new QueryNode("xmltest.employeesRecursive", "SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsEmployeesRecursive.addBinding("xmltest.employees.employeeNum"); //$NON-NLS-1$
-        FakeMetadataObject rs4a = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursive", xmltest, rsEmployeesRecursive); //$NON-NLS-1$
-
-// ======================================================================================================================
-
-        //create employees - not connected to any of the above
-        QueryNode rsEmployees2 = new QueryNode("xmltest.employees2", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE supplierNumFK = '2' AND NOT (supervisorNum IS NULL)"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xmltest.employees2", xmltest, rsEmployees2); //$NON-NLS-1$
-
-        //recursive piece
-        QueryNode rsEmployees2Recursive = new QueryNode("xmltest.employees2Recursive", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsEmployees2Recursive.addBinding("xmltest.employees2.supervisorNum"); //$NON-NLS-1$
-        FakeMetadataObject rs5a = FakeMetadataFactory.createVirtualGroup("xmltest.employees2Recursive", xmltest, rsEmployees2Recursive); //$NON-NLS-1$
-
-//      ======================================================================================================================
-// Alternate mapping class which selects from stored query
-
-        // Created 2nd virtual group w/ nested result set & binding
-        QueryNode rsQueryX = new QueryNode("xmltest.suppliersX", "SELECT * FROM (exec xmltest.sqX(?)) as X"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQueryX.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        FakeMetadataObject rsQX = FakeMetadataFactory.createVirtualGroup("xmltest.suppliersX", xmltest, rsQueryX); //$NON-NLS-1$
-
-// ======================================================================================================================
-// ALTERNATE METADATA A (temp groups)
-
-        // root temp group
-        QueryNode tempQuery = new QueryNode("tempGroup.orders", "SELECT * FROM stock.orders"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject temp = FakeMetadataFactory.createVirtualGroup("tempGroup.orders", xmltest, tempQuery); //$NON-NLS-1$
-
-        // 2nd bogus root temp group selects from first - tests that temp groups can select from others
-        QueryNode tempQuery2 = new QueryNode("tempGroup.orders2", "SELECT * FROM tempGroup.orders"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject temp2 = FakeMetadataFactory.createVirtualGroup("tempGroup.orders2", xmltest, tempQuery2); //$NON-NLS-1$
-        
-        // Created virtual group w/ nested result set & binding - selects from 2nd temp root group
-        QueryNode rsQuery3a = new QueryNode("xmltest.ordersA", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery3a.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        rsQuery3a.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
-        rsQuery3a.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject rs3a = FakeMetadataFactory.createVirtualGroup("xmltest.ordersA", xmltest, rsQuery3a); //$NON-NLS-1$
-
-// ======================================================================================================================
-// ALTERNATE METADATA B (temp groups)
-
-        //temp group selects from root temp group and it has bindings to other mapping classes
-        // from 5.5 bindings are not supported in the staging tables. even before we did not supported 
-        // them in the modeler; but we did in execution; now we remove it as it poses more issues.
-        QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        tempQuery3b.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        tempQuery3b.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
-        tempQuery3b.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b); //$NON-NLS-1$
-        
-        // Created virtual group w/ nested result set & binding
-        QueryNode rsQuery3b = new QueryNode("xmltest.ordersB", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rsQuery3b); //$NON-NLS-1$
-
-
-// ======================================================================================================================
-// ALTERNATE METADATA C (temp group with union)
-
-//        //temp group selects from root temp group and it has bindings to other mapping classes
-//        QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?");
-//        tempQuery3b.addBinding("xmltest.group.items.itemNum");
-//        tempQuery3b.addBinding("xmltest.suppliers.supplierNum");
-//        tempQuery3b.addBinding("xmltest.suppliers.supplierName");
-//        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b);
-//        
-//        // Created virtual group w/ nested result set & binding
-//        QueryNode rsQuery3b = new QueryNode("xmltest.ordersB", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B");
-//        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rs   Query3b);
-
-// ======================================================================================================================
-
-// ======================================================================================================================
-// ALTERNATE METADATA D (correlated subquery in mapping class)
-       // Create virtual groups
-       // per defect 12260 - correlated subquery in mapping class transformation
-       QueryNode rsQuery12260 = new QueryNode("xmltest.group.itemsWithNumSuppliers", "SELECT itemNum, itemName, itemQuantity, itemStatus, convert((select count(*) from stock.item_supplier where stock.items.itemNum = stock.item_supplier.itemNum), string) as NUMSuppliers FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs12260 = FakeMetadataFactory.createVirtualGroup("xmltest.group.itemsWithNumSuppliers", xmltest, rsQuery12260); //$NON-NLS-1$
-
-       List rsElements12260 = FakeMetadataFactory.createElements(rs12260, 
-           new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus", "numSuppliers" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-           new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });        
-    
-// ======================================================================================================================
-// ALTERNATE METADATA E (mapping class w/ Union)
-       // Create virtual groups
-       // per defect 8373
-       QueryNode rsQuery8373 = new QueryNode("xmltest.items8373", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items UNION ALL SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373 = FakeMetadataFactory.createVirtualGroup("xmltest.items8373", xmltest, rsQuery8373); //$NON-NLS-1$
-
-       List rsElements8373 = FakeMetadataFactory.createElements(rs8373, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
-
-       //select * from xmltest.items8373
-       QueryNode rsQuery8373a = new QueryNode("xmltest.items8373a", "SELECT * FROM xmltest.items8373"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373a = FakeMetadataFactory.createVirtualGroup("xmltest.items8373a", xmltest, rsQuery8373a); //$NON-NLS-1$
-
-       List rsElements8373a = FakeMetadataFactory.createElements(rs8373a, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
-
-       QueryNode rsQuery8373b = new QueryNode("xmltest.items8373b", "SELECT * FROM xmltest.group.items UNION ALL SELECT * FROM xmltest.group.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373b = FakeMetadataFactory.createVirtualGroup("xmltest.items8373b", xmltest, rsQuery8373b); //$NON-NLS-1$
-
-       List rsElements8373b = FakeMetadataFactory.createElements(rs8373b, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
-       
-// ======================================================================================================================
-
-
-        // Test an update query as a mapping class transformation, as if it were a 
-        // mapping class returning a single int - defect 8812
-        QueryNode rsUpdateQuery = new QueryNode("xmltest.updateTest", "INSERT INTO stock.items (itemNum, itemName, itemQuantity, itemStatus) VALUES ('3','beer',12,'something')"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsUpdate = FakeMetadataFactory.createVirtualGroup("xmltest.updateTest", xmltest, rsUpdateQuery); //$NON-NLS-1$
-
-        // Create virtual elements
-        List rsElements = FakeMetadataFactory.createElements(rs, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
-
-
-        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
-            new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
-            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
-            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements4a = FakeMetadataFactory.createElements(rs4a, 
-            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
-            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements5a = FakeMetadataFactory.createElements(rs5a, 
-            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List tempElements = FakeMetadataFactory.createElements(temp, 
-            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List tempElements2 = FakeMetadataFactory.createElements(temp2, 
-            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements3a = FakeMetadataFactory.createElements(rs3a, 
-            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List tempElements3b = FakeMetadataFactory.createElements(temp3b, 
-            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsElements3b = FakeMetadataFactory.createElements(rs3b, 
-            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsUpdateElement = FakeMetadataFactory.createElements(rsUpdate, 
-            new String[] { "rowCount" }, //$NON-NLS-1$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER});
-
-        List rsElementsX = FakeMetadataFactory.createElements(rsQX, 
-            new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-       
-        // Create virtual docs
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xmltest.doc1", xmltest, createXMLMappingNode(true)); //$NON-NLS-1$
-        List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-            
-        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xmltest.doc1Unformatted", xmltest, createXMLMappingNode(false)); //$NON-NLS-1$
-        FakeMetadataObject doc1b = FakeMetadataFactory.createVirtualGroup("xmltest.doc1b", xmltest, createXMLPlan2(false, true, 0 )); //$NON-NLS-1$
-        List docE1b = FakeMetadataFactory.createElements(doc1b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        FakeMetadataObject doc1c = FakeMetadataFactory.createVirtualGroup("xmltest.doc1c", xmltest, createXMLPlan2(false, true, 1 )); //$NON-NLS-1$
-        List docE1c = FakeMetadataFactory.createElements(doc1c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        
-        FakeMetadataObject docBounded = FakeMetadataFactory.createVirtualGroup("xmltest.docBounded", xmltest, createXMLMappingBoundingNode()); //$NON-NLS-1$
-        List docBoundedElements = FakeMetadataFactory.createElements(docBounded, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        
-
-        FakeMetadataObject doc2  = FakeMetadataFactory.createVirtualGroup("xmltest.doc2",  xmltest, createXMLPlan2(1, -1, false)); //$NON-NLS-1$
-        List docE2 = FakeMetadataFactory.createElements(doc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc2a = FakeMetadataFactory.createVirtualGroup("xmltest.doc2a", xmltest, createXMLPlan2(1, 1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2b = FakeMetadataFactory.createVirtualGroup("xmltest.doc2b", xmltest, createXMLPlan2(1, -1, true)); //$NON-NLS-1$
-        FakeMetadataObject doc2c = FakeMetadataFactory.createVirtualGroup("xmltest.doc2c", xmltest, createXMLPlan2(2, -1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2d = FakeMetadataFactory.createVirtualGroup("xmltest.doc2d", xmltest, createXMLPlan2(2, 1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2e = FakeMetadataFactory.createVirtualGroup("xmltest.doc2e", xmltest, createXMLPlan2(2, 3, false)); //$NON-NLS-1$
-
-        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xmltest.doc3", xmltest, createXMLPlanWithDefaults()); //$NON-NLS-1$
-        List docE3 = FakeMetadataFactory.createElements(doc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xmltest.doc4", xmltest, createXMLPlanAdvanced()); //$NON-NLS-1$
-        List docE4 = FakeMetadataFactory.createElements(doc4, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Fake", "Catalogs.Fake.FakeChild2", "Catalogs.Fake.FakeChild2.FakeChild2a", "Catalogs.Fake.FakeChild3", "Catalogs.Fake.FakeChild3. at FakeAtt" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER,DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xmltest.doc5", xmltest, createXMLPlanUltraAdvanced()); //$NON-NLS-1$
-        List docE5 = FakeMetadataFactory.createElements(doc5, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc6 = FakeMetadataFactory.createVirtualGroup("xmltest.doc6", xmltest, createXMLPlanUltraAdvancedExceptionOnDefault()); //$NON-NLS-1$
-        List docE6 = FakeMetadataFactory.createElements(doc6, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.Shouldn't see"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc7 = FakeMetadataFactory.createVirtualGroup("xmltest.doc7", xmltest, createTestAttributePlan()); //$NON-NLS-1$
-        List docE7 = FakeMetadataFactory.createElements(doc7, new String[] { "FixedValueTest", "FixedValueTest.wrapper", "FixedValueTest.wrapper. at fixed", "FixedValueTest.wrapper. at key", "FixedValueTest.wrapper. at fixedAttr"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-                        
-        FakeMetadataObject doc8 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8", xmltest, createXMLPlanNested()); //$NON-NLS-1$
-        List docE8 = FakeMetadataFactory.createElements(doc8, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-    
-        FakeMetadataObject doc9 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9", xmltest, createXMLPlanNested2()); //$NON-NLS-1$
-        List docE9 = FakeMetadataFactory.createElements(doc9, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$!
  //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-            
-        FakeMetadataObject doc9a = FakeMetadataFactory.createVirtualGroup("xmltest.doc9a", xmltest, createXMLPlanNested2a()); //$NON-NLS-1$
-        List docE9a = FakeMetadataFactory.createElements(doc9a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-!
 2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc9b = FakeMetadataFactory.createVirtualGroup("xmltest.doc9b", xmltest, createXMLPlanNested2b()); //$NON-NLS-1$
-        FakeMetadataObject doc10 = FakeMetadataFactory.createVirtualGroup("xmltest.doc10", xmltest, createXMLPlanNestedWithChoice()); //$NON-NLS-1$
-        List docE10 = FakeMetadataFactory.createElements(doc10, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.Pro!
 cessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc10L = FakeMetadataFactory.createVirtualGroup("xmltest.doc10L", xmltest, createXMLPlanNestedWithLookupChoice()); //$NON-NLS-1$
-        List docE10L = FakeMetadataFactory.createElements(doc10L, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.P!
 rocessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-
-        FakeMetadataObject doc11 = FakeMetadataFactory.createVirtualGroup("xmltest.doc11", xmltest, createXMLPlanMultipleDocs()); //$NON-NLS-1$
-        List docE11 = FakeMetadataFactory.createElements(doc11, new String[] { "Item", "Item. at ItemID", "Item.Name", "Item.Quantity", "Item.Suppliers", "Item.Suppliers.Supplier", "Item.Suppliers.Supplier. at SupplierID", "Item.Suppliers.Supplier.Name", "Item.Suppliers.Supplier.Zip"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        //variations on the same recursive doc====================
-        boolean useRecursiveCriteria = false;
-        int recursionlimit = -1;
-        boolean exceptionOnLimit = false;
-
-        FakeMetadataObject doc12 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-        FakeMetadataObject doc12a = FakeMetadataFactory.createVirtualGroup("xmltest.doc12a", xmltest, createXMLPlanRecursiveA(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-
-        useRecursiveCriteria = true;
-        FakeMetadataObject doc13 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-        useRecursiveCriteria = false;
-        recursionlimit = 2;
-        FakeMetadataObject doc14 = FakeMetadataFactory.createVirtualGroup("xmltest.doc14", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-        exceptionOnLimit = true;
-        FakeMetadataObject doc15 = FakeMetadataFactory.createVirtualGroup("xmltest.doc15", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-
-        useRecursiveCriteria = false;
-        recursionlimit = -1;
-        exceptionOnLimit = false;
-        FakeMetadataObject doc16 = FakeMetadataFactory.createVirtualGroup("xmltest.doc16", xmltest, createXMLPlanRecursive2(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-
-        FakeMetadataObject doc17 = FakeMetadataFactory.createVirtualGroup("xmltest.doc17", xmltest, createXMLPlanWithComment()); //$NON-NLS-1$
-
-        FakeMetadataObject doc_5266a = FakeMetadataFactory.createVirtualGroup("xmltest.doc_5266a", xmltest, createXMLPlanNestedWithChoiceFor5266()); //$NON-NLS-1$
-        List doc_E5266a = FakeMetadataFactory.createElements(doc_5266a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-
-        FakeMetadataObject doc_8917 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_8917", xmltest, createXMLPlan_defect8917()); //$NON-NLS-1$
-        FakeMetadataObject doc_9446 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9446", xmltest, createXMLPlan_defect9446()); //$NON-NLS-1$
-        FakeMetadataObject doc_9530 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9530", xmltest, createXMLPlan_defect_9530()); //$NON-NLS-1$
-
-        List docE_9446 = FakeMetadataFactory.createElements(doc_9446, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-        
-        //Test doc w/ update mapping class transformation
-        FakeMetadataObject docUpdateTest = FakeMetadataFactory.createVirtualGroup("xmltest.docUpdateTest", xmltest, createUpdateTestDoc()); //$NON-NLS-1$
-
-        FakeMetadataObject doc_9893 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9893", xmltest, createXMLPlan_9893()); //$NON-NLS-1$
-        List docE_9893 = FakeMetadataFactory.createElements(doc_9893, new String[] { "Root", "Root.ItemName"}, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc18 = FakeMetadataFactory.createVirtualGroup("xmltest.doc18", xmltest, createXMLPlanNested("xmltest.suppliersX")); //$NON-NLS-1$ //$NON-NLS-2$
-        List docE18 = FakeMetadataFactory.createElements(doc18, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc12260 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12260", xmltest, createXMLPlanCorrelatedSubqueryTransform()); //$NON-NLS-1$
-        List docE12260 = FakeMetadataFactory.createElements(doc12260, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc8373 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373", xmltest, createXMLPlan_defect8373()); //$NON-NLS-1$
-        List docE8373 = FakeMetadataFactory.createElements(doc8373, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc8373a = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373a", xmltest, createXMLPlan_defect8373a()); //$NON-NLS-1$
-        List docE8373a = FakeMetadataFactory.createElements(doc8373a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc8373b = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373b", xmltest, createXMLPlan_defect8373b()); //$NON-NLS-1$
-        List docE8373b = FakeMetadataFactory.createElements(doc8373b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject doc13617 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13617", xmltest, createXMLPlanDefect13617()); //$NON-NLS-1$
-        List docE13617 = FakeMetadataFactory.createElements(doc13617, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-        
-
-        // recursive + staging ========================================================
-
-        FakeMetadataObject doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19", xmltest, createXMLPlanRecursiveStaging(true, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-        
-        // root temp group
-        QueryNode doc19TempQuery = new QueryNode("xmltest.doc19temp", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject tempDoc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19temp", xmltest, doc19TempQuery); //$NON-NLS-1$
-        List doc19TempQueryE = FakeMetadataFactory.createElements(tempDoc19, 
-                                                              new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                                                              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-
-        //create employees - not connected to any of the above
-        QueryNode rsEmployeesDoc19 = new QueryNode("xmltest.employeesDoc19", "SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject mc1Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesDoc19", xmltest, rsEmployeesDoc19); //$NON-NLS-1$
-        List mc1Doc19E = FakeMetadataFactory.createElements(mc1Doc19, 
-                                                                  new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                                                                  new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        //recursive piece
-        QueryNode rsEmployeesRecursiveDoc19 = new QueryNode("xmltest.employeesRecursiveDoc19", "SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsEmployeesRecursiveDoc19.addBinding("xmltest.employeesDoc19.employeeNum"); //$NON-NLS-1$
-        FakeMetadataObject mc2Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursiveDoc19", xmltest, rsEmployeesRecursiveDoc19); //$NON-NLS-1$
-        List mc2Doc19E = FakeMetadataFactory.createElements(mc2Doc19, 
-                                                            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-        // recursive + staging ========================================================
-        
-        //========================================================
-
-        // Stored queries
-        FakeMetadataObject rsX = FakeMetadataFactory.createResultSet("xmltest.rsX", xmltest, new String[] { "supplierNum", "supplierName", "supplierZipCode" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FakeMetadataObject rsXp1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rsX);  //$NON-NLS-1$
-        FakeMetadataObject rsXp2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        //there is an extra statement in this proc so that the procedure wrapper is not removed
-        QueryNode sqXn1 = new QueryNode("xmltest.sqX", "CREATE VIRTUAL PROCEDURE BEGIN declare string x; SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = xmltest.sqX.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sqX = FakeMetadataFactory.createVirtualProcedure("xmltest.sqX", xmltest, Arrays.asList(new FakeMetadataObject[] { rsXp1, rsXp2 }), sqXn1);  //$NON-NLS-1$
-       
-        // Documents for Text Normalization Test 
-        // normDoc1 - for collapse
-        // normDoc2 - for replace
-        // normDoc3 - for preserve
-        FakeMetadataObject normDoc1 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc1", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_COLLAPSE)); //$NON-NLS-1$
-        List normDocE1 = FakeMetadataFactory.createElements(normDoc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
-                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject normDoc2 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc2", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_REPLACE)); //$NON-NLS-1$
-        List normDocE2 = FakeMetadataFactory.createElements(normDoc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
- 
-        FakeMetadataObject normDoc3 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc3", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_PRESERVE)); //$NON-NLS-1$
-        List normDocE3 = FakeMetadataFactory.createElements(normDoc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
-                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        
-        QueryNode vspqn1 = new QueryNode("vsp1", "CREATE VIRTUAL PROCEDURE BEGIN insert into #temp select * from stock.items; SELECT * FROM xmltest.doc1 where Item.Quantity < (select avg(itemquantity) from #temp); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsprs1 = FakeMetadataFactory.createResultSet("pm1.vsprs1", xmltest, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vspp1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.XML, vsprs1); //$NON-NLS-1$
-        FakeMetadataObject vsp1 = FakeMetadataFactory.createVirtualProcedure("xmltest.vsp1", xmltest, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn1); //$NON-NLS-1$
-
-        // Add all objects to the store
-        store.addObject(stock);
-        store.addObject(items);
-        store.addObject(item_supplier);
-   
-        store.addObject(suppliers);
-        store.addObject(orders);
-        store.addObject(employees);
-        store.addObjects(itemElements);
-        store.addObjects(itemSupplierElements);
-        store.addObjects(supplierElements);
-        store.addObjects(stockOrders);
-        store.addObjects(supplierEmployees);
-     
-        store.addObject(xmltest);
-        store.addObject(rs);
-        store.addObject(rs2);
-        store.addObject(rs3);
-        store.addObject(rs4);
-        store.addObject(rs4a);
-        store.addObject(rs5);
-        store.addObject(rs5a);
-        store.addObject(temp);
-        store.addObject(temp2);
-        store.addObject(rs3a);
-        store.addObject(temp3b);
-        store.addObject(rs3b);
-        store.addObject(rsQX);
-        store.addObject(rs12260);
-        store.addObject(rs8373);
-        store.addObject(rs8373a);
-        store.addObject(rs8373b);
-        
-        //Stored query
-        store.addObject(rsX);
-        store.addObject(sqX);
-  
-        store.addObject(rsUpdate);
-        store.addObjects(rsElements);
-        store.addObjects(rsElements2);
-        store.addObjects(rsElements3);
-        store.addObjects(rsElements4);
-        store.addObjects(rsElements4a);
-        store.addObjects(rsElements5);
-        store.addObjects(rsElements5a);
-        store.addObjects(tempElements);
-        store.addObjects(tempElements2);
-        store.addObjects(rsElements3a);
-        store.addObjects(tempElements3b);
-        store.addObjects(rsElements3b);
-        store.addObjects(rsUpdateElement);
-        store.addObjects(rsElementsX);
-        store.addObjects(rsElements12260);
-        store.addObjects(rsElements8373);
-        store.addObjects(rsElements8373a);
-        store.addObjects(rsElements8373b);
-
-        store.addObject(doc1);
-        store.addObject(docBounded);
-        store.addObject(doc1a);
-        store.addObject(doc1b);
-        store.addObject(doc1c);
-        store.addObject(doc2);
-        store.addObject(doc2a);
-        store.addObject(doc2b);
-        store.addObject(doc2c);
-        store.addObject(doc2d);
-        store.addObject(doc2e);
-        store.addObject(doc3);
-        store.addObject(doc4);
-        store.addObject(doc5);
- 
-        store.addObject(normDoc1);
-        store.addObject(normDoc2);
-        store.addObject(normDoc3);
-
-        store.addObject(doc6);
-        store.addObject(doc7);
-        store.addObject(doc8);
-        store.addObject(doc9);
-        store.addObject(doc9a);
-        store.addObject(doc9b);
-     
-        store.addObject(doc10);
-        store.addObject(doc10L);
-        store.addObject(doc11);
-        store.addObject(doc12);
-        store.addObject(doc12a);
-        store.addObject(doc13);
-        store.addObject(doc14);
-        store.addObject(doc15);
-        store.addObject(doc16);
-        store.addObject(doc17);
-        store.addObject(doc_8917);
-        store.addObject(doc_9446);
-        store.addObject(doc_9530);
-        store.addObject(docUpdateTest);
-        store.addObject(doc_9893);
-        store.addObject(doc18);
-        store.addObject(doc12260);
-        store.addObject(doc8373);
-        store.addObject(doc8373a);
-        store.addObject(doc8373b);
-        store.addObject(doc13617);
-        store.addObject(doc19);
-        store.addObject(tempDoc19);
-        store.addObject(mc1Doc19);
-        store.addObject(mc2Doc19);
-        store.addObject(doc_5266a);
-
-        store.addObjects(doc19TempQueryE);
-        store.addObjects(mc1Doc19E);
-        store.addObjects(mc2Doc19E);
-        
-        store.addObjects(docE1);
-        store.addObjects(docE1b);
-        store.addObjects(docE1c);
-        store.addObjects(docBoundedElements);
-        store.addObjects(docE2);
-        store.addObjects(docE3);
-        store.addObjects(docE4);
-        store.addObjects(docE5);
-        store.addObjects(normDocE1);
-        store.addObjects(normDocE2);
-        store.addObjects(normDocE3);
-        store.addObjects(docE6);
-        store.addObjects(docE7);
-        store.addObjects(docE8);
-        store.addObjects(docE9);
-        store.addObjects(docE9a);
-        store.addObjects(docE_9446);
-        store.addObjects(docE_9893);
-        store.addObjects(docE18);
-        store.addObjects(docE12260);
-        store.addObjects(docE8373);
-        store.addObjects(docE8373a);
-        store.addObjects(docE8373b);
-        store.addObjects(docE13617);
-        store.addObjects(doc_E5266a);
-        
-        store.addObjects(docE10);
-        store.addObjects(docE10L);
-        store.addObjects(docE11);
-        
-        store.addObject(vsp1);        
-        return facade;
-    }
-
-    public FakeMetadataFacade exampleMetadataNestedWithSibling() {
-		FakeMetadataStore store = new FakeMetadataStore();
-		FakeMetadataFacade facade = new FakeMetadataFacade(store);
-        
-		// Create models
-		FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-		FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");  //$NON-NLS-1$
-
-		// Create physical groups
-		FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
-		FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
-		FakeMetadataObject item_order = FakeMetadataFactory.createPhysicalGroup("stock.item_order", stock); //$NON-NLS-1$
-		FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
-		FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
-		      
-		// Create physical elements
-		List itemElements = FakeMetadataFactory.createElements(items, 
-			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-		//many-to-many join table
-		List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
-			new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-		List supplierElements = FakeMetadataFactory.createElements(suppliers, 
-			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-		//many-to-many join table
-		List itemOrderElements = FakeMetadataFactory.createElements(item_order, 
-			new String[] { "itemNum", "orderNum" }, //$NON-NLS-1$ //$NON-NLS-2$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-		List stockOrders = FakeMetadataFactory.createElements(orders, 
-			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-	
-// ======================================================================================================================
-
-		// Create virtual groups
-		QueryNode rsQuery1 = new QueryNode("xmltest.group.items", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject rs1 = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery1); //$NON-NLS-1$
-
-		QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-		rsQuery2.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-		FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
-
-		QueryNode rsQuery3 = new QueryNode("xmltest.orders", "SELECT concat(stock.orders.orderNum, '') as orderNum, orderName, orderZipCode FROM stock.orders, stock.item_order WHERE stock.orders.orderNum = stock.item_order.orderNum AND stock.item_order.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-		rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-		FakeMetadataObject rs3= FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
-
-		// Create virtual elements
-		List rsElements1 = FakeMetadataFactory.createElements(rs1, 
-			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-		
-		List rsElements2 = FakeMetadataFactory.createElements(rs2, 
-			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-		
-		List rsElements3 = FakeMetadataFactory.createElements(rs3, 
-			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-	
-// =========================================================================================================
-
-		// Create virtual docs
-		FakeMetadataObject doc9c= FakeMetadataFactory.createVirtualGroup("xmltest.doc9c", xmltest, createXMLPlanNested2c()); //$NON-NLS-1$
-		List docE9c = FakeMetadataFactory.createElements(doc9c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.orders", "Catalogs.Catalog.items.item.orders.order", "Catalogs.Catalog.items.item.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.orders.order.zip", "Catalogs.Catalog.items.item.orders.order.Name"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ !
 //$NON-NLS-16$ //$NON-NLS-17$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-		
-		//========================================================
-
-		// Add all objects to the store
-		store.addObject(stock);
-		
-		store.addObject(items);
-		store.addObject(item_supplier);
-		store.addObject(item_order);
-		store.addObject(suppliers);
-		store.addObject(orders);
-		
-		store.addObjects(itemElements);
-		store.addObjects(itemSupplierElements);
-		store.addObjects(supplierElements);
-		store.addObjects(stockOrders);
-		store.addObjects(itemOrderElements);
-
-		store.addObject(xmltest);
-		store.addObject(rs1);
-		store.addObject(rs2);
-		store.addObject(rs3);
-		
-		store.addObjects(rsElements1);
-		store.addObjects(rsElements2);
-		store.addObjects(rsElements3);
-
-		store.addObject(doc9c);
-		store.addObjects(docE9c);
-     
-		// Create the facade from the store
-		return facade;		
-	}
-	
-    public static FakeMetadataFacade exampleMetadata2() { 
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
-        
-        // Create models
-        FakeMetadataObject xqt = FakeMetadataFactory.createPhysicalModel("xqt"); //$NON-NLS-1$
-        FakeMetadataObject xqttest = FakeMetadataFactory.createVirtualModel("xqttest");     //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject xqtGroup = FakeMetadataFactory.createPhysicalGroup("xqt.data", xqt); //$NON-NLS-1$
-                
-        // Create physical elements
-        List xqtData = FakeMetadataFactory.createElements(xqtGroup, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        // Create new XML recursion tests virtual groups
-        QueryNode xqtDataGroup = new QueryNode("xqttest.xqtData", "SELECT intKey as key, intNum as data, (intKey + 2) as nextKey FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject objData = FakeMetadataFactory.createVirtualGroup("xqttest.xqtData", xqttest, xqtDataGroup); //$NON-NLS-1$
-        
-        QueryNode rsGroup = new QueryNode("xqttest.group", "SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject objGroup = FakeMetadataFactory.createVirtualGroup("xqttest.group", xqttest, rsGroup); //$NON-NLS-1$
-        
-        QueryNode rsSupervisor = new QueryNode("xqttest.supervisor", "SELECT key as ID, data as CODE, nextKey as groupID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsSupervisor.addBinding("xqttest.group.supervisorID"); //$NON-NLS-1$
-        FakeMetadataObject objSupervisor = FakeMetadataFactory.createVirtualGroup("xqttest.supervisor", xqttest, rsSupervisor); //$NON-NLS-1$
-
-        QueryNode rsGroup1 = new QueryNode("xqttest.group1", "SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsGroup1.addBinding("xqttest.supervisor.groupID"); //$NON-NLS-1$
-        FakeMetadataObject objGroup1 = FakeMetadataFactory.createVirtualGroup("xqttest.group1", xqttest, rsGroup1); //$NON-NLS-1$
-        
-        // Create virtual elements
-        
-        List elemXQTData = FakeMetadataFactory.createElements(objData, 
-            new String[] { "key", "data", "nextKey" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
-
-        List elemGroup = FakeMetadataFactory.createElements(objGroup, 
-            new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
-
-        List elemSupervisor = FakeMetadataFactory.createElements(objSupervisor, 
-            new String[] { "ID", "code", "groupID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
-
-        List elemGroup1 = FakeMetadataFactory.createElements(objGroup1, 
-            new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
-        
-        // Create virtual groups
-        QueryNode rsQuery = new QueryNode("xqttest.data", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey=13"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xqttest.data", xqttest, rsQuery); //$NON-NLS-1$
-        
-        QueryNode rsQuery2 = new QueryNode("xqttest.data2", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery2.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xqttest.data2", xqttest, rsQuery2); //$NON-NLS-1$
-
-        QueryNode rsQuery3 = new QueryNode("xqttest.data3", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery3.addBinding("xqttest.data2.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xqttest.data3", xqttest, rsQuery3); //$NON-NLS-1$
-
-        QueryNode rsQuery4 = new QueryNode("xqttest.data4", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery4.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xqttest.data4", xqttest, rsQuery4); //$NON-NLS-1$
-
-        QueryNode rsQuery5 = new QueryNode("xqttest.data5", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery5.addBinding("xqttest.data4.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xqttest.data5", xqttest, rsQuery5); //$NON-NLS-1$
-
-        QueryNode rsQuery6 = new QueryNode("xqttest.data6", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery6.addBinding("xqttest.data5.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs6 = FakeMetadataFactory.createVirtualGroup("xqttest.data6", xqttest, rsQuery6); //$NON-NLS-1$
-
-        
-        QueryNode rsQuery7 = new QueryNode("xqttest.data7", "SELECT intKey, intNum, stringNum FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs7 = FakeMetadataFactory.createVirtualGroup("xqttest.data7", xqttest, rsQuery7); //$NON-NLS-1$
-
-        QueryNode rsQuery8 = new QueryNode("xqttest.data8", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey < ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery8.addBinding("xqttest.data7.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs8 = FakeMetadataFactory.createVirtualGroup("xqttest.data8", xqttest, rsQuery8); //$NON-NLS-1$
-
-        // Create virtual elements
-        List rsElements = FakeMetadataFactory.createElements(rs, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements6 = FakeMetadataFactory.createElements(rs6, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements7 = FakeMetadataFactory.createElements(rs7, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsElements8 = FakeMetadataFactory.createElements(rs8, 
-            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xqttest.doc1", xqttest,   createXQTPlanRecursive_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xqttest.doc1a", xqttest, createXQTPlanRecursive1a_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc2 = FakeMetadataFactory.createVirtualGroup("xqttest.doc2", xqttest,   createXQTPlanRecursiveSiblings()); //$NON-NLS-1$
-        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xqttest.doc3", xqttest,   createXQTPlanRecursive3_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xqttest.doc4", xqttest,   createXQTPlanChoice_6796()); //$NON-NLS-1$
-        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xqttest.doc5", xqttest,   createChoiceDefect24651()); //$NON-NLS-1$
-        FakeMetadataObject groupDoc = FakeMetadataFactory.createVirtualGroup("xqttest.groupDoc", xqttest,   createGroupDoc()); //$NON-NLS-1$
-
-        List elemGroupDoc = FakeMetadataFactory.createElements(groupDoc, new String[] { "group", "group.pseudoID" /*, etc...*/ }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-        List elemGroupDoc4 = FakeMetadataFactory.createElements(doc4, new String[] { "root", "root.key", "root.key.keys", "root.key.keys.nestedkey", "root.wrapper.key", "root.wrapper.key.keys", "root.wrapper.key.keys.nestedkey"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-                                                               new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        
-        List elemGroupDoc5 = FakeMetadataFactory.createElements(doc5, new String[] { "root", "root.wrapper.key" }, //$NON-NLS-1$ //$NON-NLS-2$
-                                                                new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-         
-        store.addObject(xqt);
-        store.addObject(xqtGroup);
-        store.addObjects(xqtData);
-
-        store.addObject(xqttest);
-        
-        store.addObject(objData);
-        store.addObject(objGroup);
-        store.addObject(objSupervisor);
-        store.addObject(objGroup1);
-        store.addObjects(elemXQTData);
-        store.addObjects(elemGroup);
-        store.addObjects(elemSupervisor);
-        store.addObjects(elemGroup1);
-        
-        store.addObject(rs);
-        store.addObject(rs2);
-        store.addObject(rs3);
-        store.addObject(rs4);
-        store.addObject(rs5);
-        store.addObject(rs6);
-        store.addObject(rs7);
-        store.addObject(rs8);
-        store.addObjects(rsElements);
-        store.addObjects(rsElements2);
-        store.addObjects(rsElements3);
-        store.addObjects(rsElements4);
-        store.addObjects(rsElements5);
-        store.addObjects(rsElements6);
-        store.addObjects(rsElements7);
-        store.addObjects(rsElements8);
-
-        store.addObject(doc1);
-        store.addObject(doc1a);
-        store.addObject(doc2);
-        store.addObject(doc3);
-        store.addObject(doc4);
-        store.addObject(doc5);
-        store.addObject(groupDoc);
-        store.addObjects(elemGroupDoc);
-        store.addObjects(elemGroupDoc4);
-        store.addObjects(elemGroupDoc5);
-
-        return facade;
-    }
-
-    public static FakeMetadataFacade exampleMetadataSoap1() {
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
-        
-        // Create models
-        FakeMetadataObject taxReport = FakeMetadataFactory.createPhysicalModel("taxReport"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject arrayOfItem = FakeMetadataFactory.createPhysicalGroup("taxReport.TaxIDs", taxReport); //$NON-NLS-1$
-
-        // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(arrayOfItem, 
-            new String[] { "ID" }, //$NON-NLS-1$
-            new String[] {DataTypeManager.DefaultDataTypes.STRING});
-
-
-        QueryNode rsQuerySoap = new QueryNode("xmltest.group.TaxIDs", "SELECT ID FROM taxReport.TaxIDs"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsSoap = FakeMetadataFactory.createVirtualGroup("xmltest.group.TaxIDs", xmltest, rsQuerySoap); //$NON-NLS-1$
-
-        List rsSoapElements = FakeMetadataFactory.createElements(rsSoap, 
-        new String[] { "ID"}, //$NON-NLS-1$
-        new String[] {DataTypeManager.DefaultDataTypes.STRING});        
-
-        FakeMetadataObject doc_SOAP = FakeMetadataFactory.createVirtualGroup("xmltest.docSoap", xmltest, createXMLPlanSOAP()); //$NON-NLS-1$
-        List doc_SOAPE1 = FakeMetadataFactory.createElements(doc_SOAP, new String[] { "TaxReports", "TaxReports.TaxReport", "TaxReports.TaxReport.ArrayOfTaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID.ID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-                                               
-        store.addObject(taxReport);
-        store.addObject(arrayOfItem);
-        store.addObjects(itemElements);
-
-        store.addObject(xmltest);
-        store.addObject(rsSoap);
-        store.addObjects(rsSoapElements); 
-        store.addObject(doc_SOAP);
-        store.addObjects(doc_SOAPE1);
-        return facade;
-    }
-	
-    private static MappingNode createXQTPlanChoice_6796() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
-        choice.setSource("xqttest.data7"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$ 
-        MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
-
-        MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
-        keys.setSource("xqttest.data8"); //$NON-NLS-1$
-        keys.setMaxOccurrs(-1);
-        keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingCriteriaNode wrapper2 = choice.addCriteriaNode(new MappingCriteriaNode(null, true)); 
-        
-        key = wrapper2.addChildElement( new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
-        keys.setSource("xqttest.data8"); //$NON-NLS-1$
-        keys.setMaxOccurrs(-1);
-        keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        return doc;
-    }
-    
-    private static MappingNode createChoiceDefect24651() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
-        choice.setSource("xqttest.data7"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$ 
-        MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
-
-        MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        key.setExclude(true);
-                
-        return doc;
-    }
-
-    /**
-     * Method createXQTPlanRecursive.
-     * @return Object
-     */
-    private static MappingNode createXQTPlanRecursive_5988() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-        
-        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
-        src1.setSource("xqttest.data"); //$NON-NLS-1$
-        
-        MappingSequenceNode seq1 = new MappingSequenceNode();
-        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        src1.addSequenceNode(seq1);
-
-        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
-        src2.setSource("xqttest.data2"); //$NON-NLS-1$
-                
-        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
-        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcNestedRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
-        recursive.setSource("xqttest.data3"); //$NON-NLS-1$
-        
-        MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
-        recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
-        
-        return doc;
-    }
-
-	/**
-	 * Method createXQTPlanRecursive.
-	 * @return Object
-	 */
-    private static MappingNode createXQTPlanRecursive1a_5988() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
-        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
-        src1.setSource("xqttest.data"); //$NON-NLS-1$
-
-        MappingSequenceNode seq1 = new MappingSequenceNode();
-        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        src1.addSequenceNode(seq1);
-
-        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
-        src2.setSource("xqttest.data2"); //$NON-NLS-1$
-
-        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
-        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
-        recursive.setSource("xqttest.data3"); //$NON-NLS-1$
-        
-        MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
-        recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
-        
-        return doc;
-    }
-
-    /**
-     * Tests a non-recursive nested mapping class within a recursive mapping class, where
-     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
-     * @return Object
-     */
-    private static MappingNode createXQTPlanRecursive3_5988() {   
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
-        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
-        src1.setSource("xqttest.data"); //$NON-NLS-1$
-
-        MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
-        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
-        src2.setSource("xqttest.data2"); //$NON-NLS-1$
-        
-        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
-        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingElement nested = seq1.addChildElement(new MappingRecursiveElement("srcNested", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
-        nested.setSource("xqttest.data4"); //$NON-NLS-1$
-        
-        return doc;
-    }
-    
-    
-    private static MappingNode createXQTPlanRecursiveSiblings() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
-
-        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
-        src1.setSource("xqttest.data"); //$NON-NLS-1$
-
-        MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
-        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingElement sibiling1 = seq1.addChildElement(new MappingRecursiveElement("srcSibling1", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
-        sibiling1.setSource("xqttest.data2"); //$NON-NLS-1$
-        sibiling1.setMaxOccurrs(-1);
-        MappingElement sibiling2 = seq1.addChildElement(new MappingRecursiveElement("srcSibling2", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
-        sibiling2.setSource("xqttest.data2");//$NON-NLS-1$
-        sibiling2.setMaxOccurrs(-1);
-        return doc;
-    }
-
-	/**
-	 * Method createXMLPlanNested.
-	 * @return MappingNode root of mapping doc
-	 */
-	private static MappingNode createXMLPlanNested() {
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
-        doc.addChildElement(root);
-        
-        MappingSequenceNode sequence = new MappingSequenceNode();
-        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
-        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
-        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-                
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
-        MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
-
-        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
-
-        
-        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
-        sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        //NESTED STUFF======================================================================
-        
-        sequence1.addChildElement(nestedWrapper);
-        root.addSequenceNode(sequence);
-        return doc;  
-	}
-    
-    
-    /**
-     * for defect 9929
-     */
-    static MappingNode createXMLPlanNested(String queryGroup) {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
-        doc.addChildElement(root);
-        
-        MappingSequenceNode sequence = new MappingSequenceNode();
-        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
-        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items");         //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
-        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
-        MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
-
-        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource(queryGroup);
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", queryGroup+".supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
-        sequence3.addChildElement(new MappingElement("Name", queryGroup+".supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence3.addChildElement(new MappingElement("Zip", queryGroup+".supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        //NESTED STUFF======================================================================
-       
-        sequence1.addChildElement(nestedWrapper);
-        root.addSequenceNode(sequence);
-        return doc;  
-    }    
-
-    /**
-     * for defect 12260
-     */
-    private static MappingNode createXMLPlanCorrelatedSubqueryTransform() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingSequenceNode sequence = new MappingSequenceNode();
-        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
-
-        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.itemsWithNumSuppliers"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.itemsWithNumSuppliers.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
-        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.itemsWithNumSuppliers.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.itemsWithNumSuppliers.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("numSuppliers", "xmltest.group.itemsWithNumSuppliers.numSuppliers")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        root.addSequenceNode(sequence);
-        return doc;  
-    }
-
-    private static MappingNode createXMLPlan_9893() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
-        
-        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
-        
-        MappingElement node = seq.addChildElement(new MappingElement("ItemName", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        node.setSource("xmltest.group.items"); //$NON-NLS-1$
-        node.setMaxOccurrs(-1);
-        node.setMaxOccurrs(MappingNodeConstants.CARDINALITY_UNBOUNDED.intValue());
-        return doc;  
-    }
-
-    /** 
-     * DEFECT 8373
-     */
-    private static Object createXMLPlan_defect8373() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.items8373"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.items8373.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        return doc;  
-    }
-
-    /** 
-     * DEFECT 8373
-     */
-    private static Object createXMLPlan_defect8373a() {        
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.items8373a"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.setStagingTables(Arrays.asList(new String[] {"xmltest.items8373"})); //$NON-NLS-1$
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373a.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.items8373a.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373a.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        return doc;  
-    }
-    
-    /** 
-     * DEFECT 8373
-     */
-    private static Object createXMLPlan_defect8373b() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.items8373b"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.setStagingTables(Arrays.asList(new String[] {"xmltest.group.items"})); //$NON-NLS-1$
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373b.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.items8373b.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373b.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        return doc;
-    }    
-    
-    private static MappingNode createXMLPlanNested2() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        
-        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-                        
-        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
-        
-        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.setSource("xmltest.orders"); //$NON-NLS-1$
-        order.setMaxOccurrs(-1);
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        order.addChildElement(new MappingElement("OrderStatus", "xmltest.orders.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setMinOccurrs(0);                
-        //NESTED STUFF======================================================================
-        return doc;  
-    }
-
-	/** nested with sibling*/
-	private MappingNode createXMLPlanNested2c() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-		//NESTED STUFF======================================================================
-        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        
-        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement ordersWrapper = item.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
-        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.setSource("xmltest.orders"); //$NON-NLS-1$
-        order.setMaxOccurrs(-1);
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("Name", "xmltest.orders.orderName")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("Zip", "xmltest.orders.orderZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-		//NESTED STUFF======================================================================
-		return doc;  
-	}
-
-
-    private static MappingNode createXMLPlanNested2a() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders", "tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);    
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        
-        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$        
-        
-        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.setSource("xmltest.ordersA"); //$NON-NLS-1$
-        order.setMaxOccurrs(-1);
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersA.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersA.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersA.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersA.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setMinOccurrs(0);                
-        //NESTED STUFF======================================================================
-        return doc;  
-    }
-
-    // for doc 9b - test temp group w/ bindings
-    private static MappingNode createXMLPlanNested2b() {
-        
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders", "tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$      
-        
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-
-        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$        
-        
-        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.setSource("xmltest.ordersB"); //$NON-NLS-1$
-        
-        order.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders3B"})); //$NON-NLS-1$ 
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersB.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersB.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersB.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersB.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setMinOccurrs(0);                
-        //NESTED STUFF======================================================================
-        return doc;
-    }
-
-    public static MappingDocument createXMLPlanNestedWithChoice() {
-        MappingCriteriaNode critNode = new MappingCriteriaNode();
-        MappingElement defaltElement = critNode.addChildElement(new MappingElement("OtherOrder")); //$NON-NLS-1$
-        defaltElement.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum"));//$NON-NLS-1$ //$NON-NLS-2$                
-        return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$
-    }
-
-    private static MappingNode createXMLPlanNestedWithChoiceFor5266() {
-        MappingCriteriaNode critNode = new MappingCriteriaNode("xmltest.orders.orderStatus = 'shipped'", true); //$NON-NLS-1$
-        return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$        
-    }
-    
-    private static MappingNode createXMLPlanNestedWithLookupChoice() {
-        MappingCriteriaNode critNode = new MappingCriteriaNode(); 
-        MappingElement defaltElement = critNode.addChildElement(new MappingElement("OtherOrder"));//$NON-NLS-1$
-        defaltElement.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum"));//$NON-NLS-1$ //$NON-NLS-2$                
-        return baseXMLPlanNestedWithLookupChoice("lookup('stock.items', 'itemNum', 'itemName', xmltest.orders.orderStatus) = 'processing'", critNode); //$NON-NLS-1$
-    }
-    
-    private static MappingDocument baseXMLPlanNestedWithLookupChoice(String criteria, MappingCriteriaNode defaultNode) {        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingSequenceNode seq1 = root.addSequenceNode(new MappingSequenceNode());
-        MappingElement cats = seq1.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        
-        MappingSequenceNode seq2 = items.addSequenceNode(new MappingSequenceNode());
-        
-        MappingElement item = seq2.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingSequenceNode seq3 = item.addSequenceNode(new MappingSequenceNode());        
-        seq3.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq3.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        //NESTED STUFF======================================================================
-        MappingElement suppliers = seq3.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        
-        MappingSequenceNode seq4 = suppliers.addSequenceNode(new MappingSequenceNode());        
-        MappingElement supplier = seq4.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingSequenceNode seq5 = supplier.addSequenceNode(new MappingSequenceNode());
-        seq5.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq5.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement ordersWrapper = seq5.addChildElement(new MappingElement("ProcessingOrders")); //$NON-NLS-1$
-        
-        MappingChoiceNode choice = ordersWrapper.addChoiceNode(new MappingChoiceNode(false));
-        choice.setSource("xmltest.orders"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode(criteria, false)); 
-        MappingElement order = crit.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingSequenceNode seq6 = order.addSequenceNode(new MappingSequenceNode());      
-        seq6.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq6.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        choice.addCriteriaNode(defaultNode);
-        //NESTED STUFF======================================================================
-        return doc;        
-    }
-
-
-    private static MappingNode createTestAttributePlan() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("FixedValueTest")); //$NON-NLS-1$
-        
-        //sequence
-        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());       
-        
-        MappingElement wrapper = seq.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
-        wrapper.setSource("xmltest.group.items"); //$NON-NLS-1$
-        wrapper.setMaxOccurrs(-1);
-        MappingAttribute att = new MappingAttribute("fixedAttr"); //$NON-NLS-1$
-        att.setValue("fixed attribute"); //$NON-NLS-1$
-        wrapper.addAttribute(att);
-        
-        //sequence
-        MappingSequenceNode seq1 = wrapper.addSequenceNode(new MappingSequenceNode());
-        seq1.addChildElement(new MappingElement("key","xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq1.addChildElement(new MappingElement("fixed")) //$NON-NLS-1$
-            .setValue("fixed value"); //$NON-NLS-1$
-        
-        return doc;
-    }
-
-    private static Object createUpdateTestDoc() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("UpdateTest")); //$NON-NLS-1$
-        
-        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
-        seq.setSource("xmltest.updateTest"); //$NON-NLS-1$
-        seq.addChildElement(new MappingElement("data", "xmltest.updateTest.rowCount")); //$NON-NLS-1$ //$NON-NLS-2$        
-        return doc;
-    }
-
-    private static MappingNode createXMLPlanWithComment(){
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
-        
-        root.addCommentNode(new MappingCommentNode("Comment1")); //$NON-NLS-1$
-        MappingElement node = root.addChildElement(new MappingElement("Something")); //$NON-NLS-1$
-        node.addCommentNode(new MappingCommentNode("Comment2")); //$NON-NLS-1$
-        return doc;
-    }
-
-    public static MappingDocument createXMLMappingBoundingNode() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs"));//$NON-NLS-1$
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-       
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMinOccurrs(1);
-        item.setMaxOccurrs(2);
-        
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$        
-        return doc;
-    }
-    
-    public static MappingDocument createXMLMappingNode(boolean format) {
-        MappingDocument doc = new MappingDocument(format);
-        doc.addChildElement(createXMLPlan1Unformatted(false, 1));
-        return doc;
-    }
-    
-    private static MappingNode createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
-        MappingDocument doc = new MappingDocument(format);
-        doc.addChildElement(createXMLPlan1Unformatted(testNillable, cardinality));
-        return doc;
-    }    
-    
-    private static MappingNode createXMLPlanSOAP() {
-
-        Namespace namespace = new Namespace("ORG", "http://www.mm.org/dummy"); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("TaxReports", namespace)); //$NON-NLS-1$
-        
-        root.setNamespaces(new Namespace[] {namespace});
-        
-        MappingElement report = root.addChildElement(new MappingElement("TaxReport", namespace)); //$NON-NLS-1$
-        report.setNamespaces(new Namespace[] {namespace});
-               
-        Namespace xsiNamespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace soapNamespace = new Namespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement taxIds = report.addChildElement(new MappingElement("ArrayOfTaxID", namespace)); //$NON-NLS-1$
-        taxIds.setMinOccurrs(0);
-        taxIds.setNamespaces(new Namespace[] {xsiNamespace, soapNamespace});
-        
-        MappingAttribute xsiType = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
-        xsiType.setValue(namespace.getPrefix()+":ArrayOfTaxIDType"); //$NON-NLS-1$        
-        xsiType.setOptional(true);
-        taxIds.addAttribute(xsiType);
-        
-        MappingAttribute arrayType = new MappingAttribute("arrayType", soapNamespace); //$NON-NLS-1$
-        arrayType.setValue( namespace.getPrefix()+":TaxIDType[]"); //$NON-NLS-1$
-        arrayType.setOptional(true);
-        taxIds.addAttribute(arrayType);
-          
-        MappingElement taxId = taxIds.addChildElement(new MappingElement("TaxID", namespace)); //$NON-NLS-1$
-        taxId.setSource("xmltest.group.TaxIDs"); //$NON-NLS-1$
-        taxId.setMaxOccurrs(-1);
-        MappingAttribute xsiType2 = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
-        xsiType2.setValue(namespace.getPrefix()+":TaxIDType"); //$NON-NLS-1$
-        xsiType2.setOptional(true);
-        taxId.addAttribute(xsiType2);
-
-        taxId.addChildElement(new MappingElement("ID", "xmltest.group.TaxIDs.ID")); //$NON-NLS-1$ //$NON-NLS-2$
-        return doc;
-    }    
-    
-    
-    private static MappingElement createXMLPlan1Unformatted( boolean testNillable, int cardinality ) {
-
-        MappingElement root = new MappingElement("Catalogs");//$NON-NLS-1$
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        items.setNillable(testNillable);
-        items.setMinOccurrs(cardinality);
-            
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$        
-        return root;                                
-    }
-
-    private static MappingNode createXMLPlanDefect13617() {
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-       
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.setMinOccurrs(0);
-        
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setMinOccurrs(0);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$        
-            .setMinOccurrs(0);
- 
-        return doc;                                
-    }     
-    
-
-    private static MappingNode createXMLPlan2(int numChoices, int numDefaultChoice, boolean exception_on_Default) {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        // ======================================================================
-        // CHOICE NODE STUFF
-        //choice node, non-visual, so it has no name        
-        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exception_on_Default));
-        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        if (numChoices >= 1){
-            MappingCriteriaNode item = getChoiceChild("Item", "xmltest.group.items.itemName='Lamp'", numDefaultChoice == 1); //$NON-NLS-1$ //$NON-NLS-2$
-            choice.addCriteriaNode(item);
-        }
-        if (numChoices >= 2){
-            MappingCriteriaNode item = getChoiceChild("Item2", "xmltest.group.items.itemName='Screwdriver'", numDefaultChoice == 2); //$NON-NLS-1$ //$NON-NLS-2$
-            choice.addCriteriaNode(item);
-        }
-        if (numChoices >= 3){
-            MappingCriteriaNode item = getChoiceChild("Item3", "xmltest.group.items.itemName='Goat'", numDefaultChoice == 3); //$NON-NLS-1$ //$NON-NLS-2$
-            choice.addCriteriaNode(item);
-        }
-        if (numDefaultChoice > numChoices){
-            MappingCriteriaNode item = getChoiceChild("ItemDefault", null, true); //$NON-NLS-1$
-            choice.addCriteriaNode(item);
-        }
-        
-        // ======================================================================
-        return doc;                                
-    }
-
-    private static MappingCriteriaNode getChoiceChild(String name, String criteria, boolean defalt){
-        MappingCriteriaNode crit = new MappingCriteriaNode(criteria, defalt);
-        
-        MappingElement item = crit.addChildElement(new MappingElement(name));
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        return crit;
-    }    
-
-    private static MappingDocument createXMLPlanWithDefaults() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("1"); //$NON-NLS-1$
-
-        return doc;                                
-    }
-
-    private static MappingNode createXMLPlanUltraAdvanced() {
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        //choice node, non-visual, so it has no name
-        boolean exceptionOnDefault = false;
-        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
-        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$       
-        MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$         
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-
-        MappingCriteriaNode crit2= choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
-        MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$         
-        discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-        
-        MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode()); 
-        MappingElement unknown = crit3.addChildElement(new MappingElement("StatusUnknown"));//$NON-NLS-1$
-        unknown.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        unknown.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        unknown.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-                
-        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$ 
-        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$ 
-        
-        return doc;        
-    }
-    
-  
-
-    private static MappingNode createXMLPlanUltraAdvancedExceptionOnDefault() {
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        //choice node, non-visual, so it has no name
-        boolean exceptionOnDefault = true;
-        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
-        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$     
-        MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$        
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-
-        MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
-        MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$ 
-        discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-                .setNillable(true);
-        discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-                        
-        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)).setExclude(true); //$NON-NLS-1$ 
-        
-        return doc; 
-    }
-
-    //advanced tests of namespace declarations, use and scope; also fixed values
-    private static MappingNode createXMLPlanAdvanced() {
-        //add to previous example
-        MappingDocument doc = createXMLPlanWithDefaults();
-        MappingElement root = (MappingElement)doc.getRootNode();
-
-        Namespace nameSpaceOne = new Namespace("duh", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace nameSpaceTwo = new Namespace("duh2", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace nameSpaceThree = new Namespace("duh", "http://www.duh.org/duh/duh"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace nameSpaceFour = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, ""); //$NON-NLS-1$                      
-        Namespace nameSpaceFive = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, "http://www.default.org/default"); //$NON-NLS-1$        
-                        
-        MappingElement fakeChildOfRoot = new MappingElement("Fake", nameSpaceOne); //$NON-NLS-1$
-        fakeChildOfRoot.setValue("fixed constant value"); //$NON-NLS-1$                       
-        fakeChildOfRoot.addNamespace(nameSpaceOne);
-        fakeChildOfRoot.addNamespace(nameSpaceTwo);
-        fakeChildOfRoot.addNamespace(nameSpaceFive);
-        root.addChildElement(fakeChildOfRoot);
-
-        MappingElement fakeChild2 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild2", nameSpaceOne)); //$NON-NLS-1$ 
-
-        //add fakeChild2a with default namespace
-        MappingElement fakeChild2a = fakeChild2.addChildElement(new MappingElement("FakeChild2a")); //$NON-NLS-1$
-        fakeChild2a.setValue("another fixed constant value"); //$NON-NLS-1$
- 
-        MappingElement fakeChild3 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild3")); //$NON-NLS-1$
-        fakeChild3.addNamespace(nameSpaceThree);
-        fakeChild3.addNamespace(nameSpaceFour);        
-
-        MappingAttribute fakeAtt = new MappingAttribute("FakeAtt", nameSpaceOne); //$NON-NLS-1$
-        fakeAtt.setValue("fixed att value"); //$NON-NLS-1$
-        fakeChild3.addAttribute(fakeAtt);
-                
-        return doc;                                
-    }
-
-
-    /**
-     * Method createXMLPlanNested.
-     * @return MappingNode root of mapping doc
-     */
-    private static MappingNode createXMLPlanMultipleDocs() {
-
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        root.setSource("xmltest.group.items"); //$NON-NLS-1$
-        root.setMaxOccurrs(-1);
-        root.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-         
-        MappingSequenceNode sequence1 = root.addSequenceNode(new MappingSequenceNode());
-        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = sequence1.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        MappingSequenceNode sequence2 =  nestedWrapper.addSequenceNode(new MappingSequenceNode());
-        
-        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
-        sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$        
-        sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        return doc;  
-    }
-
-    private static MappingNode createXMLPlanRecursive(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
-        
-        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
-        ceo.setSource("xmltest.employees"); //$NON-NLS-1$
-        ceo.setMinOccurrs(0);
-        ceo.setMaxOccurrs(-1);
-        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode sequence = ceo.addSequenceNode(new MappingSequenceNode());
-        sequence.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-        MappingElement subordinates = sequence.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-        
-        //recursive piece
-        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
-        employee.setMinOccurrs(0);
-        employee.setMaxOccurrs(-1);
-
-        if (useRecursiveCriteria){
-            employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
-        }        
-        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
-        return doc;  
-    }
-
-    /*
-     * Recursion root mapping class is anchored at sequence node instead of "Employee" node
-     */
-    private static MappingNode createXMLPlanRecursiveA(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
-
-        MappingSequenceNode seq0 = root.addSequenceNode(new MappingSequenceNode());
-        seq0.setSource("xmltest.employees"); //$NON-NLS-1$
-        seq0.setMinOccurrs(0);
-        seq0.setMaxOccurrs(-1);
-        
-        MappingElement ceo = seq0.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
-        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
-        seq.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-        MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-
-        //recursive piece
-        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Subordinate", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.setSource("xmltest.employeesRecursive");  //$NON-NLS-1$
-        employee.setMinOccurrs(0);
-        employee.setMaxOccurrs(-1);
-
-        if (useRecursiveCriteria){
-            employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
-        }
-        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
-        return doc;  
-    }
-    
-    
-    private static MappingNode createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
-        
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
-        root.setStagingTables(Arrays.asList(new String[] {"xmltest.doc19temp"})); //$NON-NLS-1$
-
-        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
-        ceo.setSource("xmltest.employeesDoc19"); //$NON-NLS-1$
-        ceo.setMinOccurrs(0);
-        ceo.setMaxOccurrs(-1);
-        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employeesDoc19.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
-        seq.addChildElement(new MappingElement("FirstName", "xmltest.employeesDoc19.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq.addChildElement(new MappingElement("LastName", "xmltest.employeesDoc19.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-        MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
-
-        //recursive piece
-        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employeesDoc19")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.setSource("xmltest.employeesRecursiveDoc19"); //$NON-NLS-1$
-        employee.setMinOccurrs(0);
-        employee.setMaxOccurrs(-1);
-
-        if (useRecursiveCriteria){
-            employee.setCriteria("xmltest.employeesDoc19.employeeNum = '04'"); //$NON-NLS-1$
-        }
-        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
-
-        return doc;  
-    }
-    
-    private static MappingNode createXMLPlanRecursive2(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
-
-        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
-        ceo.setSource("xmltest.employees2"); //$NON-NLS-1$
-        ceo.setMinOccurrs(0);
-        ceo.setMaxOccurrs(-1);
-        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees2.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
-        seq.addChildElement(new MappingElement("FirstName", "xmltest.employees2.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        seq.addChildElement(new MappingElement("LastName", "xmltest.employees2.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        //recursive piece
-        MappingRecursiveElement employee = (MappingRecursiveElement)seq.addChildElement(new MappingRecursiveElement("Supervisor", "xmltest.employees2")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.setSource("xmltest.employees2Recursive"); //$NON-NLS-1$
-        employee.setMinOccurrs(0);
-        employee.setMaxOccurrs(-1);
-
-        if (useRecursiveCriteria){
-            employee.setCriteria("xmltest.employees2.employeeNum = '04'"); //$NON-NLS-1$
-        }
-        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
-        return doc;  
-    }
-
-    //this is for testing how "optional" XML elements are included/
-    //excluded from the result document
-    private static MappingNode createXMLPlan_defect8917() {
-        
-        Namespace namespace1 = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        root.addNamespace(namespace1);
-
-        {       
-        //FRAGMENT 1
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setNillable(true);        
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        {
-        //FRAGMENT 2
-        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog")); //$NON-NLS-1$
-        cat.setMinOccurrs(0);
-        
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-        	.setNillable(true); 
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        {
-        //FRAGMENT 3
-        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog2")); //$NON-NLS-1$
-        cat.setMinOccurrs(0);
-        
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setNillable(true);               
-        }        
-        
-        {
-        //FRAGMENT 4
-        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog3")); //$NON-NLS-1$
-        cat.setMinOccurrs(0);        
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        } 
-        
-        {
-        //FRAGMENT 5
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog4")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
-        items.setMinOccurrs(0);
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        }                 
-        
-        {
-        //FRAGMENT 6            
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog5")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
-        items.setMinOccurrs(0);
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.addChildElement(new MappingElement("FixedName")) //$NON-NLS-1$ 
-            .setValue("Nugent"); //$NON-NLS-1$
-        }        
-
-        {
-        //FRAGMENT 7            
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog6")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
-        items.setMinOccurrs(0);
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.addChildElement(new MappingElement("EmptyName")); //$NON-NLS-1$ 
-        }        
-        return doc;                                
-    }
-
-    /*
-     * Test of identically named nodes
-     */
-    private static MappingNode createXMLPlan_defect9446() {
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$        
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$        
-        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("XXXXX", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        return doc;                                
-    }
-    
-    private static MappingNode createXMLPlan_defect_9530() {        
-        Namespace namespace = new Namespace("mm", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace namespace2 = new Namespace("mm", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
-        Namespace namespace3 = new Namespace("mm2", "http://www.duh3.org/duh3"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs", namespace)); //$NON-NLS-1$
-        root.addNamespace(namespace);
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$        
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$        
-        
-        MappingElement item = items.addChildElement(new MappingElement("Item", namespace)); //$NON-NLS-1$
-        item.setSource("xmltest.group.items"); //$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addNamespace(namespace2);
-        item.addNamespace(namespace3);
-
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        return doc;                              
-    }    
-    
-    private static MappingNode createGroupDoc() {
-        MappingDocument doc = new MappingDocument(true);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("group")); //$NON-NLS-1$
-        root.setSource("xqttest.group"); //$NON-NLS-1$
-        root.setMinOccurrs(0);
-        root.setMaxOccurrs(-1);
-        
-        MappingAttribute attr = new MappingAttribute("pseudoID", "xqttest.group.ID"); //$NON-NLS-1$ //$NON-NLS-2$         
-        attr.setExclude(true);
-        root.addAttribute(attr);
-
-        MappingSequenceNode sequence = root.addSequenceNode(new MappingSequenceNode());
-        sequence.addChildElement(new MappingElement("ID", "xqttest.group.ID")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence.addChildElement(new MappingElement("code", "xqttest.group.Code")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingElement supervisor = sequence.addChildElement(new MappingElement("supervisor")); //$NON-NLS-1$
-        supervisor.setSource("xqttest.supervisor"); //$NON-NLS-1$
-        supervisor.setMinOccurrs(0);
-        supervisor.setMaxOccurrs(-1);
-
-        MappingSequenceNode sequence1 = supervisor.addSequenceNode(new MappingSequenceNode());
-        sequence1.addChildElement(new MappingElement("ID", "xqttest.supervisor.ID")); //$NON-NLS-1$ //$NON-NLS-2$
-        sequence1.addChildElement(new MappingElement("code", "xqttest.supervisor.Code")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingRecursiveElement group1 = (MappingRecursiveElement)sequence1.addChildElement(new MappingRecursiveElement("group", "xqttest.group")); //$NON-NLS-1$ //$NON-NLS-2$
-        group1.setSource("xqttest.group1"); //$NON-NLS-1$
-        group1.setMinOccurrs(0);
-        group1.setMaxOccurrs(-1);
-        return doc;         
-    }
-
-     
-    // Helper to create a list of elements - used in creating sample data
-    private static List createElements(List elementIDs) { 
-        List elements = new ArrayList();
-        for(int i=0; i<elementIDs.size(); i++) {
-            FakeMetadataObject elementID = (FakeMetadataObject) elementIDs.get(i);            
-            ElementSymbol element = new ElementSymbol(elementID.getName());
-            elements.add(element);
-        }        
-        
-        return elements;
-    }    
-
-    public static FakeDataManager exampleDataManager(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }                    
-
-    public static FakeDataManager exampleDataManager15117(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", " Lamp ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "  Screw  driver  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", " Goat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }     
-
-    /** unusual characters in text */
-    public static FakeDataManager exampleDataManager15117a(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "\t \n\r", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "  >Screw< \n driver  &", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", " >>\rGoat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }    
-    
-    public static FakeDataManager exampleDataManager14905(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { " ", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "  ", "  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { " ", " ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }     
-    
-    public static FakeDataManager exampleDataManager13617(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", null, new Integer(1), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ 
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }     
-    
-    public static FakeDataManager exampleDataManagerNested(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-
-            // Group stock.supplier
-            FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-            // Group stock.orders
-            FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-            // Group stock.item_supplier
-            FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-            // Group stock.employees
-            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
-
-            // Items
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            // Supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupID2);
-            List supplierElementSymbols = createElements(elementIDs);
-
-            // Orders
-            elementIDs = metadata.getElementIDsInGroupID(groupID3);
-            List ordersElementSymbols = createElements(elementIDs);
-
-            // Item_supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
-            List itemSupplierElementSymbols = createElements(elementIDs);
-
-            // Employees
-            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
-            List employeeSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupID1_2join,
-                itemSupplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
-
-
-            dataMgr.registerTuples(
-                groupID2,
-                supplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupID3,
-                ordersElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "1", "002", "54", "Nugent Co.", "10/23/01", new Integer(5), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "2", "001", "52", "Biff's Stuff", "12/31/01", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "3", "003", "56", "Microsoft", "02/31/02", new Integer(12), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "4", "003", "56", "Microsoft", "05/31/02", new Integer(9), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "5", "002", "56", "Microsoft", "06/01/02", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "6", "002", "56", "Microsoft", "07/01/02", new Integer(1), null } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "7", "002", "56", "bad data, shouldn't see", "07/01/02", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupEmployees,
-                employeeSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "01", "1", null, "Ted", "Nugent" } ), //ceo, Nugent Co. //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                    Arrays.asList( new Object[] { "02", "1", "01", "Bill", "Squier" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "03", "1", "01", "John", "Smith" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "04", "1", "02", "Leland", "Sklar" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "05", "1", "03", "Kevin", "Moore" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "06", "1", "04", "John", "Zorn" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "07", "2", null, "Geoff", "Tate" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                    Arrays.asList( new Object[] { "08", "2", "07", "Les", "Claypool" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "09", "2", "08", "Meat", "Loaf" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "10", "2", "08", "Keith", "Sweat" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "11", "1", "06", "Mike", "Patton" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "12", "1", "06", "Devin", "Townsend" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "13", "1", "11", "Puffy", "Bordin" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    } );    
-
-
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }                    
-
-	private FakeDataManager exampleDataManagerNestedWithSibling(FakeMetadataFacade metadata) {
-		FakeDataManager dataMgr = new FakeDataManager();
-    
-		try { 
-			// Group stock.items
-			FakeMetadataObject groupID1 = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-
-			// Group stock.supplier
-			FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-			// Group stock.orders
-			FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-			// Group stock.item_supplier
-			FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-			// Group stock.item_order
-			FakeMetadataObject groupID1_3join = (FakeMetadataObject) metadata.getGroupID("stock.item_order"); //$NON-NLS-1$
-
-			// Items
-			List elementIDs = metadata.getElementIDsInGroupID(groupID1);
-			List elementSymbols = createElements(elementIDs);
-
-			// Supplier
-			elementIDs = metadata.getElementIDsInGroupID(groupID2);
-			List supplierElementSymbols = createElements(elementIDs);
-
-			// Orders
-			elementIDs = metadata.getElementIDsInGroupID(groupID3);
-			List ordersElementSymbols = createElements(elementIDs);
-
-			// Item_supplier
-			elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
-			List itemSupplierElementSymbols = createElements(elementIDs);
-
-			// Item_order
-			elementIDs = metadata.getElementIDsInGroupID(groupID1_3join);
-			List itemOrderElementSymbols = createElements(elementIDs);
-        
-			dataMgr.registerTuples(
-				groupID1,
-				elementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
-
-			dataMgr.registerTuples(
-				groupID1_2join,
-				itemSupplierElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					} );    
-
-
-			dataMgr.registerTuples(
-				groupID2,
-				supplierElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
-
-			dataMgr.registerTuples(
-				groupID3,
-				ordersElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "1", "KMart", "12345" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "2", "Sun", "94040" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "3", "Cisco", "94041" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "4", "Doc", "94042" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "5", "Excite", "21098" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "6", "Yahoo", "94043" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "7", "Inktomi", "94044" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
-
-			dataMgr.registerTuples(
-				groupID1_3join,
-				itemOrderElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "1" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "2" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "3" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "4" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "5" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "6" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "003", "7" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					} );    
-
-
-
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
-        
-		return dataMgr;
-	}                    
-
-    /**
-     * Returned with some null values in the tuples, to test default/fixed attributes of nodes
-     * as well as nillable nodes
-     */
-    private FakeDataManager exampleDataManagerWithNulls(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }                    
-
-    public static FakeDataManager exampleDataManagerForSoap1(FakeMetadataFacade metadata, boolean makeEmpty) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("taxReport.TaxIDs"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            List[] tuples = null;
-            if (makeEmpty){
-                tuples = new List[0];
-            } else {
-                tuples = new List[] { 
-                    Arrays.asList( new Object[] { "1"} ),         //$NON-NLS-1$
-                    Arrays.asList( new Object[] { "2" } ),         //$NON-NLS-1$
-                    Arrays.asList( new Object[] { "3" } ),         //$NON-NLS-1$
-                    };
-            }
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                tuples );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    } 
-
-    /** data has a null value */
-    private FakeDataManager exampleDataManager_8917(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    } 
-
-    /** data has a NON-EMPTY WHITESPACE string */
-    private FakeDataManager exampleDataManager_8917a(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }
-
-    /** data has an EMPTY STRING */
-    private FakeDataManager exampleDataManager_8917b(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }    
-    
-	/**
-	 * Duplicate records in data
-	 * @param metadata
-	 * @return FakeDataManager
-	 */
-	private FakeDataManager exampleDataManagerWithDuplicates(FakeMetadataFacade metadata) {
-		FakeDataManager dataMgr = new FakeDataManager();
-    
-		try { 
-			// Group stock.items
-			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-			List elementIDs = metadata.getElementIDsInGroupID(groupID);
-			List elementSymbols = createElements(elementIDs);
-        
-			dataMgr.registerTuples(
-				groupID,
-				elementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "002", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
-
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
-        
-		return dataMgr;
-	}                    
-
-	/**
-	 *
-	 * Duplicate records in data to test more than two order by elements at the same depth
-	 * @param metadata
-	 * @return FakeDataManager
-     */
-	private FakeDataManager exampleDataManagerWithDuplicates1(FakeMetadataFacade metadata) {
-		FakeDataManager dataMgr = new FakeDataManager();
-    
-		try { 
-			// Group stock.items
-			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-			List elementIDs = metadata.getElementIDsInGroupID(groupID);
-			List elementSymbols = createElements(elementIDs);
-        
-			dataMgr.registerTuples(
-				groupID,
-				elementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "003", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "001", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
-
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
-        
-		return dataMgr;
-	}                   
-		
-    /**
-     * Deluxe example
-     */
-    private FakeDataManager exampleDataManagerDuJour(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", "Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }   
-
-    public static FakeDataManager exampleXQTDataManager(FakeMetadataFacade metadata) throws Exception {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        // Group stock.items
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("xqt.data"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List xqtData = createElements(elementIDs);
-    
-        dataMgr.registerTuples(
-            groupID,
-            xqtData,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { new Integer(1),  new Integer(-2), "-2" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(2),  new Integer(-1), null } ),        
-                Arrays.asList( new Object[] { new Integer(3),  null,            "0" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(4),  new Integer(1),  "1" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(5),  new Integer(2),  "2" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(6),  new Integer(3),  "3" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(7),  new Integer(4),  "4" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(8),  new Integer(5),  null } ),        
-                Arrays.asList( new Object[] { new Integer(9),  null,            "6" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(10), new Integer(7),  "7" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(11), new Integer(8),  "8" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(12), new Integer(9),  "9" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(13), new Integer(10), "10" } ),         //$NON-NLS-1$
-                } );    
-
-        return dataMgr;
-    }                    
-
-    public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException { 
-        QueryParser parser = new QueryParser();
-        Command command = parser.parseCommand(sql);
-        QueryResolver.resolveCommand(command, metadata);
-        command = QueryRewriter.rewrite(command, metadata, null);
-        return command;
-    }
-
-    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr) throws Exception{
-        return helpTestProcess(sql, expectedDoc, metadata, dataMgr, null);
-    }
-
-    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException) throws Exception{
-
-        return helpTestProcess(sql, metadata, dataMgr, expectedException, new DefaultCapabilitiesFinder(), expectedDoc);
-    }
-
-    static ProcessorPlan helpTestProcess(String sql, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException, CapabilitiesFinder capFinder, String... expectedDoc) throws Exception{
-        Command command = helpGetCommand(sql, metadata);
-        AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
-
-        try {
-            CommandContext planningContext = new CommandContext(); //this should be the same as the processing context, but that's not easy to do
-            planningContext.setMetadata(new TempMetadataAdapter(metadata, new TempMetadataStore()));
-            ProcessorPlan plan = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, planningContext);
-            
-            if(DEBUG) {
-                System.out.println(analysisRecord.getDebugLog());
-            }
-            List[] expected = new List[expectedDoc.length];
-            for (int i = 0; i < expectedDoc.length; i++) {
-				expected[i] = Arrays.asList(expectedDoc[i]);
-			}
-            TestProcessor.helpProcess(plan, planningContext, dataMgr, expected);
-            assertNull("Expected failure", expectedException);
-            return plan;
-        } catch (Exception e) {
-        	if (expectedException == null) {
-        		throw e;
-        	}
-        	assertTrue(expectedException.isInstance(e));
-        } finally {
-            if(DEBUG) {
-                System.out.println(analysisRecord.getDebugLog());
-            }                
-        }
-        return null;
-    }
-
-    // =============================================================================================
-    // T E S T S 
-    // =============================================================================================
-
-    @Test public void test1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testOrderBy1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testOrderBy1a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT \"xml\" FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testOrderBy1b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT xmltest.doc1.xml FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-               
-    @Test public void testOrderBy2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testOrderBy3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID DESC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-    
-    @Test public void testOrderBy3a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }      
-    
-    @Test public void testOrderBy4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }     
-     
-    @Test public void testOrderBy5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-         String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-          
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    } 
-    
-    @Test public void testOrderBy6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-   
-    //order by with temp group at the root    
-    @Test public void testOrderBy7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        helpTestProcess("SELECT * FROM xmltest.doc9a ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-           
-    //order by with multiple elements and criteria with long name, short name doesn't work
-    @Test public void testOrderBy8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +   //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Catalogs.Catalog.Items.Item.Quantity < 60 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    /*    
-    @Test public void testOrderBy9() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = "";
-          
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "Unable to resolve element: Quantity";
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Quantity < 60 ORDER BY ItemID ASC, SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
-    }
-    */
-  
-    @Test public void testOrderBy10() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Quantity < 60 ORDER BY Name DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }     
-    
-     @Test public void testOrderBy11() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID='001' OR ItemID='002' OR ItemID='003' ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    @Test public void testOrderBy13() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name DESC, Quantity ASC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-        
-    @Test public void testOrderBy14() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-                "<Catalogs>\r\n" + //$NON-NLS-1$
-                "    <Catalog>\r\n" +  //$NON-NLS-1$
-                "        <Items>\r\n" + //$NON-NLS-1$
-                "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-                "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-                "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-                "                <Suppliers>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" +  //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                </Suppliers>\r\n" + //$NON-NLS-1$
-                "            </Item>\r\n" +                  //$NON-NLS-1$
-                "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-                "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-                "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-                "                <Suppliers>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" +  //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                </Suppliers>\r\n" + //$NON-NLS-1$
-                "            </Item>\r\n" +  //$NON-NLS-1$
-                "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-                "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-                "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-                "                <Suppliers>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-                "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                </Suppliers>\r\n" + //$NON-NLS-1$
-                "            </Item>\r\n" +  //$NON-NLS-1$
-                "        </Items>\r\n" +  //$NON-NLS-1$
-                "    </Catalog>\r\n" +  //$NON-NLS-1$
-                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-     
-    @Test public void testOrderBy15() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +      //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /** test null elements*/
-    @Test public void testOrderBy17() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity ASC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    /**  test duplicate elements*/
-    @Test public void testOrderBy18() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithDuplicates(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    /**  test more than two parallel elements*/
-    @Test public void testOrderBy19() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithDuplicates1(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY ItemID ASC, Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testOrderBy20() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc =
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +           //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +         //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-               
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
-            + "ORDER BY SupplierID ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }         
-    
-    /**
-     * Doc nodes that are not mapped to data cannot be used in the 
-     * ORDER BY clause of an XML doc query
-     */
-    @Test public void testOrderBy_defect9803() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-               
-        try {
-            helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
-                + "ORDER BY Suppliers", //$NON-NLS-1$
-                "", metadata, dataMgr);  //$NON-NLS-1$
-            fail("Should have failed with QueryPlannerException but didn't"); //$NON-NLS-1$
-        } catch (QueryPlannerException e) {
-            String expectedMsg = "The XML document element [element] name='Suppliers' minOccurs=1 maxOccurs=1 is not mapped to data and cannot be used in the ORDER BY clause: ORDER BY Suppliers"; //$NON-NLS-1$
-            assertEquals(expectedMsg, e.getMessage());
-        }  
-    }    
-        
-    //defect 8130
-    @Test public void test1CriteriaWithUnmappedElementFails() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Catalog = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
-    }    
-
-    //defect 8130
-    @Test public void test1CriteriaWithUnmappedElementFails2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Item = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
-    }  
-    
-    @Test public void testNested() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    private static final String EXPECTED_DOC_NESTED_2 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-    private static final String EXPECTED_DOC_NESTED_3 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-    @Test public void testNested2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2;
-        helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /**
-     * Tests a couple temp groups at the root - B selects from A, and a mapping class
-     * selects from B
-     */
-    @Test public void testNested2aTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2;
-        helpTestProcess("SELECT * FROM xmltest.doc9a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    @Test public void testNested2aTempGroupCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </Catalog>\r\n" +  //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = 1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    /** defect 13172, CSE Case 1811 */
-    @Test public void testNested2aTempGroupCompoundCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-//        "                        <Orders>\r\n" + //$NON-NLS-1$
-//        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-//        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-//        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-//        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-//        "                            </Order>\r\n" + //$NON-NLS-1$
-//        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </Catalog>\r\n" +  //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = '1' AND tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /** defect 13172, CSE Case 1811 */
-    @Test public void testNested2aTempGroupCompoundCriteria1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-//        "                        <Orders>\r\n" + //$NON-NLS-1$
-//        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-//        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-//        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-//        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-//        "                            </Order>\r\n" + //$NON-NLS-1$
-//        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </Catalog>\r\n" +  //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = 1 AND tempGroup.orders.orderQty = 87", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /** defect 13172, CSE Case 1811 */
-    @Test public void testNested2aTempGroupCompoundCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-//        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </Catalog>\r\n" +  //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = '1' OR tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2cTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_3;
-        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID = '001'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    /**
-     * Tests a temp group C that selects from a root temp group, plus has bindings to
-     * some ancestor mapping classes ( we no longer support bindings on staging tables)
-     */
-    public void defer_testNested2bTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2;
-        helpTestProcess("SELECT * FROM xmltest.doc9b", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    @Test public void testNested2WithCriteria() throws Exception {
-
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='001'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * <p>This test illustrates how to use the context operator
-     * to specify that the result set to limit is the same as the
-     * result set which the criteria originates from, when that
-     * result set is nested below the top level.
-     * Test {@link #testNested2WithCriteria2a} shows a similar
-     * query without the context operator.</p>
-     * 
-     * @see #testNested2WithCriteria2a
-     */
-    @Test public void testNested2WithCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        XMLPlan plan = (XMLPlan)helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-
-        // check the staging base line (unknown cost)
-        // one for staging and for unloading
-        Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
-        assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
-    }
-
-    /**
-     * <p>This test illustrates how to use the context operator
-     * to specify that the result set to limit is the same as the
-     * result set which the criteria originates from, when that
-     * result set is nested below the top level.
-     * Test {@link #testNested2WithCriteria2a} shows a similar
-     * query without the context operator.</p>
-     * 
-     * <p>defect 9802, trying different ways of qualifying 1st arg
-     * to context operator</p>
-     * 
-     * @see #testNested2WithCriteria2a
-     */
-    @Test public void testNested2WithCriteria2_defect9802() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Supplier.SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }    
-    
-    /**
-     * <p>Same as {@link #testNested2WithCriteria2} but with a
-     * type conversion on the right expression from integer to string.
-     * This demonstrates a function of only constants is executed in
-     * an XML criteria.</p>
-     * shows a similar
-     * @see #testNested2WithCriteria2
-     */
-    @Test public void testNested2WithCriteria2_function() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc =
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" + //$NON-NLS-1$
-            "        <Items>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" + //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" + //$NON-NLS-1$
-            "    </Catalog>\r\n" + //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)=convert(52, string)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    /**
-     * <p>This tests the unintuitive effects of specifying a user
-     * criteria on a node inside a nested mapping class.  Here, the 
-     * "Item" fragment is repeated, but the "Supplier" fragment inside
-     * is limited by the criteria.  
-     * Test {@link #testNested2WithCriteria2} shows how to use
-     * the "context" syntax to control what context the criteria
-     * is used to restrict.</p>
-     * 
-     * <P>UPDATE: With 3.0 sp1 the default behavior is changed.
-     * Now, if "context" syntax is not used, the outer context (anchored 
-     * at "Item" node) will be limited by default, instead of the one
-     * the criteria is actually specified on.</p>
-     */
-    @Test public void testNested2WithCriteria2a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE SupplierID='52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-
-    @Test public void testNested2WithContextCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, SupplierID)='52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-//            "                                <OrderStatus/>\r\n" +
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-
-    @Test public void testNested2WithContextCriteria4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria4a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR OrderID='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria4b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-    @Test public void testNested2WithContextCriteria5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria5a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria5b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    public static String readFile(String fileName) throws Exception {
-        FileInputStream fis = new FileInputStream(UnitTestUtil.getTestDataFile(fileName));
-        
-        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-        
-        int c = 0;
-        while ((c = fis.read()) != -1) {
-            baos.write(c);
-        }
-        
-        return baos.toString();
-    }
-
-    @Test public void testNested2WithContextCriteria5Fail() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = ""; //doesn't matter //$NON-NLS-1$
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryPlannerException.class;
-        String shouldFailMsg = "expected failure since two different contexts were specified in conjunct"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(SupplierID, OrderID)='2'", expectedDoc, metadata, dataMgr, expectedException);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items/>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' AND context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria6b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items/>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' AND OrderID='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    //WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'
-    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-    @Test public void testNested2WithContextCriteria7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNested2WithContextCriteria7b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
-        String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
-         + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='5' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
-        helpTestProcess(query, expectedDoc, metadata, dataMgr);        
-    }
-
-    @Test public void testNested2WithContextCriteria7c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
-        String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
-         + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='6' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
-        helpTestProcess(query, expectedDoc, metadata, dataMgr);    
-    }
-
-    /**
-     * per defect 7333
-     */
-    @Test public void testNested2WithContextCriteria_7333() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='4' AND ItemID='003'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * per defect 7333
-     */
-    @Test public void testNested2WithContextCriteria_7333b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='003' AND OrderID='4'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * per defect 7333
-     */
-    @Test public void testNested2WithContextCriteria_7333c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items/>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' AND ItemID='003'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * per defect 7333
-     */
-    @Test public void testNested2WithContextCriteria_7333d() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items/>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='003' AND OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * Select a single item, and then limit the suppliers based on an order #
-     */
-    @Test public void testNested2WithContextCriteria8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Context(Supplier,OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testNestedWithChoice() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc10", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /**
-     * Does not use 'context' operator
-     */
-    @Test public void testNestedWithChoiceAndCriteria2_6796() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc10 where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /**
-     * Uses the 'context' operator
-     */
-    @Test public void testNestedWithChoiceAndCriteria2a_6796() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc10 where context(Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /**
-     * Does not use 'context' operator
-     */
-    @Test public void testNestedWithLookupChoice() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
-            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc10L where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-    
-    @Test public void test1Unformatted() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
-            "<Catalog>" +  //$NON-NLS-1$
-            "<Items>" +  //$NON-NLS-1$
-            "<Item ItemID=\"001\">" +  //$NON-NLS-1$
-            "<Name>Lamp</Name>" +  //$NON-NLS-1$
-            "<Quantity>5</Quantity>" +  //$NON-NLS-1$
-            "</Item>" +  //$NON-NLS-1$
-            "<Item ItemID=\"002\">" +  //$NON-NLS-1$
-            "<Name>Screwdriver</Name>" +  //$NON-NLS-1$
-            "<Quantity>100</Quantity>" +  //$NON-NLS-1$
-            "</Item>" +  //$NON-NLS-1$
-            "<Item ItemID=\"003\">" +  //$NON-NLS-1$
-            "<Name>Goat</Name>" +  //$NON-NLS-1$
-            "<Quantity>4</Quantity>" +  //$NON-NLS-1$
-            "</Item>" +  //$NON-NLS-1$
-            "</Items>" +  //$NON-NLS-1$
-            "</Catalog>" +  //$NON-NLS-1$
-            "</Catalogs>\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1Unformatted", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-
-    // jhTODO: complete this
-
-    @Test public void testChoice_5266a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" +  //$NON-NLS-1$
-            "   <Catalog>\r\n" +  //$NON-NLS-1$
-            "      <Items>\r\n" +  //$NON-NLS-1$
-            "         <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "            <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "            <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            <Suppliers>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"51\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Chucky</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>11111</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"52\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Biff's Stuff</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>22222</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"53\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>AAAA</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>33333</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "            </Suppliers>\r\n" +  //$NON-NLS-1$
-            "         </Item>\r\n" +  //$NON-NLS-1$
-            "         <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "            <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "            <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            <Suppliers>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"54\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Nugent Co.</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>44444</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"55\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Zeta</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>55555</Zip>\r\n" +  //$NON-NLS-1$\r\n" 
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$\r\n" +  
-            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "            </Suppliers>\r\n" +  //$NON-NLS-1$
-            "         </Item>\r\n" +  //$NON-NLS-1$
-            "         <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "            <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "            <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            <Suppliers>\r\n" +  //$NON-NLS-1$
-            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
-            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$
-            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
-            "                  <ProcessingOrders>\r\n" +  //$NON-NLS-1$
-            "                     <Order OrderID=\"4\">\r\n" +  //$NON-NLS-1$
-            "                        <OrderDate>05/31/02</OrderDate>\r\n" +  //$NON-NLS-1$
-            "                        <OrderQuantity>9</OrderQuantity>\r\n" +  //$NON-NLS-1$
-            "                     </Order>\r\n" +  //$NON-NLS-1$
-            "                  </ProcessingOrders>\r\n" +  //$NON-NLS-1$
-            "               </Supplier>\r\n" +  //$NON-NLS-1$
-            "            </Suppliers>\r\n" +  //$NON-NLS-1$
-            "         </Item>\r\n" +  //$NON-NLS-1$
-            "      </Items>\r\n" +  //$NON-NLS-1$
-            "   </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc_5266a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    
-    @Test public void test1WithCriteriaShortName() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE quantity < 50", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test1WithCriteriaLongName() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE catalogs.catalog.items.item.quantity < 50", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test2a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc2a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test2b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        helpTestProcess("SELECT * FROM xmltest.doc2b", null, metadata, dataMgr, TeiidComponentException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void test2c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item2>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc2c", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test2d() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item2>\r\n" +   //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc2d", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void test2e() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item2>\r\n" +   //$NON-NLS-1$
-            "            <ItemDefault ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </ItemDefault>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc2e", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testWithNillableNode() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testWithDefault() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>1</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc3", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testWithNamespaces() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>1</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "    <duh:Fake xmlns:duh=\"http://www.duh.org/duh\" xmlns:duh2=\"http://www.duh2.org/duh2\"\n" + //$NON-NLS-1$
-            "              xmlns=\"http://www.default.org/default\">fixed constant value<duh:FakeChild2>\r\n" +  //$NON-NLS-1$
-            "            <FakeChild2a>another fixed constant value</FakeChild2a>\r\n" +  //$NON-NLS-1$
-            "        </duh:FakeChild2>\r\n" +  //$NON-NLS-1$
-            "        <FakeChild3 xmlns:duh=\"http://www.duh.org/duh/duh\" duh:FakeAtt=\"fixed att value\"/>\r\n" +  //$NON-NLS-1$
-            "    </duh:Fake>\r\n" + //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc4", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testWithNewIter3Properties() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc5", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testWithNewIter3PropertiesException() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
-        
-        Command command = helpGetCommand("SELECT * FROM xmltest.doc6", metadata); //$NON-NLS-1$
-        XMLPlan plan = TestXMLPlanner.preparePlan(command, metadata, new DefaultCapabilitiesFinder(), null);
-
-        BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
-        CommandContext context = new CommandContext("pID", null, null, null, 1);                                 //$NON-NLS-1$
-        QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataMgr);
-        processor.setNonBlocking(true);
-        BatchCollector collector = processor.createBatchCollector();
-        TeiidComponentException failOnDefaultException = null;
-        try{
-            collector.collectTuples();
-        } catch (TeiidComponentException e){
-            failOnDefaultException = e;
-        }
-        
-        assertNotNull("Query processing should have failed on default of choice node.", failOnDefaultException); //$NON-NLS-1$
-    }
-
-    @Test public void testAttributeBug() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<FixedValueTest>\r\n" + //$NON-NLS-1$
-            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
-            "        <key>001</key>\r\n" + //$NON-NLS-1$
-            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
-            "    </wrapper>\r\n" + //$NON-NLS-1$
-            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
-            "        <key>002</key>\r\n" + //$NON-NLS-1$
-            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
-            "    </wrapper>\r\n" + //$NON-NLS-1$
-            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
-            "        <key>003</key>\r\n" + //$NON-NLS-1$
-            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
-            "    </wrapper>\r\n" + //$NON-NLS-1$
-            "</FixedValueTest>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc7", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testMultipleDocs() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc1 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "    <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "    <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "    <Suppliers>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "            <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "            <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "            <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "    </Suppliers>\r\n" + //$NON-NLS-1$
-            "</Item>\r\n\r\n";  //$NON-NLS-1$
-
-        String expectedDoc2 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "    <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "    <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "    <Suppliers>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "            <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "            <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "    </Suppliers>\r\n" + //$NON-NLS-1$
-            "</Item>\r\n\r\n"; //$NON-NLS-1$
-            
-        String expectedDoc3 = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "    <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "    <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "    <Suppliers>\r\n" + //$NON-NLS-1$
-            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "        </Supplier>\r\n" + //$NON-NLS-1$
-            "    </Suppliers>\r\n" + //$NON-NLS-1$
-            "</Item>\r\n\r\n"; //$NON-NLS-1$
-
-
-        helpTestProcess("SELECT * FROM xmltest.doc11", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3);         //$NON-NLS-1$
-    }
-
-    @Test public void testRecursive() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates>\r\n" + //$NON-NLS-1$
-            "                            <Employee ID=\"06\">\r\n" +  //$NON-NLS-1$
-            "                                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                                <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
-            "                                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                                    <Employee ID=\"11\">\r\n" +  //$NON-NLS-1$
-            "                                        <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
-            "                                        <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
-            "                                        <Subordinates>\r\n" + //$NON-NLS-1$
-            "                                            <Employee ID=\"13\">\r\n" +  //$NON-NLS-1$
-            "                                                <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
-            "                                                <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
-            "                                                <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                                            </Employee>\r\n" +  //$NON-NLS-1$
-            "                                        </Subordinates>\r\n" + //$NON-NLS-1$
-            "                                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                                    <Employee ID=\"12\">\r\n" +  //$NON-NLS-1$
-            "                                        <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
-            "                                        <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
-            "                                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                                </Subordinates>\r\n" + //$NON-NLS-1$
-            "                            </Employee>\r\n" +  //$NON-NLS-1$
-            "                        </Subordinates>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc12", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    @Test public void testRecursiveA() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Subordinate ID=\"02\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Subordinate ID=\"04\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates>\r\n" + //$NON-NLS-1$
-            "                            <Subordinate ID=\"06\">\r\n" +  //$NON-NLS-1$
-            "                                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                                <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
-            "                                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                                    <Subordinate ID=\"11\">\r\n" +  //$NON-NLS-1$
-            "                                        <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
-            "                                        <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
-            "                                        <Subordinates>\r\n" + //$NON-NLS-1$
-            "                                            <Subordinate ID=\"13\">\r\n" +  //$NON-NLS-1$
-            "                                                <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
-            "                                                <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
-            "                                                <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                                            </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                                        </Subordinates>\r\n" + //$NON-NLS-1$
-            "                                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                                    <Subordinate ID=\"12\">\r\n" +  //$NON-NLS-1$
-            "                                        <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
-            "                                        <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
-            "                                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                                </Subordinates>\r\n" + //$NON-NLS-1$
-            "                            </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                        </Subordinates>\r\n" + //$NON-NLS-1$
-            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Subordinate>\r\n" +  //$NON-NLS-1$
-            "            <Subordinate ID=\"03\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Subordinate ID=\"05\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Subordinate>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Subordinate ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Subordinate ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                    <Subordinate ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Subordinate>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc12a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }    
-    
-    /**
-     * 4/25/05 sbale - This failing test raises a question about recursion
-     * termination criteria - should the chunk of document that meets the 
-     * criteria be included or not?  In this test below, it is expected to
-     * be included, but is not included in actual results due to recent
-     * changes for Booz Allen POC.  I could see it going either way.
-     *  
-     * sbale 4/27/05 I have changed expected results as a result of changes for
-     * Booz Allen POC.  Previously, the recursive fragment of the document that
-     * satisfied the recursion termination criteria was included, now it is not.
-     * See commented out section below for previous expected results. 
-     * @throws Exception
-     */
-    @Test public void testRecursive2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates/>\r\n" + //$NON-NLS-1$
-//            "                <Subordinates>\r\n" + //$NON-NLS-1$
-//            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
-//            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-//            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-//            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-//            "                    </Employee>\r\n" +  //$NON-NLS-1$
-//            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc13", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-    @Test public void testRecursive3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc14", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    @Test public void testRecursive4Exception() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        helpTestProcess("SELECT * FROM xmltest.doc15", null, metadata, dataMgr, TeiidComponentException.class); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /**
-     * Seems to be failing as a result of changes for defect 12288 
-     */
-    @Test public void testRecursive5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Employees>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "        <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        </Supervisor>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "        <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "            <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
-            "                <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "            </Supervisor>\r\n" + //$NON-NLS-1$
-            "        </Supervisor>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "        <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "            <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
-            "                <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "            </Supervisor>\r\n" + //$NON-NLS-1$
-            "        </Supervisor>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</Employees>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc16", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    /**
-     * sbale 4/27/05 I have changed expected results as a result of changes for
-     * Booz Allen POC.  Previously, the recursive fragment of the document that
-     * satisfied the recursion termination criteria was included, now it is not.
-     * See commented out section below for previous expected results. 
-     * @throws Exception
-     */
-    @Test public void testRecursiveWithStagingTable_defect15607() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates/>\r\n" + //$NON-NLS-1$
-//            "                <Subordinates>\r\n" + //$NON-NLS-1$
-//            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
-//            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
-//            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
-//            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-//            "                    </Employee>\r\n" +  //$NON-NLS-1$
-//            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
-            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
-            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
-            "        <Subordinates>\r\n" + //$NON-NLS-1$
-            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
-            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
-            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
-            "                <Subordinates>\r\n" + //$NON-NLS-1$
-            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
-            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
-            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
-            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
-            "                    </Employee>\r\n" +  //$NON-NLS-1$
-            "                </Subordinates>\r\n" + //$NON-NLS-1$
-            "            </Employee>\r\n" +  //$NON-NLS-1$
-            "        </Subordinates>\r\n" + //$NON-NLS-1$
-            "    </Employee>\r\n" +  //$NON-NLS-1$
-            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc19", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-    
-    /**
-     * Tests a recursive nested mapping class within a recursive mapping class, where
-     * all nested "anchor" nodes are named "srcNestedRecursive".  Test of defect #5988
-     */
-    @Test public void testXQTRecursive_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
-        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<recursiveTest>\r\n" +  //$NON-NLS-1$
-            "    <src>\r\n" + //$NON-NLS-1$
-            "        <key>13</key>\r\n" + //$NON-NLS-1$
-            "        <data>10</data>\r\n" + //$NON-NLS-1$
-            "        <srcNested>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "            </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "        </srcNested>\r\n" + //$NON-NLS-1$
-            "        <srcRecursive>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcNested>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "            </srcNested>\r\n" + //$NON-NLS-1$
-            "            <srcRecursive>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcNested>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
-            "                </srcNested>\r\n" + //$NON-NLS-1$
-            "                <srcRecursive>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNested>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNested>\r\n" + //$NON-NLS-1$
-            "                    <srcRecursive>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcRecursive>\r\n" + //$NON-NLS-1$
-            "                </srcRecursive>\r\n" + //$NON-NLS-1$
-            "            </srcRecursive>\r\n" + //$NON-NLS-1$
-            "        </srcRecursive>\r\n" + //$NON-NLS-1$
-            "    </src>\r\n" + //$NON-NLS-1$
-            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xqttest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    /**
-     * Tests a non-recursive nested mapping class within a recursive mapping class, where
-     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
-     */
-    public void DEFER_testXQTRecursive1a_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
-        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<recursiveTest>\r\n" +  //$NON-NLS-1$
-            "    <src>\r\n" + //$NON-NLS-1$
-            "        <key>13</key>\r\n" + //$NON-NLS-1$
-            "        <data>10</data>\r\n" + //$NON-NLS-1$
-            "        <srcNested>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "        </srcNested>\r\n" + //$NON-NLS-1$
-            "        <srcNested>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcNested>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "            </srcNested>\r\n" + //$NON-NLS-1$
-            "            <srcNested>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcNested>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                </srcNested>\r\n" + //$NON-NLS-1$
-            "                <srcNested>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNested>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNested>\r\n" + //$NON-NLS-1$
-            "                    <srcNested>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNested>\r\n" + //$NON-NLS-1$
-            "                </srcNested>\r\n" + //$NON-NLS-1$
-            "            </srcNested>\r\n" + //$NON-NLS-1$
-            "        </srcNested>\r\n" + //$NON-NLS-1$
-            "    </src>\r\n" + //$NON-NLS-1$
-            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xqttest.doc1a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    /**
-     * Tests a non-recursive nested mapping class within a recursive mapping class, where
-     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
-     */
-    @Test public void testXQTRecursive2_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
-        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<recursiveTest>\r\n" +  //$NON-NLS-1$
-            "    <src>\r\n" + //$NON-NLS-1$
-            "        <key>13</key>\r\n" + //$NON-NLS-1$
-            "        <data>10</data>\r\n" + //$NON-NLS-1$
-            "        <srcNested>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "        </srcNested>\r\n" + //$NON-NLS-1$
-            "        <srcNested>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcNested>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "            </srcNested>\r\n" + //$NON-NLS-1$
-            "            <srcNested>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcNested>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                </srcNested>\r\n" + //$NON-NLS-1$
-            "                <srcNested>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcNested>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNested>\r\n" + //$NON-NLS-1$
-            "                    <srcNested>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcNested>\r\n" + //$NON-NLS-1$
-            "                </srcNested>\r\n" + //$NON-NLS-1$
-            "            </srcNested>\r\n" + //$NON-NLS-1$
-            "        </srcNested>\r\n" + //$NON-NLS-1$
-            "    </src>\r\n" + //$NON-NLS-1$
-            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xqttest.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-
-    /**
-     * for defect 5988
-     */
-    @Test public void testXQTRecursiveSiblings_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
-        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<recursiveTest>\r\n" +  //$NON-NLS-1$
-            "    <src>\r\n" + //$NON-NLS-1$
-            "        <key>13</key>\r\n" + //$NON-NLS-1$
-            "        <data>10</data>\r\n" + //$NON-NLS-1$
-            "        <srcSibling1>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling2>\r\n" + //$NON-NLS-1$
-            "            </srcSibling1>\r\n" + //$NON-NLS-1$
-            "            <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling2>\r\n" + //$NON-NLS-1$
-            "            </srcSibling2>\r\n" + //$NON-NLS-1$
-            "        </srcSibling1>\r\n" + //$NON-NLS-1$
-            "        <srcSibling2>\r\n" + //$NON-NLS-1$
-            "            <key>10</key>\r\n" + //$NON-NLS-1$
-            "            <data>7</data>\r\n" + //$NON-NLS-1$
-            "            <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling2>\r\n" + //$NON-NLS-1$
-            "            </srcSibling1>\r\n" + //$NON-NLS-1$
-            "            <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                <key>7</key>\r\n" + //$NON-NLS-1$
-            "                <data>4</data>\r\n" + //$NON-NLS-1$
-            "                <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                    <key>4</key>\r\n" + //$NON-NLS-1$
-            "                    <data>1</data>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
-            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
-            "                        <key>1</key>\r\n" + //$NON-NLS-1$
-            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
-            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
-            "                </srcSibling2>\r\n" + //$NON-NLS-1$
-            "            </srcSibling2>\r\n" + //$NON-NLS-1$
-            "        </srcSibling2>\r\n" + //$NON-NLS-1$
-            "    </src>\r\n" + //$NON-NLS-1$
-            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xqttest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
-
-    @Test public void testSelectElement1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-          
-        helpTestProcess("SELECT Name FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-     
-    @Test public void testSelectElement2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-                
-        helpTestProcess("SELECT SupplierID, OrderID, ItemID, OrderQuantity FROM xmltest.doc9 ORDER BY "+ //$NON-NLS-1$
-            " Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
-            " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
-    }
-    
-    /** select element in the reverse order of depth*/
-    @Test public void testSelectElement3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-                
-        helpTestProcess("SELECT OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9"  + //$NON-NLS-1$
-            " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
-            " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
-    }
-    
-    /** two select elements at the same level*/
-    @Test public void testSelectElement4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-          
-        helpTestProcess("SELECT ItemID, Name, Quantity FROM xmltest.doc1 WHERE ItemID='001' OR "  //$NON-NLS-1$
-            + " ItemID='002' OR ItemID='003' ORDER BY ItemID", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** defect 9756 */
-    @Test public void testSelectElement4_defect9756() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\"/>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\"/>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\"/>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-          
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc1", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }    
-    
-    /** three select elements with two of them at the same level and there are other nodes with the same name*/
-    @Test public void testSelectElement5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" +          //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" +            //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" +          //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" +        //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" +            //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-                
-        helpTestProcess("SELECT OrderQuantity, SupplierID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, OrderID, ItemID "  //$NON-NLS-1$
-            + "FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, "  //$NON-NLS-1$
-            + "OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
-    }
-    
-    /** check element.* case */
-    @Test public void testSelectElement6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-         
-        helpTestProcess("SELECT Item.* FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    /** check element.* case without attribute in order by*/
-    @Test public void testSelectElement6a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-         
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Quantity" //$NON-NLS-1$
-            + " FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testSelectElement7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-         
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID",  //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    @Test public void testSelectElement8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-         
-        helpTestProcess("SELECT xmltest.doc1.Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID",  //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** SELECT clause has element.*, but the sibling elements should not be included, only subtree should */
-    @Test public void testSelectElement9() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-      helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
-          + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' ", //$NON-NLS-1$
-          expectedDoc, metadata, dataMgr);        
-    }         
-    
-    @Test public void testSelectElement9a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
-            + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' AND Context(OrderID, OrderID)='5'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }    
-             
-    /** check element.* case with criteria and order by clause */
-    @Test public void testSelectElement10() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-         
-        helpTestProcess("SELECT Item.* FROM xmltest.doc1 WHERE Quantity <= 100 ORDER BY ItemID",  //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    @Test public void testSelectElement12() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT Supplier.*, ItemID FROM xmltest.doc9 "  //$NON-NLS-1$
-            + " WHERE ItemID='002'" //$NON-NLS-1$
-            + " ORDER BY SupplierID, OrderID DESC, ItemID", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);                
-    }
-    
-    @Test public void testSelectElement13() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT Name, Quantity FROM xmltest.doc1 "  //$NON-NLS-1$
-            + "WHERE ItemID='002'" //$NON-NLS-1$
-            + "ORDER BY Name ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);                
-    }
-
-    @Test public void testSelectElement14() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc =
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +           //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +         //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders/>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                        <Orders>\r\n" + //$NON-NLS-1$
-            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" +  //$NON-NLS-1$
-            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-            "                            </Order>\r\n" + //$NON-NLS-1$
-            "                        </Orders>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-               
-            helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000"  //$NON-NLS-1$
-                + " ORDER By SupplierID ASC, OrderID ",  //$NON-NLS-1$
-                expectedDoc, metadata, dataMgr);        
-    }
-    
-    @Test public void testSelectElement15() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc =
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-                "    <Catalog>\r\n" +  //$NON-NLS-1$
-                "        <Items>\r\n" +           //$NON-NLS-1$
-                "            <Item>\r\n" +  //$NON-NLS-1$
-                "                <Suppliers>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" +  //$NON-NLS-1$
-                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                </Suppliers>\r\n" + //$NON-NLS-1$
-                "            </Item>\r\n" +           //$NON-NLS-1$
-                "        </Items>\r\n" +  //$NON-NLS-1$
-                "    </Catalog>\r\n" +  //$NON-NLS-1$
-                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-               
-        helpTestProcess("SELECT Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
-            + " WHERE ItemID='002'" //$NON-NLS-1$
-            + " ORDER By SupplierID ",  //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-
-    @Test public void testSelectElement16() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc =
-                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-                "<Catalogs>\r\n" + //$NON-NLS-1$
-                "    <Catalog>\r\n" +  //$NON-NLS-1$
-                "        <Items>\r\n" +           //$NON-NLS-1$
-                "            <Item>\r\n" +  //$NON-NLS-1$
-                "                <Suppliers>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders/>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-                "                        <Orders>\r\n" + //$NON-NLS-1$
-                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" +  //$NON-NLS-1$
-                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-                "                            </Order>\r\n" + //$NON-NLS-1$
-                "                        </Orders>\r\n" + //$NON-NLS-1$
-                "                    </Supplier>\r\n" + //$NON-NLS-1$
-                "                </Suppliers>\r\n" + //$NON-NLS-1$
-                "            </Item>\r\n" +           //$NON-NLS-1$
-                "        </Items>\r\n" +  //$NON-NLS-1$
-                "    </Catalog>\r\n" +  //$NON-NLS-1$
-                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-               
-        helpTestProcess("SELECT Supplier.* FROM xmltest.doc9a "  //$NON-NLS-1$
-            + " WHERE ItemID='002'" //$NON-NLS-1$
-            + " ORDER By SupplierID",  //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }         
-
-    /**  CSE query 0 */
-    @Test public void testSelectElement17() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +             //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }   
-
-    /**  CSE query 1 */
-    @Test public void testSelectElement18() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9c WHERE ItemID='002'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }   
-
-    /**  CSE query 2 */
-    @Test public void testSelectElement19() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9c WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }   
-            
-
-    /**  CSE query 3 */
-    @Test public void testSelectElement20() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip" + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }   
-
-    /**  CSE query 3a */
-    @Test public void testSelectElement20a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +           //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Orders.Order.Zip" + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }   
-
-    /**  CSE query 4 */
-    @Test public void testSelectElement21() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +             //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-       
-        helpTestProcess("SELECT * " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' AND context(SupplierID, SupplierID)>'54' ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }  
-
-    /**  CSE query 4a */
-    @Test public void testSelectElement21a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        helpTestProcess("SELECT * " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE OrderID > '4' AND context(OrderID, OrderID)>'4'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }  
-    
-    /**  CSE query 5 */
-    @Test public void testSelectElement22() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +         //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '4' ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-    
-    /**  CSE query 5a */
-    @Test public void testSelectElement22a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +             //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Orders.Order.Name, OrderID  " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE OrderID > '3' ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-    
-    /**  CSE query 6 */
-    @Test public void testSelectElement23() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +      //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +         //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, SupplierID " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE OrderID > '4' ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-    
-    /**  CSE query 6a */
-    @Test public void testSelectElement23a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"4\"/>\r\n" +       //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"6\"/>\r\n" +   //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, OrderID " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-                     
-    /** test with order by and the element in the criteria is not in the select elements*/
-    @Test public void testSelectElement24() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"6\"/>\r\n" +               //$NON-NLS-1$
-            "                    <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"4\"/>\r\n" +   //$NON-NLS-1$
-            "                    <Order OrderID=\"3\"/>\r\n" +                   //$NON-NLS-1$
-            "                    <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ITEMID, OrderID " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-
-    /** test element.* with order by and the element in the criteria is not in the select elements*/
-    @Test public void testSelectElement24a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94044</Zip>\r\n" +             //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +                 //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +                 //$NON-NLS-1$
-            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, Order.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-                         
-    /** test with order by with only necessary sub-mapping classes are queried*/
-    @Test public void testSelectElement25() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\"/>\r\n" +                //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\"/>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\"/>\r\n" +                //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\"/>\r\n" +    //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\"/>\r\n" +                    //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\"/>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\"/>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT ItemID, SupplierID " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** test element.* with order by with only necessary sub-mapping classes are queried*/
-    @Test public void testSelectElement25a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +              //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT ItemID, Supplier.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** Test element.* with order by with only necessary sub-mapping classes are queried 
-     *  and case_insensitive nodes in the mapping tree
-     */
-    @Test public void testSelectElement25b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +              //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT ItemID, SUPPLIER.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    @Test public void testSelectElement26() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +              //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT ItemID, xmltest.doc9c.catalogs.catalog.items.item.suppliers.SUPPLIER.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-
-    /** test special elements: result set name, and name with format of "document.fully.qualified.element" 
-     * --> refer to Defect9497, this should fail
-     */
-    @Test public void testSelectElement27() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier/>\r\n" + //$NON-NLS-1$
-            "                    <Supplier/>\r\n" + //$NON-NLS-1$
-            "                    <Supplier/>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("SELECT doc9c.catalogs.catalog.items.item.itemID, items.item.name, item.Quantity, supplier " + //$NON-NLS-1$
-        " FROM xmltest.doc9c " + //$NON-NLS-1$
-        " WHERE doc9c.catalogs.catalog.items.item.suppliers.supplier.SupplierID > '54' AND itemID='002'" + //$NON-NLS-1$
-        " ORDER BY doc9c.catalogs.catalog.items.item.ITEMid ", //$NON-NLS-1$
-        expectedDoc, metadata, dataMgr);     
-    }
-        
-    /** test special element, root element */
-    @Test public void testSelectElement28() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT catalogs " +  //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);       
-        
-        /*String expectedDoc = "";
-        try {
-            helpTestProcess("SELECT catalogs " +
-                " FROM xmltest.doc9c " +
-                " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
-                expectedDoc, metadata, dataMgr);
-        } catch(QueryPlannerException qpe) {
-        // ok, as expected
-        } */         
-    }
-    
-    /** test special element */
-    @Test public void testSelectElement28a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc =  
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog/>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        /*String expectedDoc = "";
-        try {
-            helpTestProcess("SELECT catalog " +
-            " FROM xmltest.doc9c " +
-            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
-            expectedDoc, metadata, dataMgr, false);
-        } catch (QueryPlannerException qpe) {
-        // ok, as expected
-        } */
-        
-        helpTestProcess("SELECT catalog " +  //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);             
-    }
-
-    /** test model.document.* */
-    @Test public void testSelectElement28b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-            
-        helpTestProcess("SELECT xmltest.doc1.* " +  //$NON-NLS-1$
-            "FROM xmltest.doc1 ORDER BY ItemID ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);       
-
-    }
-        
-    /** test special element, root element */
-    @Test public void testSelectElement29() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT xmltest.doc9c.catalogs " +  //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);             
-        
-        /*String expectedDoc = "";
-        try {
-            helpTestProcess("SELECT xmltest.doc9c.catalogs " +
-            " FROM xmltest.doc9c " +
-            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
-            expectedDoc, metadata, dataMgr);
-        } catch (QueryPlannerException qpe) {
-        // ok, as expected
-        }*/
-
-    }
-    
-    /** test simple case for two elements in a mapping class */
-    @Test public void testSelectElement30() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT item.* FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }     
-                        
-    /** test NullPointerException*/
-    @Test public void testDefect_9496_1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +              //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT items.item.ItemID, suppliers.supplier.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY  ITEMid DESC, items.item.suppliers.supplier.SupplierID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-
-    @Test public void testDefect_9496_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                </Suppliers>\r\n" +             //$NON-NLS-1$
-            "            </Item>\r\n" +          //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +          //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +                          //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +  //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" +              //$NON-NLS-1$
-            "                    <Supplier>\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" +     //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT doc9c.Catalogs.catalog.items.item.ItemID, items.item.Suppliers,SuppliER.Name " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY ItemID DESC", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** test StringIndexOutOfBoundsException */
-    @Test public void testDefect_9496_3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +             //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" +              //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +         //$NON-NLS-1$
-            "                </Orders>\r\n" +    //$NON-NLS-1$
-            "            </Item>\r\n" + //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "                <Orders>\r\n" + //$NON-NLS-1$
-            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Order>\r\n" +  //$NON-NLS-1$
-            "                </Orders>\r\n" +            //$NON-NLS-1$
-            "            </Item>\r\n" +               //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        
-        helpTestProcess("SELECT item.itemID, items.item.* " + //$NON-NLS-1$
-            " FROM xmltest.doc9c " + //$NON-NLS-1$
-            " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
-            " ORDER BY  ITEMid, items.item.suppliers.supplier.SupplierID ", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }
-    
-    /** should fail: because there are other element other than "xml" */
-    /*@Test public void testResolver1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = ""; 
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
-        
-        helpTestProcess("SELECT xml, ItemID " +
-            " FROM xmltest.doc9c " +
-            " WHERE SupplierID > '54' " +
-            " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);          
-    }*/
-
-    /** should fail: partial qualified element name and "model.document.xml" */
-    /*@Test public void testResolver2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = ""; 
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
-        
-        helpTestProcess("SELECT item.ItemID, xmltest.doc9c.xml " +
-            " FROM xmltest.doc9c " +
-            " WHERE SupplierID > '54' " +
-            " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);          
-    }*/
-
-    /** should fail: test XMLResolver validatation for model.* */
-    /*@Test public void testDefect_9498_1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = ""; 
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "Unable to resolve element: xmltest";
-
-        helpTestProcess("SELECT xmltest.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
-    }*/
-
-    /** should fail: test XMLResolver validatation for model.document.* */
-    /*@Test public void testDefect_9498_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = ""; 
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "Unable to resolve element: xmltest.doc9c";
-
-        helpTestProcess("SELECT xmltest.doc9c.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);         
-    }*/
-
-    /** should fail: test XMLResolver validatation for xml.* */
-    /*@Test public void testDefect_9498_3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = ""; 
-
-        boolean shouldSucceed = false;
-        Class expectedException = QueryResolverException.class;
-        String shouldFailMsg = "Unable to resolve element: xml";
-
-        helpTestProcess("SELECT xml.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
-    }*/
-   
-    /** Test element.* with order by with only necessary sub-mapping classes are queried 
-     *  and case_insensitive nodes in the mapping tree
-     */
-    @Test public void testCommentNodeInDoc() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Root><!--Comment1--><Something><!--Comment2--></Something>\r\n" + //$NON-NLS-1$
-            "</Root>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc17", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    }    
-
-    private static final String EXPECTED_DOC_DEFECT_8917_AND_11789 = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </Catalog>\r\n" +  //$NON-NLS-1$
-        "    <OptionalCatalog>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </OptionalCatalog>\r\n" +  //$NON-NLS-1$
-        "    <OptionalCatalog2>\r\n" +  //$NON-NLS-1$
-        "        <Items>\r\n" +  //$NON-NLS-1$
-        "            <Item>\r\n" +  //$NON-NLS-1$
-        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </Items>\r\n" +  //$NON-NLS-1$
-        "    </OptionalCatalog2>\r\n" +  //$NON-NLS-1$
-        "    <Catalog4/>\r\n" +  //$NON-NLS-1$
-        "    <Catalog5>\r\n" +  //$NON-NLS-1$
-        "        <OptionalItems>\r\n" +  //$NON-NLS-1$
-        "            <Item>\r\n" +  //$NON-NLS-1$
-        "                <FixedName>Nugent</FixedName>\r\n" +  //$NON-NLS-1$
-        "            </Item>\r\n" +  //$NON-NLS-1$
-        "        </OptionalItems>\r\n" +  //$NON-NLS-1$
-        "    </Catalog5>\r\n" +              //$NON-NLS-1$
-        "    <Catalog6/>\r\n" +  //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-    @Test public void testDefect8917() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
-        
-//        helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
-        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
-        EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);        
-    } 
-    /*
-     * jhTODO
-     */
-    @Test public void testNillableOptional() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
-            "<Catalog>" +  //$NON-NLS-1$
-            "<Items xsi:nil=\"true\"/>" +  //$NON-NLS-1$
-            "</Catalog>" +  //$NON-NLS-1$
-            "</Catalogs>"; //$NON-NLS-1$
-       
-        // note: doc1b contains an 'items' element that is nillable = true, and minoccurs = 0 
-        helpTestProcess("SELECT * FROM xmltest.doc1b WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /*
-     * jhTODO
-     */
-    @Test public void testNillableNonOptional() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
-            "<Catalog>" +  //$NON-NLS-1$
-            "<Items xsi:nil=\"true\"/>" +  //$NON-NLS-1$
-            "</Catalog>" +  //$NON-NLS-1$
-            "</Catalogs>"; //$NON-NLS-1$
-        
-        // note: doc1c contains an 'items' element that has no nillable set, and minoccurs = 1 
-        helpTestProcess("SELECT * FROM xmltest.doc1c WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /** 
-     * Related to defect 8917
-     * The expected result is slightly different because the data has a
-     * NON-empty whitespace string, which will NOT be treated as null
-     * see also defect 15117
-     */
-    @Test public void testDefect11789() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager_8917a(metadata);
-
-        String expected = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "    <OptionalCatalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </OptionalCatalog>\r\n" +  //$NON-NLS-1$
-            "    <OptionalCatalog2>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </OptionalCatalog2>\r\n" +  //$NON-NLS-1$
-            "    <OptionalCatalog3>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </OptionalCatalog3>\r\n" +  //$NON-NLS-1$
-            "    <Catalog4>\r\n" +  //$NON-NLS-1$
-            "        <OptionalItems>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </OptionalItems>\r\n" +  //$NON-NLS-1$
-            "    </Catalog4>\r\n" +  //$NON-NLS-1$
-            "    <Catalog5>\r\n" +  //$NON-NLS-1$
-            "        <OptionalItems>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <FixedName>Nugent</FixedName>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </OptionalItems>\r\n" +  //$NON-NLS-1$
-            "    </Catalog5>\r\n" +              //$NON-NLS-1$
-            "    <Catalog6/>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$        
-        
-        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
-            expected, metadata, dataMgr);        
-    } 
-
-    /** 
-     * Related to defect 8917 - the result should be the same as 
-     * testDefect8917
-     */
-    @Test public void testDefect11789b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager_8917b(metadata);
-
-        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
-            EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);        
-    }    
-    
-    @Test public void testDefect9446() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item XXXXX=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <XXXXX/>\r\n" +  //$NON-NLS-1$
-            "                <XXXXX>5</XXXXX>\r\n" +           //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-//        helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
-        helpTestProcess("SELECT * FROM xmltest.doc_9446", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-
-    @Test public void testDefect9446_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items/>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc_9446 WHERE Catalogs.Catalog.Items.Item.XXXXX = '001'", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-
-    @Test public void testDefect_9530() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<mm:Catalogs xmlns:mm=\"http://www.duh.org/duh\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
-            "                     ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </mm:Item>\r\n" +  //$NON-NLS-1$
-            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
-            "                     ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
-            "            </mm:Item>\r\n" +  //$NON-NLS-1$
-            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
-            "                     ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
-            "            </mm:Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</mm:Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc_9530", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr);        
-    } 
-
-    @Test public void testSubqueryInXMLQueryCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"002\">\r\n" + 
-//            "                <Name>Screwdriver</Name>\r\n" + 
-//            "                <Quantity>100</Quantity>\r\n" + 
-//            "            </Item>\r\n" + 
-//            "            <Item ItemID=\"003\">\r\n" + 
-//            "                <Name>Goat</Name>\r\n" + 
-//            "                <Quantity>4</Quantity>\r\n" + 
-//            "            </Item>\r\n" + 
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryInXMLQueryCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"001\">\r\n" + 
-//            "                <Name>Lamp</Name>\r\n" + 
-//            "                <Quantity>5</Quantity>\r\n" + 
-//            "            </Item>\r\n" + 
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryInXMLQueryCriteria3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"001\">\r\n" + 
-//            "                <Name>Lamp</Name>\r\n" + 
-//            "                <Quantity>5</Quantity>\r\n" + 
-//            "            </Item>\r\n" + 
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE NOT (ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    public void XXXtestSubqueryInXMLQueryCriteria4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE EXISTS (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedSubquery() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"001\">\r\n" + 
-//            "                <Name>Lamp</Name>\r\n" + 
-//            "                <Quantity>5</Quantity>\r\n" + 
-//            "            </Item>\r\n" + 
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') ) )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"001\">\r\n" + 
-//            "                <Name>Lamp</Name>\r\n" + 
-//            "                <Quantity>5</Quantity>\r\n" +
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"51\">\r\n" +
-//            "                        <Name>Chucky</Name>\r\n" +
-//            "                        <Zip>11111</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"52\">\r\n" +
-//            "                        <Name>Biff's Stuff</Name>\r\n" +
-//            "                        <Zip>22222</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"53\">\r\n" +
-//            "                        <Name>AAAA</Name>\r\n" +
-//            "                        <Zip>33333</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }  
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID > ANY (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('53','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    } 
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"002\">\r\n" + 
-//            "                <Name>Screwdriver</Name>\r\n" + 
-//            "                <Quantity>100</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"54\">\r\n" +
-//            "                        <Name>Nugent Co.</Name>\r\n" +
-//            "                        <Zip>44444</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"55\">\r\n" +
-//            "                        <Name>Zeta</Name>\r\n" +
-//            "                        <Zip>55555</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-//            "            <Item ItemID=\"003\">\r\n" + 
-//            "                <Name>Goat</Name>\r\n" + 
-//            "                <Quantity>4</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID < ALL (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"002\">\r\n" + 
-//            "                <Name>Screwdriver</Name>\r\n" + 
-//            "                <Quantity>100</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"54\">\r\n" +
-//            "                        <Name>Nugent Co.</Name>\r\n" +
-//            "                        <Zip>44444</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"55\">\r\n" +
-//            "                        <Name>Zeta</Name>\r\n" +
-//            "                        <Zip>55555</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-//            "            <Item ItemID=\"003\">\r\n" + 
-//            "                <Name>Goat</Name>\r\n" + 
-//            "                <Quantity>4</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID IN (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-
-    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"54\">\r\n" +
-//            "                        <Name>Nugent Co.</Name>\r\n" +
-//            "                        <Zip>44444</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"55\">\r\n" +
-//            "                        <Name>Zeta</Name>\r\n" +
-//            "                        <Zip>55555</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers/>\r\n" + //$NON-NLS-1$
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE context(SupplierID, SupplierID) < SOME (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testCritNestedMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-//            "            <Item ItemID=\"002\">\r\n" + 
-//            "                <Name>Screwdriver</Name>\r\n" + 
-//            "                <Quantity>100</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"54\">\r\n" +
-//            "                        <Name>Nugent Co.</Name>\r\n" +
-//            "                        <Zip>44444</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"55\">\r\n" +
-//            "                        <Name>Zeta</Name>\r\n" +
-//            "                        <Zip>55555</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-//            "            <Item ItemID=\"003\">\r\n" + 
-//            "                <Name>Goat</Name>\r\n" + 
-//            "                <Quantity>4</Quantity>\r\n" + 
-//            "                <Suppliers>\r\n" +
-//            "                    <Supplier SupplierID=\"56\">\r\n" +
-//            "                        <Name>Microsoft</Name>\r\n" +
-//            "                        <Zip>66666</Zip>\r\n" +
-//            "                    </Supplier>\r\n" +
-//            "                </Suppliers>\r\n" +
-//            "            </Item>\r\n" + 
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID = '52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testDefect_9893() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Root>\r\n" + //$NON-NLS-1$
-            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
-            "</Root>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc9893", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr); 
-    }
-
-    @Test public void testDefect_9893_2() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Root>\r\n" + //$NON-NLS-1$
-            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
-            "</Root>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemName FROM xmltest.doc9893", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr); 
-    }
-
-    @Test public void testDefect_9893_3() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Root>\r\n" + //$NON-NLS-1$
-            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
-            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
-            "</Root>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemName.* FROM xmltest.doc9893", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr); 
-    }
-
-    @Test public void testDefect_9893_4() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
-        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item/>\r\n" +  //$NON-NLS-1$
-            "            <Item/>\r\n" +  //$NON-NLS-1$
-            "            <Item/>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        final boolean SHOULD_SUCCEED = true;
-        helpTestProcess("SELECT Item FROM xmltest.doc9c", //$NON-NLS-1$
-            expectedDoc, metadata, dataMgr, null);       
-    }
-
-    @Test public void testNestedWithStoredQueryInMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc18", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /** homegenous, simple array elements */
-    @Test public void testWithSOAPEncoding1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataSoap1();
-        FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, false);
-         
-        String expectedDoc = 
-             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-             "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
-             "    <ORG:TaxReport>\r\n" +  //$NON-NLS-1$
-             "        <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //$NON-NLS-1$
-             "                          xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n" + //$NON-NLS-1$
-             "                          xsi:type=\"ORG:ArrayOfTaxIDType\"\r\n" + //$NON-NLS-1$
-             " SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" +  //$NON-NLS-1$
-             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
-             "                <ID>1</ID>\r\n" +  //$NON-NLS-1$
-             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
-             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
-             "                <ID>2</ID>\r\n" +  //$NON-NLS-1$
-             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
-             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
-             "                <ID>3</ID>\r\n" +  //$NON-NLS-1$
-             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
-             "        </ORG:ArrayOfTaxID>\r\n" +  //$NON-NLS-1$
-             "    </ORG:TaxReport>\r\n" +  //$NON-NLS-1$
-             "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-     
-    /**
-     * if no data is contained in the soap elements
-     * (e.g. ORG:ArrayOfTaxID) and the schema allows it, eliminate the 
-     * whole fragment
-     */        
-    @Test public void testWithSOAPEncodingNoRows() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataSoap1();
-        FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, true);
-         
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
-            "    <ORG:TaxReport/>\r\n" +  //$NON-NLS-1$
-//            "    <ORG:TaxReport>\r\n" + 
-//            "        <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xsi:type=\"ORG:ArrayOfTaxIDType\" SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" + 
-//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
-//            "                <ID>1</ID>\r\n" + 
-//            "            </ORG:TaxID>\r\n" + 
-//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
-//            "                <ID>2</ID>\r\n" + 
-//            "            </ORG:TaxID>\r\n" + 
-//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
-//            "                <ID>3</ID>\r\n" + 
-//            "            </ORG:TaxID>\r\n" + 
-//            "        </ORG:ArrayOfTaxID>\r\n" + 
-//            "    </ORG:TaxReport>\r\n" + 
-            "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }  
-    
-    @Test public void testDefect12260() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <numSuppliers>4</numSuppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <numSuppliers>3</numSuppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <numSuppliers>1</numSuppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-
-        // Set up capabilities to duplicate defect
-        BasicSourceCapabilities caps = new BasicSourceCapabilities();
-        caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
-        caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
-        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
-        caps.setFunctionSupport("convert", true); //$NON-NLS-1$
-        CapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps); 
-        
-        helpTestProcess("SELECT * FROM xmltest.doc12260", metadata, dataMgr, null, capFinder, expectedDoc); //$NON-NLS-1$
-    }
-    
-    @Test public void testDefect8373() throws Exception{
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-         
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc8373", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testDefect8373a() throws Exception{
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-         
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc8373a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testDefect8373b() throws Exception{
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
-         
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity/>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-
-        helpTestProcess("SELECT * FROM xmltest.doc8373b", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    @Test public void testDefect13617() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager13617(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item>\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }       
-
-    @Test public void testDefect13617a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager13617(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"004\"/>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT ItemID, Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }      
-
-    /**
-     * Tests that non-zero length whitespace string will be treated like
-     * normal data 
-     * @throws Exception
-     * @since 4.2
-     */
-    @Test public void testDefect14905() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager14905(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\" \">\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"  \">\r\n" +  //$NON-NLS-1$
-            "                <Name>  </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\" \">\r\n" +  //$NON-NLS-1$
-            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    @Test public void testTextUnnormalizedDefect15117() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager15117(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name> Lamp </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>  Screw  driver  </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name> Goat </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    @Test public void testTextUnnormalizedDefect15117a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager15117a(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>\t \n&#xD;</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>  &gt;Screw&lt; \n driver  &amp;</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name> &gt;&gt;&#xD;Goat </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }      
-    
-    @Test public void testRecursiveGroupDoc() throws Exception {
-
-        FakeMetadataFacade metadata = exampleMetadata2();
-        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<group>\r\n" + //$NON-NLS-1$
-            "    <ID>2</ID>\r\n" +  //$NON-NLS-1$
-            "    <code>-1</code>\r\n" +  //$NON-NLS-1$
-            "    <supervisor>\r\n" +  //$NON-NLS-1$
-            "        <ID>4</ID>\r\n" +  //$NON-NLS-1$
-            "        <code>1</code>\r\n" +  //$NON-NLS-1$
-            "        <group>\r\n" +  //$NON-NLS-1$
-            "            <ID>6</ID>\r\n" +  //$NON-NLS-1$
-            "            <code>3</code>\r\n" +  //$NON-NLS-1$
-            "            <supervisor>\r\n" +  //$NON-NLS-1$
-            "                <ID>8</ID>\r\n" +  //$NON-NLS-1$
-            "                <code>5</code>\r\n" +  //$NON-NLS-1$
-            "                <group>\r\n" +  //$NON-NLS-1$
-            "                    <ID>10</ID>\r\n" +  //$NON-NLS-1$
-            "                    <code>7</code>\r\n" +  //$NON-NLS-1$
-            "                    <supervisor>\r\n" +  //$NON-NLS-1$
-            "                        <ID>12</ID>\r\n" +  //$NON-NLS-1$
-            "                        <code>9</code>\r\n" +  //$NON-NLS-1$
-            "                    </supervisor>\r\n" +  //$NON-NLS-1$
-            "                </group>\r\n" +  //$NON-NLS-1$
-            "            </supervisor>\r\n" +  //$NON-NLS-1$
-            "        </group>\r\n" +  //$NON-NLS-1$
-            "    </supervisor>\r\n" +  //$NON-NLS-1$
-            "</group>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xqttest.groupDoc WHERE pseudoID = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testCase2951MaxRows() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    /** test rowlimitexception() doesn't throw exception is rowlimit isn't passed */
-    @Test public void testDefect19173RowLimitException() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 4", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /** test criteria can be written backwards */
-    @Test public void testDefect19173RowLimitExceptionBackwardsCriteria() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE 4 = rowlimitexception(supplier)", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-    
-    @Test public void testCase2951MaxRows2() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /** test processing exception is thrown if row limit is passed */
-    @Test public void testDefect19173RowLimitException2() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    /** Two row limits on the same mapping class should be harmless as long as the row limits are identical. */
-    @Test public void testCase2951MaxRows2a() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierid) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /** test processing exception is thrown if row limit is passed */
-    @Test public void testDefect19173RowLimitException2a() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierid) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    /** compound criteria */
-    @Test public void testCase2951MaxRows3() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID='002' AND rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /** compound criteria */
-    @Test public void testDefect19173RowLimitException3() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID='002' AND rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }     
-    
-    @Test public void testCase2951MaxRows4() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(item) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }     
-
-    @Test public void testCase2951AndDefect19173MixTwoFunctions() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitException(item) = 6", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }     
-    
-    /** arg to rowlimit function isn't in the scope of any mapping class */
-    @Test public void testCase2951MaxRowsFails() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }     
-
-    /** two conflicting row limits on the same mapping class */
-    @Test public void testCase2951MaxRowsFails2() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** arg to rowlimitexception function isn't in the scope of any mapping class */
-    @Test public void testDefect19173RowLimitExceptionFails() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }     
-
-    /** two conflicting rowlimitexceptions on the same mapping class */
-    @Test public void testDefect19173RowLimitExceptionFails2() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    /** two conflicting rowlimit and rowlimitexceptions on the same mapping class fails planning */
-    @Test public void testDefect19173RowLimitAndRowLimitExceptionMixFails2() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    /** try rowlimit criteria written the reverse way */
-    @Test public void testCase2951MaxRows5() throws Exception {
-        
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "                <Suppliers>\r\n" + //$NON-NLS-1$
-            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-            "                    </Supplier>\r\n" + //$NON-NLS-1$
-            "                </Suppliers>\r\n" + //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE 2 = rowlimit(supplier)", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    } 
-    
-    
-    @Test public void testNormalizationCollapse() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.normDoc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    @Test public void testNormalizationReplace() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>   Screwdriver       </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>         Goat  </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Flux     Capacitor</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
-            "                <Name> Feta               Matrix       </Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
- 
-        helpTestProcess("SELECT * FROM xmltest.normDoc2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    @Test public void testNormalizationPreserve() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManagerNormalization2(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>My Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>My Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
-            "                <Name>My Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
-            "                <Name>My Milkshake</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
-            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
-            "                <Name>My Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-    
-        helpTestProcess("SELECT * FROM xmltest.normDoc3", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * Deluxe example
-     */
-    private FakeDataManager exampleDataManagerNormalization(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", " \n Screwdriver \t    \r", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "       \t\rGoat \n", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "Flux \t\r\n Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", " Feta               Matrix       ", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }   
-    private FakeDataManager exampleDataManagerNormalization2(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "My Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "My Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "My Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "My Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", "My Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }   
-    
-    private static MappingNode createXMLPlanNormalization(String normMode) {
-
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-
-        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        //choice node, non-visual, so it has no name        
-        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode());
-        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
-        choice.setMaxOccurrs(-1);
-        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
-        MappingElement item = crit.addChildElement(new MappingElement("Item")); //$NON-NLS-1$ 
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setNormalizeText(normMode) 
-            .setNillable(true);
-        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-        
-        MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
-        MappingElement discontinuedItem = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$ 
-        discontinuedItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        discontinuedItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setNormalizeText(normMode) 
-            .setNillable(true);
-        discontinuedItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$
-        
-        MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());      
-        MappingElement unknownItem = crit3.addChildElement(new MappingElement("StatusUnknown")); //$NON-NLS-1$
-        unknownItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        unknownItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setNormalizeText(normMode) 
-            .setNillable(true);
-        unknownItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setDefaultValue("0"); //$NON-NLS-1$        
-        
-        MappingCriteriaNode notIncludedSibling = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$ 
-        notIncludedSibling.setExclude(true);
-
-        MappingCriteriaNode notIncludedSibling2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$ 
-        notIncludedSibling2.setExclude(true);
-        return doc;        
-    }
-
-    static FakeDataManager exampleDataManagerCase3225(FakeMetadataFacade metadata) {
-        FakeDataManager dataMgr = new FakeDataManager();
-    
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupItems = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-
-            // Group stock.supplier
-            FakeMetadataObject groupSuppliers = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-            // Group stock.orders
-            FakeMetadataObject groupOrders = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-            // Group stock.employees
-            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
-            
-            // Group stock.item_supplier
-            FakeMetadataObject groupItemSupplier = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-            // Items
-            List elementIDs = metadata.getElementIDsInGroupID(groupItems);
-            List elementSymbols = createElements(elementIDs);
-
-            // Supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupSuppliers);
-            List supplierElementSymbols = createElements(elementIDs);
-
-            // Orders
-            elementIDs = metadata.getElementIDsInGroupID(groupOrders);
-            List ordersElementSymbols = createElements(elementIDs);
-
-            // Employees
-            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
-            List employeesElementSymbols = createElements(elementIDs);
-            
-            // Item_supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupItemSupplier);
-            List itemSupplierElementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupItems,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupItemSupplier,
-                itemSupplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
-
-
-            dataMgr.registerTuples(
-                groupSuppliers,
-                supplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupOrders,
-                ordersElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "1", "001", "51", "2/13/05", new Integer(2), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "2", "001", "52", "3/13/05", new Integer(1), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "3", "002", "53", "4/13/05", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "4", "002", "56", "5/13/05", new Integer(1), "cancelled" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "5", "003", "56", "6/13/05", new Integer(800), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    } );    
-
-            dataMgr.registerTuples(
-                groupEmployees,
-                employeesElementSymbols,
-               
-                new List[] { 
-                    Arrays.asList( new Object[] { "1001", "51", "001", "1004", "Albert", "Pujols" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1002", "51", "001", "1004", "Jim", "Edmunds" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1003", "54", "002", "1004", "David", "Eckstein" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1004", null, null, "1009", "Tony", "LaRussa" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-                    Arrays.asList( new Object[] { "1005", "56", "001", "1007", "Derrek", "Lee" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1006", "56", "003", "1007", "Corey", "Patterson" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1007", null, null, "1010", "Dusty", "Baker" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-                    Arrays.asList( new Object[] { "1008", "56", "002", "1007", "Carlos", "Zambrano" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1009", null, null, null, "Bill", "DeWitt" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                    Arrays.asList( new Object[] { "1010", null, null, null, "Some", "Guy" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                    } );             
-            
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
-        return dataMgr;
-    }      
-    
-    /**
-     * Test of doc model w/o criteria, just as a baseline 
-     * @throws Exception
-     */
-    @Test public void testCase3225() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" + //$NON-NLS-1$
-        "        <Items>\r\n" + //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" + //$NON-NLS-1$
-        "            <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
-        "                <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
-        "                <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1003\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>5/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>cancelled</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1008\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" + //$NON-NLS-1$
-        "            <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
-        "                <Name>Goat</Name>\r\n" + //$NON-NLS-1$
-        "                <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>6/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>800</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1006\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" + //$NON-NLS-1$
-        "        </Items>\r\n" + //$NON-NLS-1$
-        "    </Catalog>\r\n" + //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("select * from xmltest.itemsdoc", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
-    /**
-     * For ESpace case 3225 tests, with criteria
-     * "... where employee. at supervisorID='1004' and order.orderquantity > 1"
-     */
-    private static final String CASE_3225_WITH_CRITERIA_EXPECTED_DOC = 
-        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-        "<Catalogs>\r\n" + //$NON-NLS-1$
-        "    <Catalog>\r\n" + //$NON-NLS-1$
-        "        <Items>\r\n" + //$NON-NLS-1$
-        "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
-        "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
-        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-        "                <Suppliers>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders>\r\n" + //$NON-NLS-1$
-        "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-        "                                <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
-        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-        "                            </Order>\r\n" + //$NON-NLS-1$
-        "                        </Orders>\r\n" + //$NON-NLS-1$
-        "                        <Employees/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees/>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-        "                        <Orders/>\r\n" + //$NON-NLS-1$
-        "                        <Employees>\r\n" + //$NON-NLS-1$
-        "                            <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
-        "                                <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
-        "                                <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
-        "                            </Employee>\r\n" + //$NON-NLS-1$
-        "                        </Employees>\r\n" + //$NON-NLS-1$
-        "                    </Supplier>\r\n" + //$NON-NLS-1$
-        "                </Suppliers>\r\n" + //$NON-NLS-1$
-        "            </Item>\r\n" + //$NON-NLS-1$
-        "        </Items>\r\n" + //$NON-NLS-1$
-        "    </Catalog>\r\n" + //$NON-NLS-1$
-        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$    
-
-	private static String EXPECTED_ORDERED_DOC9A = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-	"<Catalogs>\r\n" + //$NON-NLS-1$
-	"    <Catalog>\r\n" +  //$NON-NLS-1$
-	"        <Items>\r\n" +  //$NON-NLS-1$
-	"            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-	"                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-	"                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-	"                <Suppliers>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders>\r\n" + //$NON-NLS-1$
-	"                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" +  //$NON-NLS-1$
-	"                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" + //$NON-NLS-1$
-	"                        </Orders>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                </Suppliers>\r\n" + //$NON-NLS-1$
-	"            </Item>\r\n" +              //$NON-NLS-1$
-	"            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-	"                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-	"                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-	"                <Suppliers>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders>\r\n" + //$NON-NLS-1$
-	"                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" + //$NON-NLS-1$
-	"                        </Orders>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders/>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders>\r\n" + //$NON-NLS-1$
-	"                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" +  //$NON-NLS-1$
-	"                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" + //$NON-NLS-1$
-	"                        </Orders>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                </Suppliers>\r\n" + //$NON-NLS-1$
-	"            </Item>\r\n" +  //$NON-NLS-1$
-	"            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-	"                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-	"                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
-	"                <Suppliers>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders/>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders>\r\n" + //$NON-NLS-1$
-	"                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
-	"                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
-	"                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
-	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
-	"                            </Order>\r\n" + //$NON-NLS-1$
-	"                        </Orders>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
-	"                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders/>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
-	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
-	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
-	"                        <Orders/>\r\n" + //$NON-NLS-1$
-	"                    </Supplier>\r\n" + //$NON-NLS-1$
-	"                </Suppliers>\r\n" + //$NON-NLS-1$
-	"            </Item>\r\n" +              //$NON-NLS-1$
-	"        </Items>\r\n" +  //$NON-NLS-1$
-	"    </Catalog>\r\n" +  //$NON-NLS-1$
-	"</Catalogs>\r\n\r\n";
-    
-    /**
-     * Test of query with criteria written one way.  This test is paired up 
-     * with {@link #testCase3225WithCriteriaReversed()}; both tests have the same
-     * expected results and are identical queries except their compound criteria are 
-     * written in reverse order relative to each other.  What Alan Tetrault found at
-     * ESpace is that this changes actual results, which it shouldn't.  The likely
-     * culprit is the algorithm to apply criteria to the implied context mapping class.
-     * That is, the criteria is on nodes in the scope of two nested mapping classes
-     * (the ones for orders and employees), but the implied context mapping class of both
-     * of them is the root mapping class (for items).
-     * 
-     * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
-     * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
-     * the combined criteria should limit returned items to item 001.
-     * @throws Exception
-     */
-    @Test public void testCase3225WithCriteria() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        helpTestProcess("select * from xmltest.itemsdoc where employee. at supervisorID='1004' and order.orderquantity > 1", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
-    }    
-
-    /**
-     * Test of query with criteria written the other way.  This test is paired up 
-     * with {@link #testCase3225WithCriteria()}; both tests have the same
-     * expected results and are identical queries except their compound criteria are 
-     * written in reverse order relative to each other.  What Alan Tetrault found at
-     * ESpace is that this changes actual results, which it shouldn't.  The likely
-     * culprit is the algorithm to apply criteria to the implied context mapping class.
-     * That is, the criteria is on nodes in the scope of two nested mapping classes
-     * (the ones for orders and employees), but the implied context mapping class of both
-     * of them is the root mapping class (for items).
-     * 
-     * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
-     * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
-     * the combined criteria should limit returned items to item 001.
-     * @throws Exception
-     */
-    @Test public void testCase3225WithCriteriaReversed() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        helpTestProcess("select * from xmltest.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004'", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
-    }      
-
-    /**
-     * Test the criteria from previous test, plus additional criteria explicitly
-     * on the context mapping class (in this case, the root "items" mapping class)
-     * to make sure all of the criteria is processed correctly. 
-     * @throws Exception
-     */
-    @Test public void testCase3225WithEmptyDocCriteria() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs>\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" + //$NON-NLS-1$
-            "        <Items/>\r\n" + //$NON-NLS-1$
-            "    </Catalog>\r\n" + //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("select * from xmltest.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004' and item. at itemid='002'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }      
-    
-    /**
-     * This just tests selecting * from the document, nothing fancy 
-     * @throws Exception
-     * @since 4.3
-     */
-    @Test public void testBaseballPlayersDoc() throws Exception {
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("select * from xmltest.playersDoc", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-        
-    }
-    
-    /**
-     * This one seems to work fine - criteria mapping class is 
-     * managers while implied context mapping class is players. 
-     * Expected result is same as previous test.
-     * @throws Exception
-     * @since 4.3
-     */
-    @Test public void testBaseballPlayersDocCriteria() throws Exception {
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("select * from xmltest.playersDoc where manager. at managerid = '1004'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-        
-    }     
-    
-    /**
-     * This also seems to work fine.  The context mapping class is the 
-     * middle one (managers). 
-     * @throws Exception
-     * @since 4.3
-     */
-    @Test public void testBaseballPlayersDocContextCriteria() throws Exception {
-        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
-        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("select * from xmltest.playersDoc where context(manager, owner. at ownerid) = '1009'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-        
-    }    
-    
-    /**
-     * Ensures that temp tables are still visible when processing criteria
-     */
-    @Test public void testProcedureAndXML() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        helpTestProcess("call xmltest.vsp1()", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-    
-    /**
-     * When a element with source node is specied, it can be unbouned or bounded. In the case
-     * of bounded, but result set is returning more results then it should fail.
-     */
-    public void defer_testMinMaxOnSourceNode() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        try {
-            helpTestProcess("SELECT * FROM xmltest.docBounded", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-            fail("should have failed the document restrictions."); //$NON-NLS-1$
-        } catch (TeiidProcessingException e) {
-            // pass
-        }
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java (from rev 2775, trunk/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,11800 @@
+/*
+ * 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 static org.junit.Assert.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingChoiceNode;
+import org.teiid.query.mapping.xml.MappingCommentNode;
+import org.teiid.query.mapping.xml.MappingCriteriaNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.mapping.xml.MappingNodeConstants;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingSequenceNode;
+import org.teiid.query.mapping.xml.Namespace;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.optimizer.QueryOptimizer;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.optimizer.xml.TestXMLPlanner;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.processor.BatchCollector;
+import org.teiid.query.processor.FakeDataManager;
+import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.processor.TestProcessor;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.symbol.ElementSymbol;
+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.util.CommandContext;
+
+
+/**
+ * Tests XML processing, which involves XMLPlanner making a ProcessorPlan
+ * (XMLPlan) from a mapping document (tree of MappingNode objects) and
+ * metadata, and then that XMLPlan being processed with metadata, a 
+ * ProcessorDataManager and a QueryProcessor.
+ */
+ at SuppressWarnings("nls")
+public class TestXMLProcessor {
+    private static final boolean DEBUG = false;
+    
+    /**
+     * Construct some fake metadata.  Basic conceptual tree is:
+     * 
+     * stock (physical model)
+     *   items (physical group)
+     *     itemNum (string)
+     *     itemName (string)
+     *     itemQuantity (integer)
+     * xmltest (virtual model)
+     *   rs (virtual group / result set definition)
+     *     itemNum (string)
+     *     itemName (string)
+     *     itemQuantity (integer)
+     */
+    public static FakeMetadataFacade exampleMetadataCached() {
+        return EXAMPLE_CACHED;
+    } 
+    
+    private static final FakeMetadataFacade EXAMPLE_CACHED = exampleMetadata();
+    
+    public static FakeMetadataFacade exampleMetadata() {
+        FakeMetadataStore store = new FakeMetadataStore();
+        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+        
+        // Create models
+        FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
+        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
+
+        // Create physical groups
+        FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
+        FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
+
+        FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
+        FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
+        FakeMetadataObject employees = FakeMetadataFactory.createPhysicalGroup("stock.employees", stock); //$NON-NLS-1$
+             
+        // Create physical elements
+        List itemElements = FakeMetadataFactory.createElements(items, 
+            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        //many-to-many join table
+        List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
+            new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+        List supplierElements = FakeMetadataFactory.createElements(suppliers, 
+            new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List stockOrders = FakeMetadataFactory.createElements(orders, 
+            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List supplierEmployees = FakeMetadataFactory.createElements(employees, 
+            new String[] { "employeeNum", "supplierNumFK", "supervisorNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+
+        
+// ======================================================================================================================
+
+        // Create virtual groups
+        // per defect 6829 - intentionally including the reserved word "group" as part of this virtual group name
+        QueryNode rsQuery = new QueryNode("xmltest.group.items", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery); //$NON-NLS-1$
+
+        // Created 2nd virtual group w/ nested result set & binding
+        QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        //QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT stock.suppliers.supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?");
+        rsQuery2.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
+
+        // Created virtual group w/ nested result set & binding
+        QueryNode rsQuery3 = new QueryNode("xmltest.orders", "SELECT orderNum, orderDate, orderQty, orderStatus FROM stock.orders WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+        rsQuery3.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
+        rsQuery3.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
+        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
+
+
+// ======================================================================================================================
+
+        //create employees - not connected to any of the above
+        QueryNode rsEmployees = new QueryNode("xmltest.employees", "SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xmltest.employees", xmltest, rsEmployees); //$NON-NLS-1$
+
+        //recursive piece
+        QueryNode rsEmployeesRecursive = new QueryNode("xmltest.employeesRecursive", "SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsEmployeesRecursive.addBinding("xmltest.employees.employeeNum"); //$NON-NLS-1$
+        FakeMetadataObject rs4a = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursive", xmltest, rsEmployeesRecursive); //$NON-NLS-1$
+
+// ======================================================================================================================
+
+        //create employees - not connected to any of the above
+        QueryNode rsEmployees2 = new QueryNode("xmltest.employees2", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE supplierNumFK = '2' AND NOT (supervisorNum IS NULL)"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xmltest.employees2", xmltest, rsEmployees2); //$NON-NLS-1$
+
+        //recursive piece
+        QueryNode rsEmployees2Recursive = new QueryNode("xmltest.employees2Recursive", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsEmployees2Recursive.addBinding("xmltest.employees2.supervisorNum"); //$NON-NLS-1$
+        FakeMetadataObject rs5a = FakeMetadataFactory.createVirtualGroup("xmltest.employees2Recursive", xmltest, rsEmployees2Recursive); //$NON-NLS-1$
+
+//      ======================================================================================================================
+// Alternate mapping class which selects from stored query
+
+        // Created 2nd virtual group w/ nested result set & binding
+        QueryNode rsQueryX = new QueryNode("xmltest.suppliersX", "SELECT * FROM (exec xmltest.sqX(?)) as X"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQueryX.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+        FakeMetadataObject rsQX = FakeMetadataFactory.createVirtualGroup("xmltest.suppliersX", xmltest, rsQueryX); //$NON-NLS-1$
+
+// ======================================================================================================================
+// ALTERNATE METADATA A (temp groups)
+
+        // root temp group
+        QueryNode tempQuery = new QueryNode("tempGroup.orders", "SELECT * FROM stock.orders"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject temp = FakeMetadataFactory.createVirtualGroup("tempGroup.orders", xmltest, tempQuery); //$NON-NLS-1$
+
+        // 2nd bogus root temp group selects from first - tests that temp groups can select from others
+        QueryNode tempQuery2 = new QueryNode("tempGroup.orders2", "SELECT * FROM tempGroup.orders"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject temp2 = FakeMetadataFactory.createVirtualGroup("tempGroup.orders2", xmltest, tempQuery2); //$NON-NLS-1$
+        
+        // Created virtual group w/ nested result set & binding - selects from 2nd temp root group
+        QueryNode rsQuery3a = new QueryNode("xmltest.ordersA", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery3a.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+        rsQuery3a.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
+        rsQuery3a.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
+        FakeMetadataObject rs3a = FakeMetadataFactory.createVirtualGroup("xmltest.ordersA", xmltest, rsQuery3a); //$NON-NLS-1$
+
+// ======================================================================================================================
+// ALTERNATE METADATA B (temp groups)
+
+        //temp group selects from root temp group and it has bindings to other mapping classes
+        // from 5.5 bindings are not supported in the staging tables. even before we did not supported 
+        // them in the modeler; but we did in execution; now we remove it as it poses more issues.
+        QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        tempQuery3b.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+        tempQuery3b.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
+        tempQuery3b.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
+        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b); //$NON-NLS-1$
+        
+        // Created virtual group w/ nested result set & binding
+        QueryNode rsQuery3b = new QueryNode("xmltest.ordersB", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rsQuery3b); //$NON-NLS-1$
+
+
+// ======================================================================================================================
+// ALTERNATE METADATA C (temp group with union)
+
+//        //temp group selects from root temp group and it has bindings to other mapping classes
+//        QueryNode tempQuery3b = new QueryNode("tempGroup.orders3B", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?");
+//        tempQuery3b.addBinding("xmltest.group.items.itemNum");
+//        tempQuery3b.addBinding("xmltest.suppliers.supplierNum");
+//        tempQuery3b.addBinding("xmltest.suppliers.supplierName");
+//        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b);
+//        
+//        // Created virtual group w/ nested result set & binding
+//        QueryNode rsQuery3b = new QueryNode("xmltest.ordersB", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B");
+//        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rs   Query3b);
+
+// ======================================================================================================================
+
+// ======================================================================================================================
+// ALTERNATE METADATA D (correlated subquery in mapping class)
+       // Create virtual groups
+       // per defect 12260 - correlated subquery in mapping class transformation
+       QueryNode rsQuery12260 = new QueryNode("xmltest.group.itemsWithNumSuppliers", "SELECT itemNum, itemName, itemQuantity, itemStatus, convert((select count(*) from stock.item_supplier where stock.items.itemNum = stock.item_supplier.itemNum), string) as NUMSuppliers FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+       FakeMetadataObject rs12260 = FakeMetadataFactory.createVirtualGroup("xmltest.group.itemsWithNumSuppliers", xmltest, rsQuery12260); //$NON-NLS-1$
+
+       List rsElements12260 = FakeMetadataFactory.createElements(rs12260, 
+           new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus", "numSuppliers" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+           new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });        
+    
+// ======================================================================================================================
+// ALTERNATE METADATA E (mapping class w/ Union)
+       // Create virtual groups
+       // per defect 8373
+       QueryNode rsQuery8373 = new QueryNode("xmltest.items8373", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items UNION ALL SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+       FakeMetadataObject rs8373 = FakeMetadataFactory.createVirtualGroup("xmltest.items8373", xmltest, rsQuery8373); //$NON-NLS-1$
+
+       List rsElements8373 = FakeMetadataFactory.createElements(rs8373, 
+            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
+
+       //select * from xmltest.items8373
+       QueryNode rsQuery8373a = new QueryNode("xmltest.items8373a", "SELECT * FROM xmltest.items8373"); //$NON-NLS-1$ //$NON-NLS-2$
+       FakeMetadataObject rs8373a = FakeMetadataFactory.createVirtualGroup("xmltest.items8373a", xmltest, rsQuery8373a); //$NON-NLS-1$
+
+       List rsElements8373a = FakeMetadataFactory.createElements(rs8373a, 
+            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
+
+       QueryNode rsQuery8373b = new QueryNode("xmltest.items8373b", "SELECT * FROM xmltest.group.items UNION ALL SELECT * FROM xmltest.group.items"); //$NON-NLS-1$ //$NON-NLS-2$
+       FakeMetadataObject rs8373b = FakeMetadataFactory.createVirtualGroup("xmltest.items8373b", xmltest, rsQuery8373b); //$NON-NLS-1$
+
+       List rsElements8373b = FakeMetadataFactory.createElements(rs8373b, 
+            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
+       
+// ======================================================================================================================
+
+
+        // Test an update query as a mapping class transformation, as if it were a 
+        // mapping class returning a single int - defect 8812
+        QueryNode rsUpdateQuery = new QueryNode("xmltest.updateTest", "INSERT INTO stock.items (itemNum, itemName, itemQuantity, itemStatus) VALUES ('3','beer',12,'something')"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rsUpdate = FakeMetadataFactory.createVirtualGroup("xmltest.updateTest", xmltest, rsUpdateQuery); //$NON-NLS-1$
+
+        // Create virtual elements
+        List rsElements = FakeMetadataFactory.createElements(rs, 
+            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
+
+
+        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+            new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
+            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements4a = FakeMetadataFactory.createElements(rs4a, 
+            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
+            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements5a = FakeMetadataFactory.createElements(rs5a, 
+            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        List tempElements = FakeMetadataFactory.createElements(temp, 
+            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List tempElements2 = FakeMetadataFactory.createElements(temp2, 
+            new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements3a = FakeMetadataFactory.createElements(rs3a, 
+            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List tempElements3b = FakeMetadataFactory.createElements(temp3b, 
+            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsElements3b = FakeMetadataFactory.createElements(rs3b, 
+            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        List rsUpdateElement = FakeMetadataFactory.createElements(rsUpdate, 
+            new String[] { "rowCount" }, //$NON-NLS-1$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER});
+
+        List rsElementsX = FakeMetadataFactory.createElements(rsQX, 
+            new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+       
+        // Create virtual docs
+        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xmltest.doc1", xmltest, createXMLMappingNode(true)); //$NON-NLS-1$
+        List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+            
+        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xmltest.doc1Unformatted", xmltest, createXMLMappingNode(false)); //$NON-NLS-1$
+        FakeMetadataObject doc1b = FakeMetadataFactory.createVirtualGroup("xmltest.doc1b", xmltest, createXMLPlan2(false, true, 0 )); //$NON-NLS-1$
+        List docE1b = FakeMetadataFactory.createElements(doc1b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        FakeMetadataObject doc1c = FakeMetadataFactory.createVirtualGroup("xmltest.doc1c", xmltest, createXMLPlan2(false, true, 1 )); //$NON-NLS-1$
+        List docE1c = FakeMetadataFactory.createElements(doc1c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        
+        FakeMetadataObject docBounded = FakeMetadataFactory.createVirtualGroup("xmltest.docBounded", xmltest, createXMLMappingBoundingNode()); //$NON-NLS-1$
+        List docBoundedElements = FakeMetadataFactory.createElements(docBounded, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        
+
+        FakeMetadataObject doc2  = FakeMetadataFactory.createVirtualGroup("xmltest.doc2",  xmltest, createXMLPlan2(1, -1, false)); //$NON-NLS-1$
+        List docE2 = FakeMetadataFactory.createElements(doc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        FakeMetadataObject doc2a = FakeMetadataFactory.createVirtualGroup("xmltest.doc2a", xmltest, createXMLPlan2(1, 1, false)); //$NON-NLS-1$
+        FakeMetadataObject doc2b = FakeMetadataFactory.createVirtualGroup("xmltest.doc2b", xmltest, createXMLPlan2(1, -1, true)); //$NON-NLS-1$
+        FakeMetadataObject doc2c = FakeMetadataFactory.createVirtualGroup("xmltest.doc2c", xmltest, createXMLPlan2(2, -1, false)); //$NON-NLS-1$
+        FakeMetadataObject doc2d = FakeMetadataFactory.createVirtualGroup("xmltest.doc2d", xmltest, createXMLPlan2(2, 1, false)); //$NON-NLS-1$
+        FakeMetadataObject doc2e = FakeMetadataFactory.createVirtualGroup("xmltest.doc2e", xmltest, createXMLPlan2(2, 3, false)); //$NON-NLS-1$
+
+        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xmltest.doc3", xmltest, createXMLPlanWithDefaults()); //$NON-NLS-1$
+        List docE3 = FakeMetadataFactory.createElements(doc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xmltest.doc4", xmltest, createXMLPlanAdvanced()); //$NON-NLS-1$
+        List docE4 = FakeMetadataFactory.createElements(doc4, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Fake", "Catalogs.Fake.FakeChild2", "Catalogs.Fake.FakeChild2.FakeChild2a", "Catalogs.Fake.FakeChild3", "Catalogs.Fake.FakeChild3. at FakeAtt" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER,DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xmltest.doc5", xmltest, createXMLPlanUltraAdvanced()); //$NON-NLS-1$
+        List docE5 = FakeMetadataFactory.createElements(doc5, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        FakeMetadataObject doc6 = FakeMetadataFactory.createVirtualGroup("xmltest.doc6", xmltest, createXMLPlanUltraAdvancedExceptionOnDefault()); //$NON-NLS-1$
+        List docE6 = FakeMetadataFactory.createElements(doc6, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.Shouldn't see"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+        FakeMetadataObject doc7 = FakeMetadataFactory.createVirtualGroup("xmltest.doc7", xmltest, createTestAttributePlan()); //$NON-NLS-1$
+        List docE7 = FakeMetadataFactory.createElements(doc7, new String[] { "FixedValueTest", "FixedValueTest.wrapper", "FixedValueTest.wrapper. at fixed", "FixedValueTest.wrapper. at key", "FixedValueTest.wrapper. at fixedAttr"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+                        
+        FakeMetadataObject doc8 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8", xmltest, createXMLPlanNested()); //$NON-NLS-1$
+        List docE8 = FakeMetadataFactory.createElements(doc8, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+    
+        FakeMetadataObject doc9 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9", xmltest, createXMLPlanNested2()); //$NON-NLS-1$
+        List docE9 = FakeMetadataFactory.createElements(doc9, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$!
  //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+            
+        FakeMetadataObject doc9a = FakeMetadataFactory.createVirtualGroup("xmltest.doc9a", xmltest, createXMLPlanNested2a()); //$NON-NLS-1$
+        List docE9a = FakeMetadataFactory.createElements(doc9a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-!
 2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc9b = FakeMetadataFactory.createVirtualGroup("xmltest.doc9b", xmltest, createXMLPlanNested2b()); //$NON-NLS-1$
+        FakeMetadataObject doc10 = FakeMetadataFactory.createVirtualGroup("xmltest.doc10", xmltest, createXMLPlanNestedWithChoice()); //$NON-NLS-1$
+        List docE10 = FakeMetadataFactory.createElements(doc10, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.Pro!
 cessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc10L = FakeMetadataFactory.createVirtualGroup("xmltest.doc10L", xmltest, createXMLPlanNestedWithLookupChoice()); //$NON-NLS-1$
+        List docE10L = FakeMetadataFactory.createElements(doc10L, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.P!
 rocessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+
+        FakeMetadataObject doc11 = FakeMetadataFactory.createVirtualGroup("xmltest.doc11", xmltest, createXMLPlanMultipleDocs()); //$NON-NLS-1$
+        List docE11 = FakeMetadataFactory.createElements(doc11, new String[] { "Item", "Item. at ItemID", "Item.Name", "Item.Quantity", "Item.Suppliers", "Item.Suppliers.Supplier", "Item.Suppliers.Supplier. at SupplierID", "Item.Suppliers.Supplier.Name", "Item.Suppliers.Supplier.Zip"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        //variations on the same recursive doc====================
+        boolean useRecursiveCriteria = false;
+        int recursionlimit = -1;
+        boolean exceptionOnLimit = false;
+
+        FakeMetadataObject doc12 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        FakeMetadataObject doc12a = FakeMetadataFactory.createVirtualGroup("xmltest.doc12a", xmltest, createXMLPlanRecursiveA(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+        useRecursiveCriteria = true;
+        FakeMetadataObject doc13 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        useRecursiveCriteria = false;
+        recursionlimit = 2;
+        FakeMetadataObject doc14 = FakeMetadataFactory.createVirtualGroup("xmltest.doc14", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        exceptionOnLimit = true;
+        FakeMetadataObject doc15 = FakeMetadataFactory.createVirtualGroup("xmltest.doc15", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+        useRecursiveCriteria = false;
+        recursionlimit = -1;
+        exceptionOnLimit = false;
+        FakeMetadataObject doc16 = FakeMetadataFactory.createVirtualGroup("xmltest.doc16", xmltest, createXMLPlanRecursive2(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+
+        FakeMetadataObject doc17 = FakeMetadataFactory.createVirtualGroup("xmltest.doc17", xmltest, createXMLPlanWithComment()); //$NON-NLS-1$
+
+        FakeMetadataObject doc_5266a = FakeMetadataFactory.createVirtualGroup("xmltest.doc_5266a", xmltest, createXMLPlanNestedWithChoiceFor5266()); //$NON-NLS-1$
+        List doc_E5266a = FakeMetadataFactory.createElements(doc_5266a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+
+        FakeMetadataObject doc_8917 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_8917", xmltest, createXMLPlan_defect8917()); //$NON-NLS-1$
+        FakeMetadataObject doc_9446 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9446", xmltest, createXMLPlan_defect9446()); //$NON-NLS-1$
+        FakeMetadataObject doc_9530 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9530", xmltest, createXMLPlan_defect_9530()); //$NON-NLS-1$
+
+        List docE_9446 = FakeMetadataFactory.createElements(doc_9446, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+        
+        //Test doc w/ update mapping class transformation
+        FakeMetadataObject docUpdateTest = FakeMetadataFactory.createVirtualGroup("xmltest.docUpdateTest", xmltest, createUpdateTestDoc()); //$NON-NLS-1$
+
+        FakeMetadataObject doc_9893 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9893", xmltest, createXMLPlan_9893()); //$NON-NLS-1$
+        List docE_9893 = FakeMetadataFactory.createElements(doc_9893, new String[] { "Root", "Root.ItemName"}, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc18 = FakeMetadataFactory.createVirtualGroup("xmltest.doc18", xmltest, createXMLPlanNested("xmltest.suppliersX")); //$NON-NLS-1$ //$NON-NLS-2$
+        List docE18 = FakeMetadataFactory.createElements(doc18, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc12260 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12260", xmltest, createXMLPlanCorrelatedSubqueryTransform()); //$NON-NLS-1$
+        List docE12260 = FakeMetadataFactory.createElements(doc12260, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc8373 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373", xmltest, createXMLPlan_defect8373()); //$NON-NLS-1$
+        List docE8373 = FakeMetadataFactory.createElements(doc8373, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc8373a = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373a", xmltest, createXMLPlan_defect8373a()); //$NON-NLS-1$
+        List docE8373a = FakeMetadataFactory.createElements(doc8373a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc8373b = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373b", xmltest, createXMLPlan_defect8373b()); //$NON-NLS-1$
+        List docE8373b = FakeMetadataFactory.createElements(doc8373b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+
+        FakeMetadataObject doc13617 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13617", xmltest, createXMLPlanDefect13617()); //$NON-NLS-1$
+        List docE13617 = FakeMetadataFactory.createElements(doc13617, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+        
+
+        // recursive + staging ========================================================
+
+        FakeMetadataObject doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19", xmltest, createXMLPlanRecursiveStaging(true, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        
+        // root temp group
+        QueryNode doc19TempQuery = new QueryNode("xmltest.doc19temp", "SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject tempDoc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19temp", xmltest, doc19TempQuery); //$NON-NLS-1$
+        List doc19TempQueryE = FakeMetadataFactory.createElements(tempDoc19, 
+                                                              new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+                                                              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+
+        //create employees - not connected to any of the above
+        QueryNode rsEmployeesDoc19 = new QueryNode("xmltest.employeesDoc19", "SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject mc1Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesDoc19", xmltest, rsEmployeesDoc19); //$NON-NLS-1$
+        List mc1Doc19E = FakeMetadataFactory.createElements(mc1Doc19, 
+                                                                  new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+                                                                  new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+
+        //recursive piece
+        QueryNode rsEmployeesRecursiveDoc19 = new QueryNode("xmltest.employeesRecursiveDoc19", "SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsEmployeesRecursiveDoc19.addBinding("xmltest.employeesDoc19.employeeNum"); //$NON-NLS-1$
+        FakeMetadataObject mc2Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursiveDoc19", xmltest, rsEmployeesRecursiveDoc19); //$NON-NLS-1$
+        List mc2Doc19E = FakeMetadataFactory.createElements(mc2Doc19, 
+                                                            new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+        // recursive + staging ========================================================
+        
+        //========================================================
+
+        // Stored queries
+        FakeMetadataObject rsX = FakeMetadataFactory.createResultSet("xmltest.rsX", xmltest, new String[] { "supplierNum", "supplierName", "supplierZipCode" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        FakeMetadataObject rsXp1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rsX);  //$NON-NLS-1$
+        FakeMetadataObject rsXp2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        //there is an extra statement in this proc so that the procedure wrapper is not removed
+        QueryNode sqXn1 = new QueryNode("xmltest.sqX", "CREATE VIRTUAL PROCEDURE BEGIN declare string x; SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = xmltest.sqX.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject sqX = FakeMetadataFactory.createVirtualProcedure("xmltest.sqX", xmltest, Arrays.asList(new FakeMetadataObject[] { rsXp1, rsXp2 }), sqXn1);  //$NON-NLS-1$
+       
+        // Documents for Text Normalization Test 
+        // normDoc1 - for collapse
+        // normDoc2 - for replace
+        // normDoc3 - for preserve
+        FakeMetadataObject normDoc1 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc1", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_COLLAPSE)); //$NON-NLS-1$
+        List normDocE1 = FakeMetadataFactory.createElements(normDoc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+                                                        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        FakeMetadataObject normDoc2 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc2", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_REPLACE)); //$NON-NLS-1$
+        List normDocE2 = FakeMetadataFactory.createElements(normDoc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+ 
+        FakeMetadataObject normDoc3 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc3", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_PRESERVE)); //$NON-NLS-1$
+        List normDocE3 = FakeMetadataFactory.createElements(normDoc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+                                                            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        
+        QueryNode vspqn1 = new QueryNode("vsp1", "CREATE VIRTUAL PROCEDURE BEGIN insert into #temp select * from stock.items; SELECT * FROM xmltest.doc1 where Item.Quantity < (select avg(itemquantity) from #temp); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject vsprs1 = FakeMetadataFactory.createResultSet("pm1.vsprs1", xmltest, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject vspp1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.XML, vsprs1); //$NON-NLS-1$
+        FakeMetadataObject vsp1 = FakeMetadataFactory.createVirtualProcedure("xmltest.vsp1", xmltest, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn1); //$NON-NLS-1$
+
+        // Add all objects to the store
+        store.addObject(stock);
+        store.addObject(items);
+        store.addObject(item_supplier);
+   
+        store.addObject(suppliers);
+        store.addObject(orders);
+        store.addObject(employees);
+        store.addObjects(itemElements);
+        store.addObjects(itemSupplierElements);
+        store.addObjects(supplierElements);
+        store.addObjects(stockOrders);
+        store.addObjects(supplierEmployees);
+     
+        store.addObject(xmltest);
+        store.addObject(rs);
+        store.addObject(rs2);
+        store.addObject(rs3);
+        store.addObject(rs4);
+        store.addObject(rs4a);
+        store.addObject(rs5);
+        store.addObject(rs5a);
+        store.addObject(temp);
+        store.addObject(temp2);
+        store.addObject(rs3a);
+        store.addObject(temp3b);
+        store.addObject(rs3b);
+        store.addObject(rsQX);
+        store.addObject(rs12260);
+        store.addObject(rs8373);
+        store.addObject(rs8373a);
+        store.addObject(rs8373b);
+        
+        //Stored query
+        store.addObject(rsX);
+        store.addObject(sqX);
+  
+        store.addObject(rsUpdate);
+        store.addObjects(rsElements);
+        store.addObjects(rsElements2);
+        store.addObjects(rsElements3);
+        store.addObjects(rsElements4);
+        store.addObjects(rsElements4a);
+        store.addObjects(rsElements5);
+        store.addObjects(rsElements5a);
+        store.addObjects(tempElements);
+        store.addObjects(tempElements2);
+        store.addObjects(rsElements3a);
+        store.addObjects(tempElements3b);
+        store.addObjects(rsElements3b);
+        store.addObjects(rsUpdateElement);
+        store.addObjects(rsElementsX);
+        store.addObjects(rsElements12260);
+        store.addObjects(rsElements8373);
+        store.addObjects(rsElements8373a);
+        store.addObjects(rsElements8373b);
+
+        store.addObject(doc1);
+        store.addObject(docBounded);
+        store.addObject(doc1a);
+        store.addObject(doc1b);
+        store.addObject(doc1c);
+        store.addObject(doc2);
+        store.addObject(doc2a);
+        store.addObject(doc2b);
+        store.addObject(doc2c);
+        store.addObject(doc2d);
+        store.addObject(doc2e);
+        store.addObject(doc3);
+        store.addObject(doc4);
+        store.addObject(doc5);
+ 
+        store.addObject(normDoc1);
+        store.addObject(normDoc2);
+        store.addObject(normDoc3);
+
+        store.addObject(doc6);
+        store.addObject(doc7);
+        store.addObject(doc8);
+        store.addObject(doc9);
+        store.addObject(doc9a);
+        store.addObject(doc9b);
+     
+        store.addObject(doc10);
+        store.addObject(doc10L);
+        store.addObject(doc11);
+        store.addObject(doc12);
+        store.addObject(doc12a);
+        store.addObject(doc13);
+        store.addObject(doc14);
+        store.addObject(doc15);
+        store.addObject(doc16);
+        store.addObject(doc17);
+        store.addObject(doc_8917);
+        store.addObject(doc_9446);
+        store.addObject(doc_9530);
+        store.addObject(docUpdateTest);
+        store.addObject(doc_9893);
+        store.addObject(doc18);
+        store.addObject(doc12260);
+        store.addObject(doc8373);
+        store.addObject(doc8373a);
+        store.addObject(doc8373b);
+        store.addObject(doc13617);
+        store.addObject(doc19);
+        store.addObject(tempDoc19);
+        store.addObject(mc1Doc19);
+        store.addObject(mc2Doc19);
+        store.addObject(doc_5266a);
+
+        store.addObjects(doc19TempQueryE);
+        store.addObjects(mc1Doc19E);
+        store.addObjects(mc2Doc19E);
+        
+        store.addObjects(docE1);
+        store.addObjects(docE1b);
+        store.addObjects(docE1c);
+        store.addObjects(docBoundedElements);
+        store.addObjects(docE2);
+        store.addObjects(docE3);
+        store.addObjects(docE4);
+        store.addObjects(docE5);
+        store.addObjects(normDocE1);
+        store.addObjects(normDocE2);
+        store.addObjects(normDocE3);
+        store.addObjects(docE6);
+        store.addObjects(docE7);
+        store.addObjects(docE8);
+        store.addObjects(docE9);
+        store.addObjects(docE9a);
+        store.addObjects(docE_9446);
+        store.addObjects(docE_9893);
+        store.addObjects(docE18);
+        store.addObjects(docE12260);
+        store.addObjects(docE8373);
+        store.addObjects(docE8373a);
+        store.addObjects(docE8373b);
+        store.addObjects(docE13617);
+        store.addObjects(doc_E5266a);
+        
+        store.addObjects(docE10);
+        store.addObjects(docE10L);
+        store.addObjects(docE11);
+        
+        store.addObject(vsp1);        
+        return facade;
+    }
+
+    public FakeMetadataFacade exampleMetadataNestedWithSibling() {
+		FakeMetadataStore store = new FakeMetadataStore();
+		FakeMetadataFacade facade = new FakeMetadataFacade(store);
+        
+		// Create models
+		FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
+		FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");  //$NON-NLS-1$
+
+		// Create physical groups
+		FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
+		FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
+		FakeMetadataObject item_order = FakeMetadataFactory.createPhysicalGroup("stock.item_order", stock); //$NON-NLS-1$
+		FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
+		FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
+		      
+		// Create physical elements
+		List itemElements = FakeMetadataFactory.createElements(items, 
+			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+		//many-to-many join table
+		List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
+			new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+		List supplierElements = FakeMetadataFactory.createElements(suppliers, 
+			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+		//many-to-many join table
+		List itemOrderElements = FakeMetadataFactory.createElements(item_order, 
+			new String[] { "itemNum", "orderNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+		List stockOrders = FakeMetadataFactory.createElements(orders, 
+			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+// ======================================================================================================================
+
+		// Create virtual groups
+		QueryNode rsQuery1 = new QueryNode("xmltest.group.items", "SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+		FakeMetadataObject rs1 = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery1); //$NON-NLS-1$
+
+		QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+		rsQuery2.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+		FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
+
+		QueryNode rsQuery3 = new QueryNode("xmltest.orders", "SELECT concat(stock.orders.orderNum, '') as orderNum, orderName, orderZipCode FROM stock.orders, stock.item_order WHERE stock.orders.orderNum = stock.item_order.orderNum AND stock.item_order.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+		rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
+		FakeMetadataObject rs3= FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
+
+		// Create virtual elements
+		List rsElements1 = FakeMetadataFactory.createElements(rs1, 
+			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+		
+		List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+		
+		List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+// =========================================================================================================
+
+		// Create virtual docs
+		FakeMetadataObject doc9c= FakeMetadataFactory.createVirtualGroup("xmltest.doc9c", xmltest, createXMLPlanNested2c()); //$NON-NLS-1$
+		List docE9c = FakeMetadataFactory.createElements(doc9c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.orders", "Catalogs.Catalog.items.item.orders.order", "Catalogs.Catalog.items.item.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.orders.order.zip", "Catalogs.Catalog.items.item.orders.order.Name"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ !
 //$NON-NLS-16$ //$NON-NLS-17$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+		
+		//========================================================
+
+		// Add all objects to the store
+		store.addObject(stock);
+		
+		store.addObject(items);
+		store.addObject(item_supplier);
+		store.addObject(item_order);
+		store.addObject(suppliers);
+		store.addObject(orders);
+		
+		store.addObjects(itemElements);
+		store.addObjects(itemSupplierElements);
+		store.addObjects(supplierElements);
+		store.addObjects(stockOrders);
+		store.addObjects(itemOrderElements);
+
+		store.addObject(xmltest);
+		store.addObject(rs1);
+		store.addObject(rs2);
+		store.addObject(rs3);
+		
+		store.addObjects(rsElements1);
+		store.addObjects(rsElements2);
+		store.addObjects(rsElements3);
+
+		store.addObject(doc9c);
+		store.addObjects(docE9c);
+     
+		// Create the facade from the store
+		return facade;		
+	}
+	
+    public static FakeMetadataFacade exampleMetadata2() { 
+        FakeMetadataStore store = new FakeMetadataStore();
+        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+        
+        // Create models
+        FakeMetadataObject xqt = FakeMetadataFactory.createPhysicalModel("xqt"); //$NON-NLS-1$
+        FakeMetadataObject xqttest = FakeMetadataFactory.createVirtualModel("xqttest");     //$NON-NLS-1$
+
+        // Create physical groups
+        FakeMetadataObject xqtGroup = FakeMetadataFactory.createPhysicalGroup("xqt.data", xqt); //$NON-NLS-1$
+                
+        // Create physical elements
+        List xqtData = FakeMetadataFactory.createElements(xqtGroup, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        // Create new XML recursion tests virtual groups
+        QueryNode xqtDataGroup = new QueryNode("xqttest.xqtData", "SELECT intKey as key, intNum as data, (intKey + 2) as nextKey FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject objData = FakeMetadataFactory.createVirtualGroup("xqttest.xqtData", xqttest, xqtDataGroup); //$NON-NLS-1$
+        
+        QueryNode rsGroup = new QueryNode("xqttest.group", "SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject objGroup = FakeMetadataFactory.createVirtualGroup("xqttest.group", xqttest, rsGroup); //$NON-NLS-1$
+        
+        QueryNode rsSupervisor = new QueryNode("xqttest.supervisor", "SELECT key as ID, data as CODE, nextKey as groupID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsSupervisor.addBinding("xqttest.group.supervisorID"); //$NON-NLS-1$
+        FakeMetadataObject objSupervisor = FakeMetadataFactory.createVirtualGroup("xqttest.supervisor", xqttest, rsSupervisor); //$NON-NLS-1$
+
+        QueryNode rsGroup1 = new QueryNode("xqttest.group1", "SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsGroup1.addBinding("xqttest.supervisor.groupID"); //$NON-NLS-1$
+        FakeMetadataObject objGroup1 = FakeMetadataFactory.createVirtualGroup("xqttest.group1", xqttest, rsGroup1); //$NON-NLS-1$
+        
+        // Create virtual elements
+        
+        List elemXQTData = FakeMetadataFactory.createElements(objData, 
+            new String[] { "key", "data", "nextKey" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
+
+        List elemGroup = FakeMetadataFactory.createElements(objGroup, 
+            new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
+
+        List elemSupervisor = FakeMetadataFactory.createElements(objSupervisor, 
+            new String[] { "ID", "code", "groupID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
+
+        List elemGroup1 = FakeMetadataFactory.createElements(objGroup1, 
+            new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
+        
+        // Create virtual groups
+        QueryNode rsQuery = new QueryNode("xqttest.data", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey=13"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xqttest.data", xqttest, rsQuery); //$NON-NLS-1$
+        
+        QueryNode rsQuery2 = new QueryNode("xqttest.data2", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery2.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xqttest.data2", xqttest, rsQuery2); //$NON-NLS-1$
+
+        QueryNode rsQuery3 = new QueryNode("xqttest.data3", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery3.addBinding("xqttest.data2.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xqttest.data3", xqttest, rsQuery3); //$NON-NLS-1$
+
+        QueryNode rsQuery4 = new QueryNode("xqttest.data4", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery4.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xqttest.data4", xqttest, rsQuery4); //$NON-NLS-1$
+
+        QueryNode rsQuery5 = new QueryNode("xqttest.data5", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery5.addBinding("xqttest.data4.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xqttest.data5", xqttest, rsQuery5); //$NON-NLS-1$
+
+        QueryNode rsQuery6 = new QueryNode("xqttest.data6", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery6.addBinding("xqttest.data5.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs6 = FakeMetadataFactory.createVirtualGroup("xqttest.data6", xqttest, rsQuery6); //$NON-NLS-1$
+
+        
+        QueryNode rsQuery7 = new QueryNode("xqttest.data7", "SELECT intKey, intNum, stringNum FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rs7 = FakeMetadataFactory.createVirtualGroup("xqttest.data7", xqttest, rsQuery7); //$NON-NLS-1$
+
+        QueryNode rsQuery8 = new QueryNode("xqttest.data8", "SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey < ?"); //$NON-NLS-1$ //$NON-NLS-2$
+        rsQuery8.addBinding("xqttest.data7.intNum"); //$NON-NLS-1$
+        FakeMetadataObject rs8 = FakeMetadataFactory.createVirtualGroup("xqttest.data8", xqttest, rsQuery8); //$NON-NLS-1$
+
+        // Create virtual elements
+        List rsElements = FakeMetadataFactory.createElements(rs, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements6 = FakeMetadataFactory.createElements(rs6, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements7 = FakeMetadataFactory.createElements(rs7, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+        List rsElements8 = FakeMetadataFactory.createElements(rs8, 
+            new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+
+
+        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xqttest.doc1", xqttest,   createXQTPlanRecursive_5988()); //$NON-NLS-1$
+        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xqttest.doc1a", xqttest, createXQTPlanRecursive1a_5988()); //$NON-NLS-1$
+        FakeMetadataObject doc2 = FakeMetadataFactory.createVirtualGroup("xqttest.doc2", xqttest,   createXQTPlanRecursiveSiblings()); //$NON-NLS-1$
+        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xqttest.doc3", xqttest,   createXQTPlanRecursive3_5988()); //$NON-NLS-1$
+        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xqttest.doc4", xqttest,   createXQTPlanChoice_6796()); //$NON-NLS-1$
+        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xqttest.doc5", xqttest,   createChoiceDefect24651()); //$NON-NLS-1$
+        FakeMetadataObject groupDoc = FakeMetadataFactory.createVirtualGroup("xqttest.groupDoc", xqttest,   createGroupDoc()); //$NON-NLS-1$
+
+        List elemGroupDoc = FakeMetadataFactory.createElements(groupDoc, new String[] { "group", "group.pseudoID" /*, etc...*/ }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+        List elemGroupDoc4 = FakeMetadataFactory.createElements(doc4, new String[] { "root", "root.key", "root.key.keys", "root.key.keys.nestedkey", "root.wrapper.key", "root.wrapper.key.keys", "root.wrapper.key.keys.nestedkey"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+                                                               new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+        
+        List elemGroupDoc5 = FakeMetadataFactory.createElements(doc5, new String[] { "root", "root.wrapper.key" }, //$NON-NLS-1$ //$NON-NLS-2$
+                                                                new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+         
+        store.addObject(xqt);
+        store.addObject(xqtGroup);
+        store.addObjects(xqtData);
+
+        store.addObject(xqttest);
+        
+        store.addObject(objData);
+        store.addObject(objGroup);
+        store.addObject(objSupervisor);
+        store.addObject(objGroup1);
+        store.addObjects(elemXQTData);
+        store.addObjects(elemGroup);
+        store.addObjects(elemSupervisor);
+        store.addObjects(elemGroup1);
+        
+        store.addObject(rs);
+        store.addObject(rs2);
+        store.addObject(rs3);
+        store.addObject(rs4);
+        store.addObject(rs5);
+        store.addObject(rs6);
+        store.addObject(rs7);
+        store.addObject(rs8);
+        store.addObjects(rsElements);
+        store.addObjects(rsElements2);
+        store.addObjects(rsElements3);
+        store.addObjects(rsElements4);
+        store.addObjects(rsElements5);
+        store.addObjects(rsElements6);
+        store.addObjects(rsElements7);
+        store.addObjects(rsElements8);
+
+        store.addObject(doc1);
+        store.addObject(doc1a);
+        store.addObject(doc2);
+        store.addObject(doc3);
+        store.addObject(doc4);
+        store.addObject(doc5);
+        store.addObject(groupDoc);
+        store.addObjects(elemGroupDoc);
+        store.addObjects(elemGroupDoc4);
+        store.addObjects(elemGroupDoc5);
+
+        return facade;
+    }
+
+    public static FakeMetadataFacade exampleMetadataSoap1() {
+        FakeMetadataStore store = new FakeMetadataStore();
+        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+        
+        // Create models
+        FakeMetadataObject taxReport = FakeMetadataFactory.createPhysicalModel("taxReport"); //$NON-NLS-1$
+        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
+
+        // Create physical groups
+        FakeMetadataObject arrayOfItem = FakeMetadataFactory.createPhysicalGroup("taxReport.TaxIDs", taxReport); //$NON-NLS-1$
+
+        // Create physical elements
+        List itemElements = FakeMetadataFactory.createElements(arrayOfItem, 
+            new String[] { "ID" }, //$NON-NLS-1$
+            new String[] {DataTypeManager.DefaultDataTypes.STRING});
+
+
+        QueryNode rsQuerySoap = new QueryNode("xmltest.group.TaxIDs", "SELECT ID FROM taxReport.TaxIDs"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject rsSoap = FakeMetadataFactory.createVirtualGroup("xmltest.group.TaxIDs", xmltest, rsQuerySoap); //$NON-NLS-1$
+
+        List rsSoapElements = FakeMetadataFactory.createElements(rsSoap, 
+        new String[] { "ID"}, //$NON-NLS-1$
+        new String[] {DataTypeManager.DefaultDataTypes.STRING});        
+
+        FakeMetadataObject doc_SOAP = FakeMetadataFactory.createVirtualGroup("xmltest.docSoap", xmltest, createXMLPlanSOAP()); //$NON-NLS-1$
+        List doc_SOAPE1 = FakeMetadataFactory.createElements(doc_SOAP, new String[] { "TaxReports", "TaxReports.TaxReport", "TaxReports.TaxReport.ArrayOfTaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID.ID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+                                               
+        store.addObject(taxReport);
+        store.addObject(arrayOfItem);
+        store.addObjects(itemElements);
+
+        store.addObject(xmltest);
+        store.addObject(rsSoap);
+        store.addObjects(rsSoapElements); 
+        store.addObject(doc_SOAP);
+        store.addObjects(doc_SOAPE1);
+        return facade;
+    }
+	
+    private static MappingNode createXQTPlanChoice_6796() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
+        choice.setSource("xqttest.data7"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$ 
+        MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+
+        MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
+        keys.setSource("xqttest.data8"); //$NON-NLS-1$
+        keys.setMaxOccurrs(-1);
+        keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingCriteriaNode wrapper2 = choice.addCriteriaNode(new MappingCriteriaNode(null, true)); 
+        
+        key = wrapper2.addChildElement( new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        keys = key.addChildElement(new MappingElement("keys")); //$NON-NLS-1$
+        keys.setSource("xqttest.data8"); //$NON-NLS-1$
+        keys.setMaxOccurrs(-1);
+        keys.addChildElement(new MappingElement("nestedkey", "xqttest.data8.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        return doc;
+    }
+    
+    private static MappingNode createChoiceDefect24651() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        MappingChoiceNode choice = root.addChoiceNode(new MappingChoiceNode(false));
+        choice.setSource("xqttest.data7"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xqttest.data7.intKey < 10", false)); //$NON-NLS-1$ 
+        MappingElement wrapper1 = crit.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+
+        MappingElement key = wrapper1.addChildElement(new MappingElement("key", "xqttest.data7.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        key.setExclude(true);
+                
+        return doc;
+    }
+
+    /**
+     * Method createXQTPlanRecursive.
+     * @return Object
+     */
+    private static MappingNode createXQTPlanRecursive_5988() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+        
+        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+        src1.setSource("xqttest.data"); //$NON-NLS-1$
+        
+        MappingSequenceNode seq1 = new MappingSequenceNode();
+        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        src1.addSequenceNode(seq1);
+
+        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+        src2.setSource("xqttest.data2"); //$NON-NLS-1$
+                
+        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcNestedRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
+        recursive.setSource("xqttest.data3"); //$NON-NLS-1$
+        
+        MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+        recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
+        
+        return doc;
+    }
+
+	/**
+	 * Method createXQTPlanRecursive.
+	 * @return Object
+	 */
+    private static MappingNode createXQTPlanRecursive1a_5988() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+        src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+        MappingSequenceNode seq1 = new MappingSequenceNode();
+        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        src1.addSequenceNode(seq1);
+
+        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+        src2.setSource("xqttest.data2"); //$NON-NLS-1$
+
+        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement recursive = seq2.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data2")); //$NON-NLS-1$ //$NON-NLS-2$
+        recursive.setSource("xqttest.data3"); //$NON-NLS-1$
+        
+        MappingElement recursive2 = seq1.addChildElement(new MappingRecursiveElement("srcRecursive", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+        recursive2.setSource("xqttest.data4"); //$NON-NLS-1$
+        
+        return doc;
+    }
+
+    /**
+     * Tests a non-recursive nested mapping class within a recursive mapping class, where
+     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
+     * @return Object
+     */
+    private static MappingNode createXQTPlanRecursive3_5988() {   
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+        src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+        MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
+        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingElement src2 = seq1.addChildElement(new MappingElement("srcNested")); //$NON-NLS-1$
+        src2.setSource("xqttest.data2"); //$NON-NLS-1$
+        
+        MappingSequenceNode seq2 = src2.addSequenceNode(new MappingSequenceNode());
+        seq2.addChildElement(new MappingElement("key", "xqttest.data2.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq2.addChildElement(new MappingElement("data", "xqttest.data2.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingElement nested = seq1.addChildElement(new MappingRecursiveElement("srcNested", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+        nested.setSource("xqttest.data4"); //$NON-NLS-1$
+        
+        return doc;
+    }
+    
+    
+    private static MappingNode createXQTPlanRecursiveSiblings() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
+
+        MappingElement src1 = root.addChildElement(new MappingElement("src")); //$NON-NLS-1$
+        src1.setSource("xqttest.data"); //$NON-NLS-1$
+
+        MappingSequenceNode seq1 = src1.addSequenceNode(new MappingSequenceNode());
+        seq1.addChildElement(new MappingElement("key", "xqttest.data.intKey")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq1.addChildElement(new MappingElement("data", "xqttest.data.intNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingElement sibiling1 = seq1.addChildElement(new MappingRecursiveElement("srcSibling1", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+        sibiling1.setSource("xqttest.data2"); //$NON-NLS-1$
+        sibiling1.setMaxOccurrs(-1);
+        MappingElement sibiling2 = seq1.addChildElement(new MappingRecursiveElement("srcSibling2", "xqttest.data")); //$NON-NLS-1$ //$NON-NLS-2$
+        sibiling2.setSource("xqttest.data2");//$NON-NLS-1$
+        sibiling2.setMaxOccurrs(-1);
+        return doc;
+    }
+
+	/**
+	 * Method createXMLPlanNested.
+	 * @return MappingNode root of mapping doc
+	 */
+	private static MappingNode createXMLPlanNested() {
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
+        doc.addChildElement(root);
+        
+        MappingSequenceNode sequence = new MappingSequenceNode();
+        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+                
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
+        MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
+
+        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
+
+        
+        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+        sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        //NESTED STUFF======================================================================
+        
+        sequence1.addChildElement(nestedWrapper);
+        root.addSequenceNode(sequence);
+        return doc;  
+	}
+    
+    
+    /**
+     * for defect 9929
+     */
+    static MappingNode createXMLPlanNested(String queryGroup) {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
+        doc.addChildElement(root);
+        
+        MappingSequenceNode sequence = new MappingSequenceNode();
+        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items");         //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = new MappingElement("Suppliers"); //$NON-NLS-1$
+        MappingSequenceNode sequence2 = nestedWrapper.addSequenceNode(new MappingSequenceNode());
+
+        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource(queryGroup);
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", queryGroup+".supplierNum"));//$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+        sequence3.addChildElement(new MappingElement("Name", queryGroup+".supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence3.addChildElement(new MappingElement("Zip", queryGroup+".supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        //NESTED STUFF======================================================================
+       
+        sequence1.addChildElement(nestedWrapper);
+        root.addSequenceNode(sequence);
+        return doc;  
+    }    
+
+    /**
+     * for defect 12260
+     */
+    private static MappingNode createXMLPlanCorrelatedSubqueryTransform() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        
+        MappingSequenceNode sequence = new MappingSequenceNode();
+        MappingElement cats = sequence.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        MappingSequenceNode sequence0 = items.addSequenceNode(new MappingSequenceNode());
+
+        MappingElement item = sequence0.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.itemsWithNumSuppliers"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.itemsWithNumSuppliers.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode sequence1 = item.addSequenceNode(new MappingSequenceNode());
+        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.itemsWithNumSuppliers.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.itemsWithNumSuppliers.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("numSuppliers", "xmltest.group.itemsWithNumSuppliers.numSuppliers")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        root.addSequenceNode(sequence);
+        return doc;  
+    }
+
+    private static MappingNode createXMLPlan_9893() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
+        
+        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+        
+        MappingElement node = seq.addChildElement(new MappingElement("ItemName", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        node.setSource("xmltest.group.items"); //$NON-NLS-1$
+        node.setMaxOccurrs(-1);
+        node.setMaxOccurrs(MappingNodeConstants.CARDINALITY_UNBOUNDED.intValue());
+        return doc;  
+    }
+
+    /** 
+     * DEFECT 8373
+     */
+    private static Object createXMLPlan_defect8373() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.items8373"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.items8373.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        return doc;  
+    }
+
+    /** 
+     * DEFECT 8373
+     */
+    private static Object createXMLPlan_defect8373a() {        
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.items8373a"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.setStagingTables(Arrays.asList(new String[] {"xmltest.items8373"})); //$NON-NLS-1$
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373a.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.items8373a.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373a.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        return doc;  
+    }
+    
+    /** 
+     * DEFECT 8373
+     */
+    private static Object createXMLPlan_defect8373b() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.items8373b"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.setStagingTables(Arrays.asList(new String[] {"xmltest.group.items"})); //$NON-NLS-1$
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items8373b.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.items8373b.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.items8373b.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        return doc;
+    }    
+    
+    private static MappingNode createXMLPlanNested2() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+        
+        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+                        
+        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
+        
+        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+        order.setSource("xmltest.orders"); //$NON-NLS-1$
+        order.setMaxOccurrs(-1);
+        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        order.addChildElement(new MappingElement("OrderStatus", "xmltest.orders.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setMinOccurrs(0);                
+        //NESTED STUFF======================================================================
+        return doc;  
+    }
+
+	/** nested with sibling*/
+	private MappingNode createXMLPlanNested2c() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+		//NESTED STUFF======================================================================
+        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+        
+        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement ordersWrapper = item.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
+        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+        order.setSource("xmltest.orders"); //$NON-NLS-1$
+        order.setMaxOccurrs(-1);
+        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("Name", "xmltest.orders.orderName")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("Zip", "xmltest.orders.orderZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+		//NESTED STUFF======================================================================
+		return doc;  
+	}
+
+
+    private static MappingNode createXMLPlanNested2a() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders", "tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);    
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+        
+        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$        
+        
+        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+        order.setSource("xmltest.ordersA"); //$NON-NLS-1$
+        order.setMaxOccurrs(-1);
+        order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersA.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersA.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersA.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersA.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setMinOccurrs(0);                
+        //NESTED STUFF======================================================================
+        return doc;  
+    }
+
+    // for doc 9b - test temp group w/ bindings
+    private static MappingNode createXMLPlanNested2b() {
+        
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders", "tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$      
+        
+        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+
+        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$        
+        
+        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+        order.setSource("xmltest.ordersB"); //$NON-NLS-1$
+        
+        order.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders3B"})); //$NON-NLS-1$ 
+        order.addAttribute(new MappingAttribute("OrderID", "xmltest.ordersB.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderDate", "xmltest.ordersB.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.ordersB.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        order.addChildElement(new MappingElement("OrderStatus", "xmltest.ordersB.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setMinOccurrs(0);                
+        //NESTED STUFF======================================================================
+        return doc;
+    }
+
+    public static MappingDocument createXMLPlanNestedWithChoice() {
+        MappingCriteriaNode critNode = new MappingCriteriaNode();
+        MappingElement defaltElement = critNode.addChildElement(new MappingElement("OtherOrder")); //$NON-NLS-1$
+        defaltElement.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum"));//$NON-NLS-1$ //$NON-NLS-2$                
+        return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$
+    }
+
+    private static MappingNode createXMLPlanNestedWithChoiceFor5266() {
+        MappingCriteriaNode critNode = new MappingCriteriaNode("xmltest.orders.orderStatus = 'shipped'", true); //$NON-NLS-1$
+        return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$        
+    }
+    
+    private static MappingNode createXMLPlanNestedWithLookupChoice() {
+        MappingCriteriaNode critNode = new MappingCriteriaNode(); 
+        MappingElement defaltElement = critNode.addChildElement(new MappingElement("OtherOrder"));//$NON-NLS-1$
+        defaltElement.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum"));//$NON-NLS-1$ //$NON-NLS-2$                
+        return baseXMLPlanNestedWithLookupChoice("lookup('stock.items', 'itemNum', 'itemName', xmltest.orders.orderStatus) = 'processing'", critNode); //$NON-NLS-1$
+    }
+    
+    private static MappingDocument baseXMLPlanNestedWithLookupChoice(String criteria, MappingCriteriaNode defaultNode) {        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        
+        MappingSequenceNode seq1 = root.addSequenceNode(new MappingSequenceNode());
+        MappingElement cats = seq1.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        
+        MappingSequenceNode seq2 = items.addSequenceNode(new MappingSequenceNode());
+        
+        MappingElement item = seq2.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingSequenceNode seq3 = item.addSequenceNode(new MappingSequenceNode());        
+        seq3.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq3.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        //NESTED STUFF======================================================================
+        MappingElement suppliers = seq3.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+        
+        MappingSequenceNode seq4 = suppliers.addSequenceNode(new MappingSequenceNode());        
+        MappingElement supplier = seq4.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingSequenceNode seq5 = supplier.addSequenceNode(new MappingSequenceNode());
+        seq5.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq5.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement ordersWrapper = seq5.addChildElement(new MappingElement("ProcessingOrders")); //$NON-NLS-1$
+        
+        MappingChoiceNode choice = ordersWrapper.addChoiceNode(new MappingChoiceNode(false));
+        choice.setSource("xmltest.orders"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode(criteria, false)); 
+        MappingElement order = crit.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingSequenceNode seq6 = order.addSequenceNode(new MappingSequenceNode());      
+        seq6.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq6.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        choice.addCriteriaNode(defaultNode);
+        //NESTED STUFF======================================================================
+        return doc;        
+    }
+
+
+    private static MappingNode createTestAttributePlan() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("FixedValueTest")); //$NON-NLS-1$
+        
+        //sequence
+        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());       
+        
+        MappingElement wrapper = seq.addChildElement(new MappingElement("wrapper")); //$NON-NLS-1$
+        wrapper.setSource("xmltest.group.items"); //$NON-NLS-1$
+        wrapper.setMaxOccurrs(-1);
+        MappingAttribute att = new MappingAttribute("fixedAttr"); //$NON-NLS-1$
+        att.setValue("fixed attribute"); //$NON-NLS-1$
+        wrapper.addAttribute(att);
+        
+        //sequence
+        MappingSequenceNode seq1 = wrapper.addSequenceNode(new MappingSequenceNode());
+        seq1.addChildElement(new MappingElement("key","xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq1.addChildElement(new MappingElement("fixed")) //$NON-NLS-1$
+            .setValue("fixed value"); //$NON-NLS-1$
+        
+        return doc;
+    }
+
+    private static Object createUpdateTestDoc() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("UpdateTest")); //$NON-NLS-1$
+        
+        MappingSequenceNode seq = root.addSequenceNode(new MappingSequenceNode());
+        seq.setSource("xmltest.updateTest"); //$NON-NLS-1$
+        seq.addChildElement(new MappingElement("data", "xmltest.updateTest.rowCount")); //$NON-NLS-1$ //$NON-NLS-2$        
+        return doc;
+    }
+
+    private static MappingNode createXMLPlanWithComment(){
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
+        
+        root.addCommentNode(new MappingCommentNode("Comment1")); //$NON-NLS-1$
+        MappingElement node = root.addChildElement(new MappingElement("Something")); //$NON-NLS-1$
+        node.addCommentNode(new MappingCommentNode("Comment2")); //$NON-NLS-1$
+        return doc;
+    }
+
+    public static MappingDocument createXMLMappingBoundingNode() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs"));//$NON-NLS-1$
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+       
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMinOccurrs(1);
+        item.setMaxOccurrs(2);
+        
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$        
+        return doc;
+    }
+    
+    public static MappingDocument createXMLMappingNode(boolean format) {
+        MappingDocument doc = new MappingDocument(format);
+        doc.addChildElement(createXMLPlan1Unformatted(false, 1));
+        return doc;
+    }
+    
+    private static MappingNode createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
+        MappingDocument doc = new MappingDocument(format);
+        doc.addChildElement(createXMLPlan1Unformatted(testNillable, cardinality));
+        return doc;
+    }    
+    
+    private static MappingNode createXMLPlanSOAP() {
+
+        Namespace namespace = new Namespace("ORG", "http://www.mm.org/dummy"); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("TaxReports", namespace)); //$NON-NLS-1$
+        
+        root.setNamespaces(new Namespace[] {namespace});
+        
+        MappingElement report = root.addChildElement(new MappingElement("TaxReport", namespace)); //$NON-NLS-1$
+        report.setNamespaces(new Namespace[] {namespace});
+               
+        Namespace xsiNamespace = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace soapNamespace = new Namespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingElement taxIds = report.addChildElement(new MappingElement("ArrayOfTaxID", namespace)); //$NON-NLS-1$
+        taxIds.setMinOccurrs(0);
+        taxIds.setNamespaces(new Namespace[] {xsiNamespace, soapNamespace});
+        
+        MappingAttribute xsiType = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
+        xsiType.setValue(namespace.getPrefix()+":ArrayOfTaxIDType"); //$NON-NLS-1$        
+        xsiType.setOptional(true);
+        taxIds.addAttribute(xsiType);
+        
+        MappingAttribute arrayType = new MappingAttribute("arrayType", soapNamespace); //$NON-NLS-1$
+        arrayType.setValue( namespace.getPrefix()+":TaxIDType[]"); //$NON-NLS-1$
+        arrayType.setOptional(true);
+        taxIds.addAttribute(arrayType);
+          
+        MappingElement taxId = taxIds.addChildElement(new MappingElement("TaxID", namespace)); //$NON-NLS-1$
+        taxId.setSource("xmltest.group.TaxIDs"); //$NON-NLS-1$
+        taxId.setMaxOccurrs(-1);
+        MappingAttribute xsiType2 = new MappingAttribute("type", xsiNamespace); //$NON-NLS-1$
+        xsiType2.setValue(namespace.getPrefix()+":TaxIDType"); //$NON-NLS-1$
+        xsiType2.setOptional(true);
+        taxId.addAttribute(xsiType2);
+
+        taxId.addChildElement(new MappingElement("ID", "xmltest.group.TaxIDs.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+        return doc;
+    }    
+    
+    
+    private static MappingElement createXMLPlan1Unformatted( boolean testNillable, int cardinality ) {
+
+        MappingElement root = new MappingElement("Catalogs");//$NON-NLS-1$
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        items.setNillable(testNillable);
+        items.setMinOccurrs(cardinality);
+            
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName").setNillable(true)); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$        
+        return root;                                
+    }
+
+    private static MappingNode createXMLPlanDefect13617() {
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+       
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.setMinOccurrs(0);
+        
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setMinOccurrs(0);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$        
+            .setMinOccurrs(0);
+ 
+        return doc;                                
+    }     
+    
+
+    private static MappingNode createXMLPlan2(int numChoices, int numDefaultChoice, boolean exception_on_Default) {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        // ======================================================================
+        // CHOICE NODE STUFF
+        //choice node, non-visual, so it has no name        
+        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exception_on_Default));
+        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        if (numChoices >= 1){
+            MappingCriteriaNode item = getChoiceChild("Item", "xmltest.group.items.itemName='Lamp'", numDefaultChoice == 1); //$NON-NLS-1$ //$NON-NLS-2$
+            choice.addCriteriaNode(item);
+        }
+        if (numChoices >= 2){
+            MappingCriteriaNode item = getChoiceChild("Item2", "xmltest.group.items.itemName='Screwdriver'", numDefaultChoice == 2); //$NON-NLS-1$ //$NON-NLS-2$
+            choice.addCriteriaNode(item);
+        }
+        if (numChoices >= 3){
+            MappingCriteriaNode item = getChoiceChild("Item3", "xmltest.group.items.itemName='Goat'", numDefaultChoice == 3); //$NON-NLS-1$ //$NON-NLS-2$
+            choice.addCriteriaNode(item);
+        }
+        if (numDefaultChoice > numChoices){
+            MappingCriteriaNode item = getChoiceChild("ItemDefault", null, true); //$NON-NLS-1$
+            choice.addCriteriaNode(item);
+        }
+        
+        // ======================================================================
+        return doc;                                
+    }
+
+    private static MappingCriteriaNode getChoiceChild(String name, String criteria, boolean defalt){
+        MappingCriteriaNode crit = new MappingCriteriaNode(criteria, defalt);
+        
+        MappingElement item = crit.addChildElement(new MappingElement(name));
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        return crit;
+    }    
+
+    private static MappingDocument createXMLPlanWithDefaults() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("1"); //$NON-NLS-1$
+
+        return doc;                                
+    }
+
+    private static MappingNode createXMLPlanUltraAdvanced() {
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        //choice node, non-visual, so it has no name
+        boolean exceptionOnDefault = false;
+        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
+        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$       
+        MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$         
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+
+        MappingCriteriaNode crit2= choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
+        MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$         
+        discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+        
+        MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode()); 
+        MappingElement unknown = crit3.addChildElement(new MappingElement("StatusUnknown"));//$NON-NLS-1$
+        unknown.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        unknown.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        unknown.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+                
+        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$ 
+        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)).setExclude(true); //$NON-NLS-1$ 
+        
+        return doc;        
+    }
+    
+  
+
+    private static MappingNode createXMLPlanUltraAdvancedExceptionOnDefault() {
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        //choice node, non-visual, so it has no name
+        boolean exceptionOnDefault = true;
+        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode(exceptionOnDefault));
+        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit1 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$     
+        MappingElement item = crit1.addChildElement(new MappingElement("Item")); //$NON-NLS-1$        
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+
+        MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
+        MappingElement discontinued = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$ 
+        discontinued.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        discontinued.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+                .setNillable(true);
+        discontinued.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+                        
+        choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)).setExclude(true); //$NON-NLS-1$ 
+        
+        return doc; 
+    }
+
+    //advanced tests of namespace declarations, use and scope; also fixed values
+    private static MappingNode createXMLPlanAdvanced() {
+        //add to previous example
+        MappingDocument doc = createXMLPlanWithDefaults();
+        MappingElement root = (MappingElement)doc.getRootNode();
+
+        Namespace nameSpaceOne = new Namespace("duh", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace nameSpaceTwo = new Namespace("duh2", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace nameSpaceThree = new Namespace("duh", "http://www.duh.org/duh/duh"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace nameSpaceFour = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, ""); //$NON-NLS-1$                      
+        Namespace nameSpaceFive = new Namespace(MappingNodeConstants.DEFAULT_NAMESPACE_PREFIX, "http://www.default.org/default"); //$NON-NLS-1$        
+                        
+        MappingElement fakeChildOfRoot = new MappingElement("Fake", nameSpaceOne); //$NON-NLS-1$
+        fakeChildOfRoot.setValue("fixed constant value"); //$NON-NLS-1$                       
+        fakeChildOfRoot.addNamespace(nameSpaceOne);
+        fakeChildOfRoot.addNamespace(nameSpaceTwo);
+        fakeChildOfRoot.addNamespace(nameSpaceFive);
+        root.addChildElement(fakeChildOfRoot);
+
+        MappingElement fakeChild2 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild2", nameSpaceOne)); //$NON-NLS-1$ 
+
+        //add fakeChild2a with default namespace
+        MappingElement fakeChild2a = fakeChild2.addChildElement(new MappingElement("FakeChild2a")); //$NON-NLS-1$
+        fakeChild2a.setValue("another fixed constant value"); //$NON-NLS-1$
+ 
+        MappingElement fakeChild3 = fakeChildOfRoot.addChildElement(new MappingElement("FakeChild3")); //$NON-NLS-1$
+        fakeChild3.addNamespace(nameSpaceThree);
+        fakeChild3.addNamespace(nameSpaceFour);        
+
+        MappingAttribute fakeAtt = new MappingAttribute("FakeAtt", nameSpaceOne); //$NON-NLS-1$
+        fakeAtt.setValue("fixed att value"); //$NON-NLS-1$
+        fakeChild3.addAttribute(fakeAtt);
+                
+        return doc;                                
+    }
+
+
+    /**
+     * Method createXMLPlanNested.
+     * @return MappingNode root of mapping doc
+     */
+    private static MappingNode createXMLPlanMultipleDocs() {
+
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        root.setSource("xmltest.group.items"); //$NON-NLS-1$
+        root.setMaxOccurrs(-1);
+        root.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+         
+        MappingSequenceNode sequence1 = root.addSequenceNode(new MappingSequenceNode());
+        sequence1.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        //NESTED STUFF======================================================================
+        MappingElement nestedWrapper = sequence1.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+        MappingSequenceNode sequence2 =  nestedWrapper.addSequenceNode(new MappingSequenceNode());
+        
+        MappingElement supplier = sequence2.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+        supplier.setSource("xmltest.suppliers"); //$NON-NLS-1$
+        supplier.setMaxOccurrs(-1);
+        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingSequenceNode sequence3 = supplier.addSequenceNode(new MappingSequenceNode());
+        sequence3.addChildElement(new MappingElement("Name", "xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$        
+        sequence3.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+        return doc;  
+    }
+
+    private static MappingNode createXMLPlanRecursive(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
+        
+        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+        ceo.setSource("xmltest.employees"); //$NON-NLS-1$
+        ceo.setMinOccurrs(0);
+        ceo.setMaxOccurrs(-1);
+        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode sequence = ceo.addSequenceNode(new MappingSequenceNode());
+        sequence.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+        MappingElement subordinates = sequence.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+        
+        //recursive piece
+        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
+        employee.setSource("xmltest.employeesRecursive"); //$NON-NLS-1$
+        employee.setMinOccurrs(0);
+        employee.setMaxOccurrs(-1);
+
+        if (useRecursiveCriteria){
+            employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
+        }        
+        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+        return doc;  
+    }
+
+    /*
+     * Recursion root mapping class is anchored at sequence node instead of "Employee" node
+     */
+    private static MappingNode createXMLPlanRecursiveA(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
+
+        MappingSequenceNode seq0 = root.addSequenceNode(new MappingSequenceNode());
+        seq0.setSource("xmltest.employees"); //$NON-NLS-1$
+        seq0.setMinOccurrs(0);
+        seq0.setMaxOccurrs(-1);
+        
+        MappingElement ceo = seq0.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+        seq.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+        MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+
+        //recursive piece
+        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Subordinate", "xmltest.employees")); //$NON-NLS-1$ //$NON-NLS-2$
+        employee.setSource("xmltest.employeesRecursive");  //$NON-NLS-1$
+        employee.setMinOccurrs(0);
+        employee.setMaxOccurrs(-1);
+
+        if (useRecursiveCriteria){
+            employee.setCriteria("xmltest.employees.employeeNum = '04'"); //$NON-NLS-1$
+        }
+        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+        return doc;  
+    }
+    
+    
+    private static MappingNode createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+        
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
+        root.setStagingTables(Arrays.asList(new String[] {"xmltest.doc19temp"})); //$NON-NLS-1$
+
+        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+        ceo.setSource("xmltest.employeesDoc19"); //$NON-NLS-1$
+        ceo.setMinOccurrs(0);
+        ceo.setMaxOccurrs(-1);
+        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employeesDoc19.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+        seq.addChildElement(new MappingElement("FirstName", "xmltest.employeesDoc19.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq.addChildElement(new MappingElement("LastName", "xmltest.employeesDoc19.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+        MappingElement subordinates = seq.addChildElement(new MappingElement("Subordinates")); //$NON-NLS-1$
+
+        //recursive piece
+        MappingRecursiveElement employee = (MappingRecursiveElement)subordinates.addChildElement(new MappingRecursiveElement("Employee", "xmltest.employeesDoc19")); //$NON-NLS-1$ //$NON-NLS-2$
+        employee.setSource("xmltest.employeesRecursiveDoc19"); //$NON-NLS-1$
+        employee.setMinOccurrs(0);
+        employee.setMaxOccurrs(-1);
+
+        if (useRecursiveCriteria){
+            employee.setCriteria("xmltest.employeesDoc19.employeeNum = '04'"); //$NON-NLS-1$
+        }
+        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+
+        return doc;  
+    }
+    
+    private static MappingNode createXMLPlanRecursive2(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
+
+        MappingElement ceo = root.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+        ceo.setSource("xmltest.employees2"); //$NON-NLS-1$
+        ceo.setMinOccurrs(0);
+        ceo.setMaxOccurrs(-1);
+        ceo.addAttribute(new MappingAttribute("ID", "xmltest.employees2.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingSequenceNode seq = ceo.addSequenceNode(new MappingSequenceNode());
+        seq.addChildElement(new MappingElement("FirstName", "xmltest.employees2.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+        seq.addChildElement(new MappingElement("LastName", "xmltest.employees2.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        //recursive piece
+        MappingRecursiveElement employee = (MappingRecursiveElement)seq.addChildElement(new MappingRecursiveElement("Supervisor", "xmltest.employees2")); //$NON-NLS-1$ //$NON-NLS-2$
+        employee.setSource("xmltest.employees2Recursive"); //$NON-NLS-1$
+        employee.setMinOccurrs(0);
+        employee.setMaxOccurrs(-1);
+
+        if (useRecursiveCriteria){
+            employee.setCriteria("xmltest.employees2.employeeNum = '04'"); //$NON-NLS-1$
+        }
+        employee.setRecursionLimit(recursionLimit > 0 ? recursionLimit:10, exceptionOnLimit);
+        return doc;  
+    }
+
+    //this is for testing how "optional" XML elements are included/
+    //excluded from the result document
+    private static MappingNode createXMLPlan_defect8917() {
+        
+        Namespace namespace1 = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        root.addNamespace(namespace1);
+
+        {       
+        //FRAGMENT 1
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setNillable(true);        
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        {
+        //FRAGMENT 2
+        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog")); //$NON-NLS-1$
+        cat.setMinOccurrs(0);
+        
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+        	.setNillable(true); 
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        {
+        //FRAGMENT 3
+        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog2")); //$NON-NLS-1$
+        cat.setMinOccurrs(0);
+        
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setNillable(true);               
+        }        
+        
+        {
+        //FRAGMENT 4
+        MappingElement cat = root.addChildElement(new MappingElement("OptionalCatalog3")); //$NON-NLS-1$
+        cat.setMinOccurrs(0);        
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        } 
+        
+        {
+        //FRAGMENT 5
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog4")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+        items.setMinOccurrs(0);
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        }                 
+        
+        {
+        //FRAGMENT 6            
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog5")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+        items.setMinOccurrs(0);
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.addChildElement(new MappingElement("FixedName")) //$NON-NLS-1$ 
+            .setValue("Nugent"); //$NON-NLS-1$
+        }        
+
+        {
+        //FRAGMENT 7            
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog6")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("OptionalItems")); //$NON-NLS-1$
+        items.setMinOccurrs(0);
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.addChildElement(new MappingElement("EmptyName")); //$NON-NLS-1$ 
+        }        
+        return doc;                                
+    }
+
+    /*
+     * Test of identically named nodes
+     */
+    private static MappingNode createXMLPlan_defect9446() {
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$        
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$        
+        MappingElement item = items.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addAttribute(new MappingAttribute("XXXXX", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("XXXXX", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        return doc;                                
+    }
+    
+    private static MappingNode createXMLPlan_defect_9530() {        
+        Namespace namespace = new Namespace("mm", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace namespace2 = new Namespace("mm", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
+        Namespace namespace3 = new Namespace("mm2", "http://www.duh3.org/duh3"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs", namespace)); //$NON-NLS-1$
+        root.addNamespace(namespace);
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$        
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$        
+        
+        MappingElement item = items.addChildElement(new MappingElement("Item", namespace)); //$NON-NLS-1$
+        item.setSource("xmltest.group.items"); //$NON-NLS-1$
+        item.setMaxOccurrs(-1);
+        item.addNamespace(namespace2);
+        item.addNamespace(namespace3);
+
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+        return doc;                              
+    }    
+    
+    private static MappingNode createGroupDoc() {
+        MappingDocument doc = new MappingDocument(true);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("group")); //$NON-NLS-1$
+        root.setSource("xqttest.group"); //$NON-NLS-1$
+        root.setMinOccurrs(0);
+        root.setMaxOccurrs(-1);
+        
+        MappingAttribute attr = new MappingAttribute("pseudoID", "xqttest.group.ID"); //$NON-NLS-1$ //$NON-NLS-2$         
+        attr.setExclude(true);
+        root.addAttribute(attr);
+
+        MappingSequenceNode sequence = root.addSequenceNode(new MappingSequenceNode());
+        sequence.addChildElement(new MappingElement("ID", "xqttest.group.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence.addChildElement(new MappingElement("code", "xqttest.group.Code")); //$NON-NLS-1$ //$NON-NLS-2$
+
+        MappingElement supervisor = sequence.addChildElement(new MappingElement("supervisor")); //$NON-NLS-1$
+        supervisor.setSource("xqttest.supervisor"); //$NON-NLS-1$
+        supervisor.setMinOccurrs(0);
+        supervisor.setMaxOccurrs(-1);
+
+        MappingSequenceNode sequence1 = supervisor.addSequenceNode(new MappingSequenceNode());
+        sequence1.addChildElement(new MappingElement("ID", "xqttest.supervisor.ID")); //$NON-NLS-1$ //$NON-NLS-2$
+        sequence1.addChildElement(new MappingElement("code", "xqttest.supervisor.Code")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        MappingRecursiveElement group1 = (MappingRecursiveElement)sequence1.addChildElement(new MappingRecursiveElement("group", "xqttest.group")); //$NON-NLS-1$ //$NON-NLS-2$
+        group1.setSource("xqttest.group1"); //$NON-NLS-1$
+        group1.setMinOccurrs(0);
+        group1.setMaxOccurrs(-1);
+        return doc;         
+    }
+
+     
+    // Helper to create a list of elements - used in creating sample data
+    private static List createElements(List elementIDs) { 
+        List elements = new ArrayList();
+        for(int i=0; i<elementIDs.size(); i++) {
+            FakeMetadataObject elementID = (FakeMetadataObject) elementIDs.get(i);            
+            ElementSymbol element = new ElementSymbol(elementID.getName());
+            elements.add(element);
+        }        
+        
+        return elements;
+    }    
+
+    public static FakeDataManager exampleDataManager(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }                    
+
+    public static FakeDataManager exampleDataManager15117(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", " Lamp ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "  Screw  driver  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", " Goat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }     
+
+    /** unusual characters in text */
+    public static FakeDataManager exampleDataManager15117a(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "\t \n\r", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "  >Screw< \n driver  &", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", " >>\rGoat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }    
+    
+    public static FakeDataManager exampleDataManager14905(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { " ", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "  ", "  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { " ", " ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }     
+    
+    public static FakeDataManager exampleDataManager13617(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "004", null, new Integer(1), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ 
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }     
+    
+    public static FakeDataManager exampleDataManagerNested(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+
+            // Group stock.supplier
+            FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+
+            // Group stock.orders
+            FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
+
+            // Group stock.item_supplier
+            FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
+
+            // Group stock.employees
+            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
+
+            // Items
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+
+            // Supplier
+            elementIDs = metadata.getElementIDsInGroupID(groupID2);
+            List supplierElementSymbols = createElements(elementIDs);
+
+            // Orders
+            elementIDs = metadata.getElementIDsInGroupID(groupID3);
+            List ordersElementSymbols = createElements(elementIDs);
+
+            // Item_supplier
+            elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
+            List itemSupplierElementSymbols = createElements(elementIDs);
+
+            // Employees
+            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
+            List employeeSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupID1_2join,
+                itemSupplierElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    } );    
+
+
+            dataMgr.registerTuples(
+                groupID2,
+                supplierElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupID3,
+                ordersElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "1", "002", "54", "Nugent Co.", "10/23/01", new Integer(5), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "2", "001", "52", "Biff's Stuff", "12/31/01", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "3", "003", "56", "Microsoft", "02/31/02", new Integer(12), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "4", "003", "56", "Microsoft", "05/31/02", new Integer(9), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "5", "002", "56", "Microsoft", "06/01/02", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "6", "002", "56", "Microsoft", "07/01/02", new Integer(1), null } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "7", "002", "56", "bad data, shouldn't see", "07/01/02", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupEmployees,
+                employeeSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "01", "1", null, "Ted", "Nugent" } ), //ceo, Nugent Co. //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+                    Arrays.asList( new Object[] { "02", "1", "01", "Bill", "Squier" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "03", "1", "01", "John", "Smith" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "04", "1", "02", "Leland", "Sklar" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "05", "1", "03", "Kevin", "Moore" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "06", "1", "04", "John", "Zorn" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "07", "2", null, "Geoff", "Tate" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+                    Arrays.asList( new Object[] { "08", "2", "07", "Les", "Claypool" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "09", "2", "08", "Meat", "Loaf" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "10", "2", "08", "Keith", "Sweat" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "11", "1", "06", "Mike", "Patton" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "12", "1", "06", "Devin", "Townsend" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "13", "1", "11", "Puffy", "Bordin" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    } );    
+
+
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }                    
+
+	private FakeDataManager exampleDataManagerNestedWithSibling(FakeMetadataFacade metadata) {
+		FakeDataManager dataMgr = new FakeDataManager();
+    
+		try { 
+			// Group stock.items
+			FakeMetadataObject groupID1 = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+
+			// Group stock.supplier
+			FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+
+			// Group stock.orders
+			FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
+
+			// Group stock.item_supplier
+			FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
+
+			// Group stock.item_order
+			FakeMetadataObject groupID1_3join = (FakeMetadataObject) metadata.getGroupID("stock.item_order"); //$NON-NLS-1$
+
+			// Items
+			List elementIDs = metadata.getElementIDsInGroupID(groupID1);
+			List elementSymbols = createElements(elementIDs);
+
+			// Supplier
+			elementIDs = metadata.getElementIDsInGroupID(groupID2);
+			List supplierElementSymbols = createElements(elementIDs);
+
+			// Orders
+			elementIDs = metadata.getElementIDsInGroupID(groupID3);
+			List ordersElementSymbols = createElements(elementIDs);
+
+			// Item_supplier
+			elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
+			List itemSupplierElementSymbols = createElements(elementIDs);
+
+			// Item_order
+			elementIDs = metadata.getElementIDsInGroupID(groupID1_3join);
+			List itemOrderElementSymbols = createElements(elementIDs);
+        
+			dataMgr.registerTuples(
+				groupID1,
+				elementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					} );    
+
+			dataMgr.registerTuples(
+				groupID1_2join,
+				itemSupplierElementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					} );    
+
+
+			dataMgr.registerTuples(
+				groupID2,
+				supplierElementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					} );    
+
+			dataMgr.registerTuples(
+				groupID3,
+				ordersElementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "1", "KMart", "12345" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "2", "Sun", "94040" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "3", "Cisco", "94041" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "4", "Doc", "94042" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "5", "Excite", "21098" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "6", "Yahoo", "94043" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "7", "Inktomi", "94044" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					} );    
+
+			dataMgr.registerTuples(
+				groupID1_3join,
+				itemOrderElementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "001", "1" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "2" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "3" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "001", "4" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "002", "5" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "002", "6" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					Arrays.asList( new Object[] { "003", "7" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					} );    
+
+
+
+		} catch(Throwable e) { 
+			e.printStackTrace();
+			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+		}
+        
+		return dataMgr;
+	}                    
+
+    /**
+     * Returned with some null values in the tuples, to test default/fixed attributes of nodes
+     * as well as nillable nodes
+     */
+    private FakeDataManager exampleDataManagerWithNulls(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }                    
+
+    public static FakeDataManager exampleDataManagerForSoap1(FakeMetadataFacade metadata, boolean makeEmpty) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("taxReport.TaxIDs"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            List[] tuples = null;
+            if (makeEmpty){
+                tuples = new List[0];
+            } else {
+                tuples = new List[] { 
+                    Arrays.asList( new Object[] { "1"} ),         //$NON-NLS-1$
+                    Arrays.asList( new Object[] { "2" } ),         //$NON-NLS-1$
+                    Arrays.asList( new Object[] { "3" } ),         //$NON-NLS-1$
+                    };
+            }
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                tuples );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    } 
+
+    /** data has a null value */
+    private FakeDataManager exampleDataManager_8917(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    } 
+
+    /** data has a NON-EMPTY WHITESPACE string */
+    private FakeDataManager exampleDataManager_8917a(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }
+
+    /** data has an EMPTY STRING */
+    private FakeDataManager exampleDataManager_8917b(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }    
+    
+	/**
+	 * Duplicate records in data
+	 * @param metadata
+	 * @return FakeDataManager
+	 */
+	private FakeDataManager exampleDataManagerWithDuplicates(FakeMetadataFacade metadata) {
+		FakeDataManager dataMgr = new FakeDataManager();
+    
+		try { 
+			// Group stock.items
+			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+			List elementIDs = metadata.getElementIDsInGroupID(groupID);
+			List elementSymbols = createElements(elementIDs);
+        
+			dataMgr.registerTuples(
+				groupID,
+				elementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "002", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					} );    
+
+		} catch(Throwable e) { 
+			e.printStackTrace();
+			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+		}
+        
+		return dataMgr;
+	}                    
+
+	/**
+	 *
+	 * Duplicate records in data to test more than two order by elements at the same depth
+	 * @param metadata
+	 * @return FakeDataManager
+     */
+	private FakeDataManager exampleDataManagerWithDuplicates1(FakeMetadataFacade metadata) {
+		FakeDataManager dataMgr = new FakeDataManager();
+    
+		try { 
+			// Group stock.items
+			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+			List elementIDs = metadata.getElementIDsInGroupID(groupID);
+			List elementSymbols = createElements(elementIDs);
+        
+			dataMgr.registerTuples(
+				groupID,
+				elementSymbols,
+                
+				new List[] { 
+					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "003", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					Arrays.asList( new Object[] { "001", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					} );    
+
+		} catch(Throwable e) { 
+			e.printStackTrace();
+			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+		}
+        
+		return dataMgr;
+	}                   
+		
+    /**
+     * Deluxe example
+     */
+    private FakeDataManager exampleDataManagerDuJour(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "004", "Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "006", "Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }   
+
+    public static FakeDataManager exampleXQTDataManager(FakeMetadataFacade metadata) throws Exception {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        // Group stock.items
+        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("xqt.data"); //$NON-NLS-1$
+        List elementIDs = metadata.getElementIDsInGroupID(groupID);
+        List xqtData = createElements(elementIDs);
+    
+        dataMgr.registerTuples(
+            groupID,
+            xqtData,
+            
+            new List[] { 
+                Arrays.asList( new Object[] { new Integer(1),  new Integer(-2), "-2" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(2),  new Integer(-1), null } ),        
+                Arrays.asList( new Object[] { new Integer(3),  null,            "0" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(4),  new Integer(1),  "1" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(5),  new Integer(2),  "2" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(6),  new Integer(3),  "3" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(7),  new Integer(4),  "4" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(8),  new Integer(5),  null } ),        
+                Arrays.asList( new Object[] { new Integer(9),  null,            "6" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(10), new Integer(7),  "7" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(11), new Integer(8),  "8" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(12), new Integer(9),  "9" } ),         //$NON-NLS-1$
+                Arrays.asList( new Object[] { new Integer(13), new Integer(10), "10" } ),         //$NON-NLS-1$
+                } );    
+
+        return dataMgr;
+    }                    
+
+    public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException { 
+        QueryParser parser = new QueryParser();
+        Command command = parser.parseCommand(sql);
+        QueryResolver.resolveCommand(command, metadata);
+        command = QueryRewriter.rewrite(command, metadata, null);
+        return command;
+    }
+
+    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr) throws Exception{
+        return helpTestProcess(sql, expectedDoc, metadata, dataMgr, null);
+    }
+
+    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException) throws Exception{
+
+        return helpTestProcess(sql, metadata, dataMgr, expectedException, new DefaultCapabilitiesFinder(), expectedDoc);
+    }
+
+    static ProcessorPlan helpTestProcess(String sql, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException, CapabilitiesFinder capFinder, String... expectedDoc) throws Exception{
+        Command command = helpGetCommand(sql, metadata);
+        AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
+
+        try {
+            CommandContext planningContext = new CommandContext(); //this should be the same as the processing context, but that's not easy to do
+            planningContext.setMetadata(new TempMetadataAdapter(metadata, new TempMetadataStore()));
+            ProcessorPlan plan = QueryOptimizer.optimizePlan(command, metadata, null, capFinder, analysisRecord, planningContext);
+            
+            if(DEBUG) {
+                System.out.println(analysisRecord.getDebugLog());
+            }
+            List[] expected = new List[expectedDoc.length];
+            for (int i = 0; i < expectedDoc.length; i++) {
+				expected[i] = Arrays.asList(expectedDoc[i]);
+			}
+            TestProcessor.helpProcess(plan, planningContext, dataMgr, expected);
+            assertNull("Expected failure", expectedException);
+            return plan;
+        } catch (Exception e) {
+        	if (expectedException == null) {
+        		throw e;
+        	}
+        	assertTrue(expectedException.isInstance(e));
+        } finally {
+            if(DEBUG) {
+                System.out.println(analysisRecord.getDebugLog());
+            }                
+        }
+        return null;
+    }
+
+    // =============================================================================================
+    // T E S T S 
+    // =============================================================================================
+
+    @Test public void test1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testOrderBy1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testOrderBy1a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT \"xml\" FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testOrderBy1b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT xmltest.doc1.xml FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+               
+    @Test public void testOrderBy2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Catalogs.Catalog.Items.Item.Quantity DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testOrderBy3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID DESC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+    
+    @Test public void testOrderBy3a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }      
+    
+    @Test public void testOrderBy4() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }     
+     
+    @Test public void testOrderBy5() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+         String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+          
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    } 
+    
+    @Test public void testOrderBy6() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+   
+    //order by with temp group at the root    
+    @Test public void testOrderBy7() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        helpTestProcess("SELECT * FROM xmltest.doc9a ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+           
+    //order by with multiple elements and criteria with long name, short name doesn't work
+    @Test public void testOrderBy8() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +   //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Catalogs.Catalog.Items.Item.Quantity < 60 ORDER BY Catalogs.Catalog.Items.Item.ItemID ASC, Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    /*    
+    @Test public void testOrderBy9() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadata();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = "";
+          
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "Unable to resolve element: Quantity";
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE Quantity < 60 ORDER BY ItemID ASC, SupplierID ASC, OrderID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
+    }
+    */
+  
+    @Test public void testOrderBy10() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Quantity < 60 ORDER BY Name DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }     
+    
+     @Test public void testOrderBy11() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID='001' OR ItemID='002' OR ItemID='003' ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    @Test public void testOrderBy13() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name DESC, Quantity ASC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+        
+    @Test public void testOrderBy14() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+                "<Catalogs>\r\n" + //$NON-NLS-1$
+                "    <Catalog>\r\n" +  //$NON-NLS-1$
+                "        <Items>\r\n" + //$NON-NLS-1$
+                "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+                "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+                "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+                "                <Suppliers>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" +  //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                </Suppliers>\r\n" + //$NON-NLS-1$
+                "            </Item>\r\n" +                  //$NON-NLS-1$
+                "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+                "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+                "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+                "                <Suppliers>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" +  //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                </Suppliers>\r\n" + //$NON-NLS-1$
+                "            </Item>\r\n" +  //$NON-NLS-1$
+                "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+                "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+                "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+                "                <Suppliers>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+                "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                </Suppliers>\r\n" + //$NON-NLS-1$
+                "            </Item>\r\n" +  //$NON-NLS-1$
+                "        </Items>\r\n" +  //$NON-NLS-1$
+                "    </Catalog>\r\n" +  //$NON-NLS-1$
+                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+     
+    @Test public void testOrderBy15() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +      //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /** test null elements*/
+    @Test public void testOrderBy17() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity ASC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    /**  test duplicate elements*/
+    @Test public void testOrderBy18() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithDuplicates(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    /**  test more than two parallel elements*/
+    @Test public void testOrderBy19() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithDuplicates1(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 ORDER BY ItemID ASC, Name ASC, Quantity DESC ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testOrderBy20() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +           //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +         //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+               
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
+            + "ORDER BY SupplierID ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }         
+    
+    /**
+     * Doc nodes that are not mapped to data cannot be used in the 
+     * ORDER BY clause of an XML doc query
+     */
+    @Test public void testOrderBy_defect9803() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+               
+        try {
+            helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000 " //$NON-NLS-1$
+                + "ORDER BY Suppliers", //$NON-NLS-1$
+                "", metadata, dataMgr);  //$NON-NLS-1$
+            fail("Should have failed with QueryPlannerException but didn't"); //$NON-NLS-1$
+        } catch (QueryPlannerException e) {
+            String expectedMsg = "The XML document element [element] name='Suppliers' minOccurs=1 maxOccurs=1 is not mapped to data and cannot be used in the ORDER BY clause: ORDER BY Suppliers"; //$NON-NLS-1$
+            assertEquals(expectedMsg, e.getMessage());
+        }  
+    }    
+        
+    //defect 8130
+    @Test public void test1CriteriaWithUnmappedElementFails() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Catalog = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
+    }    
+
+    //defect 8130
+    @Test public void test1CriteriaWithUnmappedElementFails2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Item = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
+    }  
+    
+    @Test public void testNested() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    private static final String EXPECTED_DOC_NESTED_2 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+    private static final String EXPECTED_DOC_NESTED_3 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+    @Test public void testNested2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2;
+        helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /**
+     * Tests a couple temp groups at the root - B selects from A, and a mapping class
+     * selects from B
+     */
+    @Test public void testNested2aTempGroup() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2;
+        helpTestProcess("SELECT * FROM xmltest.doc9a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    @Test public void testNested2aTempGroupCriteria() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </Catalog>\r\n" +  //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = 1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    /** defect 13172, CSE Case 1811 */
+    @Test public void testNested2aTempGroupCompoundCriteria() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+//        "                        <Orders>\r\n" + //$NON-NLS-1$
+//        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+//        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+//        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+//        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+//        "                            </Order>\r\n" + //$NON-NLS-1$
+//        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </Catalog>\r\n" +  //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = '1' AND tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /** defect 13172, CSE Case 1811 */
+    @Test public void testNested2aTempGroupCompoundCriteria1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+//        "                        <Orders>\r\n" + //$NON-NLS-1$
+//        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+//        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+//        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+//        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+//        "                            </Order>\r\n" + //$NON-NLS-1$
+//        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </Catalog>\r\n" +  //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = 1 AND tempGroup.orders.orderQty = 87", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /** defect 13172, CSE Case 1811 */
+    @Test public void testNested2aTempGroupCompoundCriteria2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+        "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+//        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </Catalog>\r\n" +  //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE tempGroup.orders.orderNum = '1' OR tempGroup.orders.orderStatus = 'processing'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2cTempGroup() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_3;
+        helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID = '001'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    /**
+     * Tests a temp group C that selects from a root temp group, plus has bindings to
+     * some ancestor mapping classes ( we no longer support bindings on staging tables)
+     */
+    public void defer_testNested2bTempGroup() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2;
+        helpTestProcess("SELECT * FROM xmltest.doc9b", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    @Test public void testNested2WithCriteria() throws Exception {
+
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='001'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * <p>This test illustrates how to use the context operator
+     * to specify that the result set to limit is the same as the
+     * result set which the criteria originates from, when that
+     * result set is nested below the top level.
+     * Test {@link #testNested2WithCriteria2a} shows a similar
+     * query without the context operator.</p>
+     * 
+     * @see #testNested2WithCriteria2a
+     */
+    @Test public void testNested2WithCriteria2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        XMLPlan plan = (XMLPlan)helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+
+        // check the staging base line (unknown cost)
+        // one for staging and for unloading
+        Map stats = XMLProgramUtil.getProgramStats(plan.getOriginalProgram());
+        assertEquals(2, ((List)stats.get(ExecStagingTableInstruction.class)).size());
+    }
+
+    /**
+     * <p>This test illustrates how to use the context operator
+     * to specify that the result set to limit is the same as the
+     * result set which the criteria originates from, when that
+     * result set is nested below the top level.
+     * Test {@link #testNested2WithCriteria2a} shows a similar
+     * query without the context operator.</p>
+     * 
+     * <p>defect 9802, trying different ways of qualifying 1st arg
+     * to context operator</p>
+     * 
+     * @see #testNested2WithCriteria2a
+     */
+    @Test public void testNested2WithCriteria2_defect9802() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Supplier.SupplierID, SupplierID)='52'", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }    
+    
+    /**
+     * <p>Same as {@link #testNested2WithCriteria2} but with a
+     * type conversion on the right expression from integer to string.
+     * This demonstrates a function of only constants is executed in
+     * an XML criteria.</p>
+     * shows a similar
+     * @see #testNested2WithCriteria2
+     */
+    @Test public void testNested2WithCriteria2_function() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" + //$NON-NLS-1$
+            "        <Items>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" + //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" + //$NON-NLS-1$
+            "    </Catalog>\r\n" + //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)=convert(52, string)", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    /**
+     * <p>This tests the unintuitive effects of specifying a user
+     * criteria on a node inside a nested mapping class.  Here, the 
+     * "Item" fragment is repeated, but the "Supplier" fragment inside
+     * is limited by the criteria.  
+     * Test {@link #testNested2WithCriteria2} shows how to use
+     * the "context" syntax to control what context the criteria
+     * is used to restrict.</p>
+     * 
+     * <P>UPDATE: With 3.0 sp1 the default behavior is changed.
+     * Now, if "context" syntax is not used, the outer context (anchored 
+     * at "Item" node) will be limited by default, instead of the one
+     * the criteria is actually specified on.</p>
+     */
+    @Test public void testNested2WithCriteria2a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE SupplierID='52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+
+    @Test public void testNested2WithContextCriteria() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, SupplierID)='52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+//            "                                <OrderStatus/>\r\n" +
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+
+    @Test public void testNested2WithContextCriteria4() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria4a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR OrderID='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria4b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='6'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+    @Test public void testNested2WithContextCriteria5() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria5a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria5b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' OR OrderID='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    public static String readFile(String fileName) throws Exception {
+        FileInputStream fis = new FileInputStream(UnitTestUtil.getTestDataFile(fileName));
+        
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        
+        int c = 0;
+        while ((c = fis.read()) != -1) {
+            baos.write(c);
+        }
+        
+        return baos.toString();
+    }
+
+    @Test public void testNested2WithContextCriteria5Fail() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = ""; //doesn't matter //$NON-NLS-1$
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryPlannerException.class;
+        String shouldFailMsg = "expected failure since two different contexts were specified in conjunct"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(SupplierID, OrderID)='2'", expectedDoc, metadata, dataMgr, expectedException);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria6() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items/>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' AND context(Item, OrderID)='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria6b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items/>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' AND OrderID='2'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    //WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'
+    private static final String EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+    @Test public void testNested2WithContextCriteria7() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNested2WithContextCriteria7b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
+        String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
+         + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='5' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
+        helpTestProcess(query, expectedDoc, metadata, dataMgr);        
+    }
+
+    @Test public void testNested2WithContextCriteria7c() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
+        String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
+         + "Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderID)='6' AND context(OrderID, OrderID)='5'"; //$NON-NLS-1$
+        helpTestProcess(query, expectedDoc, metadata, dataMgr);    
+    }
+
+    /**
+     * per defect 7333
+     */
+    @Test public void testNested2WithContextCriteria_7333() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='4' AND ItemID='003'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * per defect 7333
+     */
+    @Test public void testNested2WithContextCriteria_7333b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='003' AND OrderID='4'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * per defect 7333
+     */
+    @Test public void testNested2WithContextCriteria_7333c() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items/>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE OrderID='5' AND ItemID='003'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * per defect 7333
+     */
+    @Test public void testNested2WithContextCriteria_7333d() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items/>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='003' AND OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * Select a single item, and then limit the suppliers based on an order #
+     */
+    @Test public void testNested2WithContextCriteria8() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Context(Supplier,OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testNestedWithChoice() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc10", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /**
+     * Does not use 'context' operator
+     */
+    @Test public void testNestedWithChoiceAndCriteria2_6796() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc10 where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /**
+     * Uses the 'context' operator
+     */
+    @Test public void testNestedWithChoiceAndCriteria2a_6796() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc10 where context(Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /**
+     * Does not use 'context' operator
+     */
+    @Test public void testNestedWithLookupChoice() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                            <OtherOrder OrderID=\"6\"/>\r\n" + //$NON-NLS-1$
+            "                        </ProcessingOrders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc10L where Catalogs.Catalog.Items.Item.Suppliers.Supplier.ProcessingOrders.OtherOrder.OrderID='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+    
+    @Test public void test1Unformatted() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+            "<Catalog>" +  //$NON-NLS-1$
+            "<Items>" +  //$NON-NLS-1$
+            "<Item ItemID=\"001\">" +  //$NON-NLS-1$
+            "<Name>Lamp</Name>" +  //$NON-NLS-1$
+            "<Quantity>5</Quantity>" +  //$NON-NLS-1$
+            "</Item>" +  //$NON-NLS-1$
+            "<Item ItemID=\"002\">" +  //$NON-NLS-1$
+            "<Name>Screwdriver</Name>" +  //$NON-NLS-1$
+            "<Quantity>100</Quantity>" +  //$NON-NLS-1$
+            "</Item>" +  //$NON-NLS-1$
+            "<Item ItemID=\"003\">" +  //$NON-NLS-1$
+            "<Name>Goat</Name>" +  //$NON-NLS-1$
+            "<Quantity>4</Quantity>" +  //$NON-NLS-1$
+            "</Item>" +  //$NON-NLS-1$
+            "</Items>" +  //$NON-NLS-1$
+            "</Catalog>" +  //$NON-NLS-1$
+            "</Catalogs>\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1Unformatted", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+
+    // jhTODO: complete this
+
+    @Test public void testChoice_5266a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" +  //$NON-NLS-1$
+            "   <Catalog>\r\n" +  //$NON-NLS-1$
+            "      <Items>\r\n" +  //$NON-NLS-1$
+            "         <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "            <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "            <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            <Suppliers>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"51\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Chucky</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>11111</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"52\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Biff's Stuff</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>22222</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"53\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>AAAA</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>33333</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "            </Suppliers>\r\n" +  //$NON-NLS-1$
+            "         </Item>\r\n" +  //$NON-NLS-1$
+            "         <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "            <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "            <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            <Suppliers>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"54\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Nugent Co.</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>44444</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"55\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Zeta</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>55555</Zip>\r\n" +  //$NON-NLS-1$\r\n" 
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$\r\n" +  
+            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders/>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "            </Suppliers>\r\n" +  //$NON-NLS-1$
+            "         </Item>\r\n" +  //$NON-NLS-1$
+            "         <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "            <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "            <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            <Suppliers>\r\n" +  //$NON-NLS-1$
+            "               <Supplier SupplierID=\"56\">\r\n" +  //$NON-NLS-1$
+            "                  <Name>Microsoft</Name>\r\n" +  //$NON-NLS-1$
+            "                  <Zip>66666</Zip>\r\n" +  //$NON-NLS-1$
+            "                  <ProcessingOrders>\r\n" +  //$NON-NLS-1$
+            "                     <Order OrderID=\"4\">\r\n" +  //$NON-NLS-1$
+            "                        <OrderDate>05/31/02</OrderDate>\r\n" +  //$NON-NLS-1$
+            "                        <OrderQuantity>9</OrderQuantity>\r\n" +  //$NON-NLS-1$
+            "                     </Order>\r\n" +  //$NON-NLS-1$
+            "                  </ProcessingOrders>\r\n" +  //$NON-NLS-1$
+            "               </Supplier>\r\n" +  //$NON-NLS-1$
+            "            </Suppliers>\r\n" +  //$NON-NLS-1$
+            "         </Item>\r\n" +  //$NON-NLS-1$
+            "      </Items>\r\n" +  //$NON-NLS-1$
+            "   </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc_5266a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    
+    @Test public void test1WithCriteriaShortName() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE quantity < 50", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test1WithCriteriaLongName() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE catalogs.catalog.items.item.quantity < 50", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test2a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc2a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test2b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        helpTestProcess("SELECT * FROM xmltest.doc2b", null, metadata, dataMgr, TeiidComponentException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void test2c() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item2>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc2c", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test2d() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item2>\r\n" +   //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc2d", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void test2e() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item2 ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item2>\r\n" +   //$NON-NLS-1$
+            "            <ItemDefault ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </ItemDefault>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc2e", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testWithNillableNode() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testWithDefault() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>1</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc3", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testWithNamespaces() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>1</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "    <duh:Fake xmlns:duh=\"http://www.duh.org/duh\" xmlns:duh2=\"http://www.duh2.org/duh2\"\n" + //$NON-NLS-1$
+            "              xmlns=\"http://www.default.org/default\">fixed constant value<duh:FakeChild2>\r\n" +  //$NON-NLS-1$
+            "            <FakeChild2a>another fixed constant value</FakeChild2a>\r\n" +  //$NON-NLS-1$
+            "        </duh:FakeChild2>\r\n" +  //$NON-NLS-1$
+            "        <FakeChild3 xmlns:duh=\"http://www.duh.org/duh/duh\" duh:FakeAtt=\"fixed att value\"/>\r\n" +  //$NON-NLS-1$
+            "    </duh:Fake>\r\n" + //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc4", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testWithNewIter3Properties() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc5", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testWithNewIter3PropertiesException() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
+        
+        Command command = helpGetCommand("SELECT * FROM xmltest.doc6", metadata); //$NON-NLS-1$
+        XMLPlan plan = TestXMLPlanner.preparePlan(command, metadata, new DefaultCapabilitiesFinder(), null);
+
+        BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
+        CommandContext context = new CommandContext("pID", null, null, null, 1);                                 //$NON-NLS-1$
+        QueryProcessor processor = new QueryProcessor(plan, context, bufferMgr, dataMgr);
+        processor.setNonBlocking(true);
+        BatchCollector collector = processor.createBatchCollector();
+        TeiidComponentException failOnDefaultException = null;
+        try{
+            collector.collectTuples();
+        } catch (TeiidComponentException e){
+            failOnDefaultException = e;
+        }
+        
+        assertNotNull("Query processing should have failed on default of choice node.", failOnDefaultException); //$NON-NLS-1$
+    }
+
+    @Test public void testAttributeBug() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<FixedValueTest>\r\n" + //$NON-NLS-1$
+            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+            "        <key>001</key>\r\n" + //$NON-NLS-1$
+            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+            "    </wrapper>\r\n" + //$NON-NLS-1$
+            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+            "        <key>002</key>\r\n" + //$NON-NLS-1$
+            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+            "    </wrapper>\r\n" + //$NON-NLS-1$
+            "    <wrapper fixedAttr=\"fixed attribute\">\r\n" + //$NON-NLS-1$
+            "        <key>003</key>\r\n" + //$NON-NLS-1$
+            "        <fixed>fixed value</fixed>\r\n" + //$NON-NLS-1$
+            "    </wrapper>\r\n" + //$NON-NLS-1$
+            "</FixedValueTest>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc7", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testMultipleDocs() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc1 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "    <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "    <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "    <Suppliers>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "            <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "            <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "            <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "    </Suppliers>\r\n" + //$NON-NLS-1$
+            "</Item>\r\n\r\n";  //$NON-NLS-1$
+
+        String expectedDoc2 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "    <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "    <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "    <Suppliers>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "            <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "            <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "    </Suppliers>\r\n" + //$NON-NLS-1$
+            "</Item>\r\n\r\n"; //$NON-NLS-1$
+            
+        String expectedDoc3 = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "    <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "    <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "    <Suppliers>\r\n" + //$NON-NLS-1$
+            "        <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "            <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "            <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "        </Supplier>\r\n" + //$NON-NLS-1$
+            "    </Suppliers>\r\n" + //$NON-NLS-1$
+            "</Item>\r\n\r\n"; //$NON-NLS-1$
+
+
+        helpTestProcess("SELECT * FROM xmltest.doc11", metadata, dataMgr, null, new DefaultCapabilitiesFinder(), expectedDoc1, expectedDoc2, expectedDoc3);         //$NON-NLS-1$
+    }
+
+    @Test public void testRecursive() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates>\r\n" + //$NON-NLS-1$
+            "                            <Employee ID=\"06\">\r\n" +  //$NON-NLS-1$
+            "                                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                                <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
+            "                                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                                    <Employee ID=\"11\">\r\n" +  //$NON-NLS-1$
+            "                                        <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
+            "                                        <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
+            "                                        <Subordinates>\r\n" + //$NON-NLS-1$
+            "                                            <Employee ID=\"13\">\r\n" +  //$NON-NLS-1$
+            "                                                <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
+            "                                                <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
+            "                                                <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                                            </Employee>\r\n" +  //$NON-NLS-1$
+            "                                        </Subordinates>\r\n" + //$NON-NLS-1$
+            "                                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                                    <Employee ID=\"12\">\r\n" +  //$NON-NLS-1$
+            "                                        <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
+            "                                        <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
+            "                                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                                </Subordinates>\r\n" + //$NON-NLS-1$
+            "                            </Employee>\r\n" +  //$NON-NLS-1$
+            "                        </Subordinates>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc12", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    @Test public void testRecursiveA() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Subordinate ID=\"02\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Subordinate ID=\"04\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates>\r\n" + //$NON-NLS-1$
+            "                            <Subordinate ID=\"06\">\r\n" +  //$NON-NLS-1$
+            "                                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                                <LastName>Zorn</LastName>\r\n" + //$NON-NLS-1$
+            "                                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                                    <Subordinate ID=\"11\">\r\n" +  //$NON-NLS-1$
+            "                                        <FirstName>Mike</FirstName>\r\n" + //$NON-NLS-1$
+            "                                        <LastName>Patton</LastName>\r\n" + //$NON-NLS-1$
+            "                                        <Subordinates>\r\n" + //$NON-NLS-1$
+            "                                            <Subordinate ID=\"13\">\r\n" +  //$NON-NLS-1$
+            "                                                <FirstName>Puffy</FirstName>\r\n" + //$NON-NLS-1$
+            "                                                <LastName>Bordin</LastName>\r\n" + //$NON-NLS-1$
+            "                                                <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                                            </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                                        </Subordinates>\r\n" + //$NON-NLS-1$
+            "                                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                                    <Subordinate ID=\"12\">\r\n" +  //$NON-NLS-1$
+            "                                        <FirstName>Devin</FirstName>\r\n" + //$NON-NLS-1$
+            "                                        <LastName>Townsend</LastName>\r\n" + //$NON-NLS-1$
+            "                                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                                </Subordinates>\r\n" + //$NON-NLS-1$
+            "                            </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                        </Subordinates>\r\n" + //$NON-NLS-1$
+            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Subordinate>\r\n" +  //$NON-NLS-1$
+            "            <Subordinate ID=\"03\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Subordinate ID=\"05\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Subordinate>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Subordinate ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Subordinate ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                    <Subordinate ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Subordinate>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Subordinate>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc12a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }    
+    
+    /**
+     * 4/25/05 sbale - This failing test raises a question about recursion
+     * termination criteria - should the chunk of document that meets the 
+     * criteria be included or not?  In this test below, it is expected to
+     * be included, but is not included in actual results due to recent
+     * changes for Booz Allen POC.  I could see it going either way.
+     *  
+     * sbale 4/27/05 I have changed expected results as a result of changes for
+     * Booz Allen POC.  Previously, the recursive fragment of the document that
+     * satisfied the recursion termination criteria was included, now it is not.
+     * See commented out section below for previous expected results. 
+     * @throws Exception
+     */
+    @Test public void testRecursive2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates/>\r\n" + //$NON-NLS-1$
+//            "                <Subordinates>\r\n" + //$NON-NLS-1$
+//            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
+//            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+//            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+//            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+//            "                    </Employee>\r\n" +  //$NON-NLS-1$
+//            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc13", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+    @Test public void testRecursive3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc14", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    @Test public void testRecursive4Exception() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        helpTestProcess("SELECT * FROM xmltest.doc15", null, metadata, dataMgr, TeiidComponentException.class); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /**
+     * Seems to be failing as a result of changes for defect 12288 
+     */
+    @Test public void testRecursive5() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Employees>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "        <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        </Supervisor>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "        <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "            <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+            "                <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "            </Supervisor>\r\n" + //$NON-NLS-1$
+            "        </Supervisor>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "        <Supervisor ID=\"08\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "            <Supervisor ID=\"07\">\r\n" + //$NON-NLS-1$
+            "                <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "            </Supervisor>\r\n" + //$NON-NLS-1$
+            "        </Supervisor>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</Employees>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc16", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    /**
+     * sbale 4/27/05 I have changed expected results as a result of changes for
+     * Booz Allen POC.  Previously, the recursive fragment of the document that
+     * satisfied the recursion termination criteria was included, now it is not.
+     * See commented out section below for previous expected results. 
+     * @throws Exception
+     */
+    @Test public void testRecursiveWithStagingTable_defect15607() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<OrgHierarchy>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"01\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Ted</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Nugent</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"02\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Squier</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates/>\r\n" + //$NON-NLS-1$
+//            "                <Subordinates>\r\n" + //$NON-NLS-1$
+//            "                    <Employee ID=\"04\">\r\n" +  //$NON-NLS-1$
+//            "                        <FirstName>Leland</FirstName>\r\n" + //$NON-NLS-1$
+//            "                        <LastName>Sklar</LastName>\r\n" + //$NON-NLS-1$
+//            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+//            "                    </Employee>\r\n" +  //$NON-NLS-1$
+//            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "            <Employee ID=\"03\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>John</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Smith</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"05\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Kevin</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Moore</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "    <Employee ID=\"07\">\r\n" +  //$NON-NLS-1$
+            "        <FirstName>Geoff</FirstName>\r\n" + //$NON-NLS-1$
+            "        <LastName>Tate</LastName>\r\n" + //$NON-NLS-1$
+            "        <Subordinates>\r\n" + //$NON-NLS-1$
+            "            <Employee ID=\"08\">\r\n" +  //$NON-NLS-1$
+            "                <FirstName>Les</FirstName>\r\n" + //$NON-NLS-1$
+            "                <LastName>Claypool</LastName>\r\n" + //$NON-NLS-1$
+            "                <Subordinates>\r\n" + //$NON-NLS-1$
+            "                    <Employee ID=\"09\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Meat</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Loaf</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                    <Employee ID=\"10\">\r\n" +  //$NON-NLS-1$
+            "                        <FirstName>Keith</FirstName>\r\n" + //$NON-NLS-1$
+            "                        <LastName>Sweat</LastName>\r\n" + //$NON-NLS-1$
+            "                        <Subordinates/>\r\n" + //$NON-NLS-1$
+            "                    </Employee>\r\n" +  //$NON-NLS-1$
+            "                </Subordinates>\r\n" + //$NON-NLS-1$
+            "            </Employee>\r\n" +  //$NON-NLS-1$
+            "        </Subordinates>\r\n" + //$NON-NLS-1$
+            "    </Employee>\r\n" +  //$NON-NLS-1$
+            "</OrgHierarchy>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc19", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+    
+    /**
+     * Tests a recursive nested mapping class within a recursive mapping class, where
+     * all nested "anchor" nodes are named "srcNestedRecursive".  Test of defect #5988
+     */
+    @Test public void testXQTRecursive_5988() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadata2();
+        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<recursiveTest>\r\n" +  //$NON-NLS-1$
+            "    <src>\r\n" + //$NON-NLS-1$
+            "        <key>13</key>\r\n" + //$NON-NLS-1$
+            "        <data>10</data>\r\n" + //$NON-NLS-1$
+            "        <srcNested>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "            </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "        </srcNested>\r\n" + //$NON-NLS-1$
+            "        <srcRecursive>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcNested>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "            </srcNested>\r\n" + //$NON-NLS-1$
+            "            <srcRecursive>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcNested>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNestedRecursive>\r\n" + //$NON-NLS-1$
+            "                </srcNested>\r\n" + //$NON-NLS-1$
+            "                <srcRecursive>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNested>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNested>\r\n" + //$NON-NLS-1$
+            "                    <srcRecursive>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcRecursive>\r\n" + //$NON-NLS-1$
+            "                </srcRecursive>\r\n" + //$NON-NLS-1$
+            "            </srcRecursive>\r\n" + //$NON-NLS-1$
+            "        </srcRecursive>\r\n" + //$NON-NLS-1$
+            "    </src>\r\n" + //$NON-NLS-1$
+            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xqttest.doc1", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    /**
+     * Tests a non-recursive nested mapping class within a recursive mapping class, where
+     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
+     */
+    public void DEFER_testXQTRecursive1a_5988() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadata2();
+        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<recursiveTest>\r\n" +  //$NON-NLS-1$
+            "    <src>\r\n" + //$NON-NLS-1$
+            "        <key>13</key>\r\n" + //$NON-NLS-1$
+            "        <data>10</data>\r\n" + //$NON-NLS-1$
+            "        <srcNested>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "        </srcNested>\r\n" + //$NON-NLS-1$
+            "        <srcNested>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcNested>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "            </srcNested>\r\n" + //$NON-NLS-1$
+            "            <srcNested>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcNested>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                </srcNested>\r\n" + //$NON-NLS-1$
+            "                <srcNested>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNested>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNested>\r\n" + //$NON-NLS-1$
+            "                    <srcNested>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNested>\r\n" + //$NON-NLS-1$
+            "                </srcNested>\r\n" + //$NON-NLS-1$
+            "            </srcNested>\r\n" + //$NON-NLS-1$
+            "        </srcNested>\r\n" + //$NON-NLS-1$
+            "    </src>\r\n" + //$NON-NLS-1$
+            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xqttest.doc1a", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    /**
+     * Tests a non-recursive nested mapping class within a recursive mapping class, where
+     * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
+     */
+    @Test public void testXQTRecursive2_5988() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadata2();
+        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<recursiveTest>\r\n" +  //$NON-NLS-1$
+            "    <src>\r\n" + //$NON-NLS-1$
+            "        <key>13</key>\r\n" + //$NON-NLS-1$
+            "        <data>10</data>\r\n" + //$NON-NLS-1$
+            "        <srcNested>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "        </srcNested>\r\n" + //$NON-NLS-1$
+            "        <srcNested>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcNested>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "            </srcNested>\r\n" + //$NON-NLS-1$
+            "            <srcNested>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcNested>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                </srcNested>\r\n" + //$NON-NLS-1$
+            "                <srcNested>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcNested>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNested>\r\n" + //$NON-NLS-1$
+            "                    <srcNested>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcNested>\r\n" + //$NON-NLS-1$
+            "                </srcNested>\r\n" + //$NON-NLS-1$
+            "            </srcNested>\r\n" + //$NON-NLS-1$
+            "        </srcNested>\r\n" + //$NON-NLS-1$
+            "    </src>\r\n" + //$NON-NLS-1$
+            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xqttest.doc3", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+
+    /**
+     * for defect 5988
+     */
+    @Test public void testXQTRecursiveSiblings_5988() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadata2();
+        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<recursiveTest>\r\n" +  //$NON-NLS-1$
+            "    <src>\r\n" + //$NON-NLS-1$
+            "        <key>13</key>\r\n" + //$NON-NLS-1$
+            "        <data>10</data>\r\n" + //$NON-NLS-1$
+            "        <srcSibling1>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling2>\r\n" + //$NON-NLS-1$
+            "            </srcSibling1>\r\n" + //$NON-NLS-1$
+            "            <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling2>\r\n" + //$NON-NLS-1$
+            "            </srcSibling2>\r\n" + //$NON-NLS-1$
+            "        </srcSibling1>\r\n" + //$NON-NLS-1$
+            "        <srcSibling2>\r\n" + //$NON-NLS-1$
+            "            <key>10</key>\r\n" + //$NON-NLS-1$
+            "            <data>7</data>\r\n" + //$NON-NLS-1$
+            "            <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling2>\r\n" + //$NON-NLS-1$
+            "            </srcSibling1>\r\n" + //$NON-NLS-1$
+            "            <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                <key>7</key>\r\n" + //$NON-NLS-1$
+            "                <data>4</data>\r\n" + //$NON-NLS-1$
+            "                <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                    <key>4</key>\r\n" + //$NON-NLS-1$
+            "                    <data>1</data>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling1>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling1>\r\n" + //$NON-NLS-1$
+            "                    <srcSibling2>\r\n" + //$NON-NLS-1$
+            "                        <key>1</key>\r\n" + //$NON-NLS-1$
+            "                        <data>-2</data>\r\n" + //$NON-NLS-1$
+            "                    </srcSibling2>\r\n" + //$NON-NLS-1$
+            "                </srcSibling2>\r\n" + //$NON-NLS-1$
+            "            </srcSibling2>\r\n" + //$NON-NLS-1$
+            "        </srcSibling2>\r\n" + //$NON-NLS-1$
+            "    </src>\r\n" + //$NON-NLS-1$
+            "</recursiveTest>\r\n\r\n";  //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xqttest.doc2", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
+    }
+
+    @Test public void testSelectElement1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+          
+        helpTestProcess("SELECT Name FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+     
+    @Test public void testSelectElement2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+                
+        helpTestProcess("SELECT SupplierID, OrderID, ItemID, OrderQuantity FROM xmltest.doc9 ORDER BY "+ //$NON-NLS-1$
+            " Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
+            " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
+    }
+    
+    /** select element in the reverse order of depth*/
+    @Test public void testSelectElement3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+                
+        helpTestProcess("SELECT OrderQuantity, SupplierID, ItemID, OrderID FROM xmltest.doc9"  + //$NON-NLS-1$
+            " ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC," + //$NON-NLS-1$
+            " OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
+    }
+    
+    /** two select elements at the same level*/
+    @Test public void testSelectElement4() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+          
+        helpTestProcess("SELECT ItemID, Name, Quantity FROM xmltest.doc1 WHERE ItemID='001' OR "  //$NON-NLS-1$
+            + " ItemID='002' OR ItemID='003' ORDER BY ItemID", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** defect 9756 */
+    @Test public void testSelectElement4_defect9756() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\"/>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\"/>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\"/>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+          
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item. at ItemID FROM xmltest.doc1", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }    
+    
+    /** three select elements with two of them at the same level and there are other nodes with the same name*/
+    @Test public void testSelectElement5() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" +          //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" +            //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" +          //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" +        //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" +            //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" +           //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+                
+        helpTestProcess("SELECT OrderQuantity, SupplierID, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, OrderID, ItemID "  //$NON-NLS-1$
+            + "FROM xmltest.doc9 ORDER BY Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID ASC, "  //$NON-NLS-1$
+            + "OrderID DESC, Catalogs.Catalog.Items.Item.ItemID DESC", expectedDoc, metadata, dataMgr);           //$NON-NLS-1$
+    }
+    
+    /** check element.* case */
+    @Test public void testSelectElement6() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+         
+        helpTestProcess("SELECT Item.* FROM xmltest.doc1 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    /** check element.* case without attribute in order by*/
+    @Test public void testSelectElement6a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+         
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Quantity" //$NON-NLS-1$
+            + " FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testSelectElement7() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+         
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID",  //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    @Test public void testSelectElement8() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+         
+        helpTestProcess("SELECT xmltest.doc1.Catalogs.Catalog.Items.Item.* FROM xmltest.doc1 ORDER BY ItemID",  //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** SELECT clause has element.*, but the sibling elements should not be included, only subtree should */
+    @Test public void testSelectElement9() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+      helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
+          + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' ", //$NON-NLS-1$
+          expectedDoc, metadata, dataMgr);        
+    }         
+    
+    @Test public void testSelectElement9a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Suppliers.Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
+            + "WHERE ItemID='002' AND Context(Supplier,OrderID)='5' AND Context(OrderID, OrderID)='5'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }    
+             
+    /** check element.* case with criteria and order by clause */
+    @Test public void testSelectElement10() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+         
+        helpTestProcess("SELECT Item.* FROM xmltest.doc1 WHERE Quantity <= 100 ORDER BY ItemID",  //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    @Test public void testSelectElement12() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT Supplier.*, ItemID FROM xmltest.doc9 "  //$NON-NLS-1$
+            + " WHERE ItemID='002'" //$NON-NLS-1$
+            + " ORDER BY SupplierID, OrderID DESC, ItemID", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);                
+    }
+    
+    @Test public void testSelectElement13() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT Name, Quantity FROM xmltest.doc1 "  //$NON-NLS-1$
+            + "WHERE ItemID='002'" //$NON-NLS-1$
+            + "ORDER BY Name ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);                
+    }
+
+    @Test public void testSelectElement14() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +           //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +         //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders/>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                        <Orders>\r\n" + //$NON-NLS-1$
+            "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" +  //$NON-NLS-1$
+            "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+            "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+            "                            </Order>\r\n" + //$NON-NLS-1$
+            "                        </Orders>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+               
+            helpTestProcess("SELECT * FROM xmltest.doc9 WHERE ItemID='002' AND Catalogs.Catalog.Items.Item.Suppliers.Supplier.Orders.Order.OrderQuantity < 1000"  //$NON-NLS-1$
+                + " ORDER By SupplierID ASC, OrderID ",  //$NON-NLS-1$
+                expectedDoc, metadata, dataMgr);        
+    }
+    
+    @Test public void testSelectElement15() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc =
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+                "    <Catalog>\r\n" +  //$NON-NLS-1$
+                "        <Items>\r\n" +           //$NON-NLS-1$
+                "            <Item>\r\n" +  //$NON-NLS-1$
+                "                <Suppliers>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" +  //$NON-NLS-1$
+                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                </Suppliers>\r\n" + //$NON-NLS-1$
+                "            </Item>\r\n" +           //$NON-NLS-1$
+                "        </Items>\r\n" +  //$NON-NLS-1$
+                "    </Catalog>\r\n" +  //$NON-NLS-1$
+                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+               
+        helpTestProcess("SELECT Supplier.* FROM xmltest.doc9 "  //$NON-NLS-1$
+            + " WHERE ItemID='002'" //$NON-NLS-1$
+            + " ORDER By SupplierID ",  //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+
+    @Test public void testSelectElement16() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc =
+                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+                "<Catalogs>\r\n" + //$NON-NLS-1$
+                "    <Catalog>\r\n" +  //$NON-NLS-1$
+                "        <Items>\r\n" +           //$NON-NLS-1$
+                "            <Item>\r\n" +  //$NON-NLS-1$
+                "                <Suppliers>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders/>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+                "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+                "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+                "                        <Orders>\r\n" + //$NON-NLS-1$
+                "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" +  //$NON-NLS-1$
+                "                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+                "                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+                "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+                "                            </Order>\r\n" + //$NON-NLS-1$
+                "                        </Orders>\r\n" + //$NON-NLS-1$
+                "                    </Supplier>\r\n" + //$NON-NLS-1$
+                "                </Suppliers>\r\n" + //$NON-NLS-1$
+                "            </Item>\r\n" +           //$NON-NLS-1$
+                "        </Items>\r\n" +  //$NON-NLS-1$
+                "    </Catalog>\r\n" +  //$NON-NLS-1$
+                "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+               
+        helpTestProcess("SELECT Supplier.* FROM xmltest.doc9a "  //$NON-NLS-1$
+            + " WHERE ItemID='002'" //$NON-NLS-1$
+            + " ORDER By SupplierID",  //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }         
+
+    /**  CSE query 0 */
+    @Test public void testSelectElement17() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +             //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }   
+
+    /**  CSE query 1 */
+    @Test public void testSelectElement18() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9c WHERE ItemID='002'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }   
+
+    /**  CSE query 2 */
+    @Test public void testSelectElement19() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9c WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }   
+            
+
+    /**  CSE query 3 */
+    @Test public void testSelectElement20() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip" + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }   
+
+    /**  CSE query 3a */
+    @Test public void testSelectElement20a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +           //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Quantity, Catalogs.Catalog.Items.Item.Orders.Order.Zip" + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE Catalogs.Catalog.Items.Item.Name='Screwdriver'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }   
+
+    /**  CSE query 4 */
+    @Test public void testSelectElement21() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +             //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+       
+        helpTestProcess("SELECT * " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' AND context(SupplierID, SupplierID)>'54' ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }  
+
+    /**  CSE query 4a */
+    @Test public void testSelectElement21a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        helpTestProcess("SELECT * " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE OrderID > '4' AND context(OrderID, OrderID)>'4'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }  
+    
+    /**  CSE query 5 */
+    @Test public void testSelectElement22() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +         //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Zip " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '4' ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+    
+    /**  CSE query 5a */
+    @Test public void testSelectElement22a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +             //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemID, Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Orders.Order.Name, OrderID  " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE OrderID > '3' ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+    
+    /**  CSE query 6 */
+    @Test public void testSelectElement23() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +      //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +         //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.Name, Catalogs.Catalog.Items.Item.Suppliers.Supplier.Name, SupplierID " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE OrderID > '4' ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+    
+    /**  CSE query 6a */
+    @Test public void testSelectElement23a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\"/>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"4\"/>\r\n" +       //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"6\"/>\r\n" +   //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, OrderID " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+                     
+    /** test with order by and the element in the criteria is not in the select elements*/
+    @Test public void testSelectElement24() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\"/>\r\n" + //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"6\"/>\r\n" +               //$NON-NLS-1$
+            "                    <Order OrderID=\"5\"/>\r\n" + //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"4\"/>\r\n" +   //$NON-NLS-1$
+            "                    <Order OrderID=\"3\"/>\r\n" +                   //$NON-NLS-1$
+            "                    <Order OrderID=\"2\"/>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\"/>\r\n" + //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ITEMID, OrderID " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+
+    /** test element.* with order by and the element in the criteria is not in the select elements*/
+    @Test public void testSelectElement24a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94044</Zip>\r\n" +             //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +                 //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +                 //$NON-NLS-1$
+            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, Order.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+                         
+    /** test with order by with only necessary sub-mapping classes are queried*/
+    @Test public void testSelectElement25() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\"/>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\"/>\r\n" +                //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\"/>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\"/>\r\n" +                //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\"/>\r\n" +    //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\"/>\r\n" +                    //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\"/>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\"/>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT ItemID, SupplierID " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** test element.* with order by with only necessary sub-mapping classes are queried*/
+    @Test public void testSelectElement25a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +              //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT ItemID, Supplier.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** Test element.* with order by with only necessary sub-mapping classes are queried 
+     *  and case_insensitive nodes in the mapping tree
+     */
+    @Test public void testSelectElement25b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +              //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT ItemID, SUPPLIER.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    @Test public void testSelectElement26() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +              //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT ItemID, xmltest.doc9c.catalogs.catalog.items.item.suppliers.SUPPLIER.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC, SupplierID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+
+    /** test special elements: result set name, and name with format of "document.fully.qualified.element" 
+     * --> refer to Defect9497, this should fail
+     */
+    @Test public void testSelectElement27() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier/>\r\n" + //$NON-NLS-1$
+            "                    <Supplier/>\r\n" + //$NON-NLS-1$
+            "                    <Supplier/>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("SELECT doc9c.catalogs.catalog.items.item.itemID, items.item.name, item.Quantity, supplier " + //$NON-NLS-1$
+        " FROM xmltest.doc9c " + //$NON-NLS-1$
+        " WHERE doc9c.catalogs.catalog.items.item.suppliers.supplier.SupplierID > '54' AND itemID='002'" + //$NON-NLS-1$
+        " ORDER BY doc9c.catalogs.catalog.items.item.ITEMid ", //$NON-NLS-1$
+        expectedDoc, metadata, dataMgr);     
+    }
+        
+    /** test special element, root element */
+    @Test public void testSelectElement28() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT catalogs " +  //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);       
+        
+        /*String expectedDoc = "";
+        try {
+            helpTestProcess("SELECT catalogs " +
+                " FROM xmltest.doc9c " +
+                " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+                expectedDoc, metadata, dataMgr);
+        } catch(QueryPlannerException qpe) {
+        // ok, as expected
+        } */         
+    }
+    
+    /** test special element */
+    @Test public void testSelectElement28a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc =  
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog/>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        /*String expectedDoc = "";
+        try {
+            helpTestProcess("SELECT catalog " +
+            " FROM xmltest.doc9c " +
+            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+            expectedDoc, metadata, dataMgr, false);
+        } catch (QueryPlannerException qpe) {
+        // ok, as expected
+        } */
+        
+        helpTestProcess("SELECT catalog " +  //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);             
+    }
+
+    /** test model.document.* */
+    @Test public void testSelectElement28b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+            
+        helpTestProcess("SELECT xmltest.doc1.* " +  //$NON-NLS-1$
+            "FROM xmltest.doc1 ORDER BY ItemID ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);       
+
+    }
+        
+    /** test special element, root element */
+    @Test public void testSelectElement29() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs/>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT xmltest.doc9c.catalogs " +  //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);             
+        
+        /*String expectedDoc = "";
+        try {
+            helpTestProcess("SELECT xmltest.doc9c.catalogs " +
+            " FROM xmltest.doc9c " +
+            " WHERE item.suppliers.supplier.SupplierID > '54' AND itemID='002'",
+            expectedDoc, metadata, dataMgr);
+        } catch (QueryPlannerException qpe) {
+        // ok, as expected
+        }*/
+
+    }
+    
+    /** test simple case for two elements in a mapping class */
+    @Test public void testSelectElement30() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT item.* FROM xmltest.doc1 WHERE ItemID='001' AND Quantity < 60 ORDER BY ItemID", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }     
+                        
+    /** test NullPointerException*/
+    @Test public void testDefect_9496_1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +              //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT items.item.ItemID, suppliers.supplier.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY  ITEMid DESC, items.item.suppliers.supplier.SupplierID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+
+    @Test public void testDefect_9496_2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                </Suppliers>\r\n" +             //$NON-NLS-1$
+            "            </Item>\r\n" +          //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +          //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +                          //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +  //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" +              //$NON-NLS-1$
+            "                    <Supplier>\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" +     //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT doc9c.Catalogs.catalog.items.item.ItemID, items.item.Suppliers,SuppliER.Name " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY ItemID DESC", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** test StringIndexOutOfBoundsException */
+    @Test public void testDefect_9496_3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+            "                        <Name>KMart</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>12345</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Sun</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94040</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Cisco</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94041</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Doc</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94042</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +             //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" +              //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Excite</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>21098</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                    <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Yahoo</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94043</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +         //$NON-NLS-1$
+            "                </Orders>\r\n" +    //$NON-NLS-1$
+            "            </Item>\r\n" + //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "                <Orders>\r\n" + //$NON-NLS-1$
+            "                    <Order OrderID=\"7\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Inktomi</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>94044</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Order>\r\n" +  //$NON-NLS-1$
+            "                </Orders>\r\n" +            //$NON-NLS-1$
+            "            </Item>\r\n" +               //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        
+        helpTestProcess("SELECT item.itemID, items.item.* " + //$NON-NLS-1$
+            " FROM xmltest.doc9c " + //$NON-NLS-1$
+            " WHERE item.suppliers.supplier.SupplierID > '54' " + //$NON-NLS-1$
+            " ORDER BY  ITEMid, items.item.suppliers.supplier.SupplierID ", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }
+    
+    /** should fail: because there are other element other than "xml" */
+    /*@Test public void testResolver1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = ""; 
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
+        
+        helpTestProcess("SELECT xml, ItemID " +
+            " FROM xmltest.doc9c " +
+            " WHERE SupplierID > '54' " +
+            " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);          
+    }*/
+
+    /** should fail: partial qualified element name and "model.document.xml" */
+    /*@Test public void testResolver2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = ""; 
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "If any symbol in SELECT clause is 'xml' or group.'xml' , then no other element is allowed.";
+        
+        helpTestProcess("SELECT item.ItemID, xmltest.doc9c.xml " +
+            " FROM xmltest.doc9c " +
+            " WHERE SupplierID > '54' " +
+            " ORDER BY ItemID DESC", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);          
+    }*/
+
+    /** should fail: test XMLResolver validatation for model.* */
+    /*@Test public void testDefect_9498_1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = ""; 
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "Unable to resolve element: xmltest";
+
+        helpTestProcess("SELECT xmltest.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
+    }*/
+
+    /** should fail: test XMLResolver validatation for model.document.* */
+    /*@Test public void testDefect_9498_2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = ""; 
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "Unable to resolve element: xmltest.doc9c";
+
+        helpTestProcess("SELECT xmltest.doc9c.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);         
+    }*/
+
+    /** should fail: test XMLResolver validatation for xml.* */
+    /*@Test public void testDefect_9498_3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = ""; 
+
+        boolean shouldSucceed = false;
+        Class expectedException = QueryResolverException.class;
+        String shouldFailMsg = "Unable to resolve element: xml";
+
+        helpTestProcess("SELECT xml.* FROM xmltest.doc9c ", expectedDoc, metadata, dataMgr, shouldSucceed, expectedException, shouldFailMsg);        
+    }*/
+   
+    /** Test element.* with order by with only necessary sub-mapping classes are queried 
+     *  and case_insensitive nodes in the mapping tree
+     */
+    @Test public void testCommentNodeInDoc() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Root><!--Comment1--><Something><!--Comment2--></Something>\r\n" + //$NON-NLS-1$
+            "</Root>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc17", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    }    
+
+    private static final String EXPECTED_DOC_DEFECT_8917_AND_11789 = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </Catalog>\r\n" +  //$NON-NLS-1$
+        "    <OptionalCatalog>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </OptionalCatalog>\r\n" +  //$NON-NLS-1$
+        "    <OptionalCatalog2>\r\n" +  //$NON-NLS-1$
+        "        <Items>\r\n" +  //$NON-NLS-1$
+        "            <Item>\r\n" +  //$NON-NLS-1$
+        "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </Items>\r\n" +  //$NON-NLS-1$
+        "    </OptionalCatalog2>\r\n" +  //$NON-NLS-1$
+        "    <Catalog4/>\r\n" +  //$NON-NLS-1$
+        "    <Catalog5>\r\n" +  //$NON-NLS-1$
+        "        <OptionalItems>\r\n" +  //$NON-NLS-1$
+        "            <Item>\r\n" +  //$NON-NLS-1$
+        "                <FixedName>Nugent</FixedName>\r\n" +  //$NON-NLS-1$
+        "            </Item>\r\n" +  //$NON-NLS-1$
+        "        </OptionalItems>\r\n" +  //$NON-NLS-1$
+        "    </Catalog5>\r\n" +              //$NON-NLS-1$
+        "    <Catalog6/>\r\n" +  //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+    @Test public void testDefect8917() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+        
+//        helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
+        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+        EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);        
+    } 
+    /*
+     * jhTODO
+     */
+    @Test public void testNillableOptional() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+            "<Catalog>" +  //$NON-NLS-1$
+            "<Items xsi:nil=\"true\"/>" +  //$NON-NLS-1$
+            "</Catalog>" +  //$NON-NLS-1$
+            "</Catalogs>"; //$NON-NLS-1$
+       
+        // note: doc1b contains an 'items' element that is nillable = true, and minoccurs = 0 
+        helpTestProcess("SELECT * FROM xmltest.doc1b WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /*
+     * jhTODO
+     */
+    @Test public void testNillableNonOptional() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + //$NON-NLS-1$
+            "<Catalog>" +  //$NON-NLS-1$
+            "<Items xsi:nil=\"true\"/>" +  //$NON-NLS-1$
+            "</Catalog>" +  //$NON-NLS-1$
+            "</Catalogs>"; //$NON-NLS-1$
+        
+        // note: doc1c contains an 'items' element that has no nillable set, and minoccurs = 1 
+        helpTestProcess("SELECT * FROM xmltest.doc1c WHERE ItemID='9999' ", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /** 
+     * Related to defect 8917
+     * The expected result is slightly different because the data has a
+     * NON-empty whitespace string, which will NOT be treated as null
+     * see also defect 15117
+     */
+    @Test public void testDefect11789() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager_8917a(metadata);
+
+        String expected = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "    <OptionalCatalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </OptionalCatalog>\r\n" +  //$NON-NLS-1$
+            "    <OptionalCatalog2>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </OptionalCatalog2>\r\n" +  //$NON-NLS-1$
+            "    <OptionalCatalog3>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </OptionalCatalog3>\r\n" +  //$NON-NLS-1$
+            "    <Catalog4>\r\n" +  //$NON-NLS-1$
+            "        <OptionalItems>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </OptionalItems>\r\n" +  //$NON-NLS-1$
+            "    </Catalog4>\r\n" +  //$NON-NLS-1$
+            "    <Catalog5>\r\n" +  //$NON-NLS-1$
+            "        <OptionalItems>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <FixedName>Nugent</FixedName>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </OptionalItems>\r\n" +  //$NON-NLS-1$
+            "    </Catalog5>\r\n" +              //$NON-NLS-1$
+            "    <Catalog6/>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$        
+        
+        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+            expected, metadata, dataMgr);        
+    } 
+
+    /** 
+     * Related to defect 8917 - the result should be the same as 
+     * testDefect8917
+     */
+    @Test public void testDefect11789b() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager_8917b(metadata);
+
+        helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
+            EXPECTED_DOC_DEFECT_8917_AND_11789, metadata, dataMgr);        
+    }    
+    
+    @Test public void testDefect9446() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item XXXXX=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <XXXXX/>\r\n" +  //$NON-NLS-1$
+            "                <XXXXX>5</XXXXX>\r\n" +           //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+//        helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
+        helpTestProcess("SELECT * FROM xmltest.doc_9446", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+
+    @Test public void testDefect9446_2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager_8917(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items/>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc_9446 WHERE Catalogs.Catalog.Items.Item.XXXXX = '001'", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+
+    @Test public void testDefect_9530() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<mm:Catalogs xmlns:mm=\"http://www.duh.org/duh\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+            "                     ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </mm:Item>\r\n" +  //$NON-NLS-1$
+            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+            "                     ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +             //$NON-NLS-1$
+            "            </mm:Item>\r\n" +  //$NON-NLS-1$
+            "            <mm:Item xmlns:mm2=\"http://www.duh3.org/duh3\" xmlns:mm=\"http://www.duh2.org/duh2\"\r\n" + //$NON-NLS-1$
+            "                     ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +           //$NON-NLS-1$
+            "            </mm:Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</mm:Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc_9530", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr);        
+    } 
+
+    @Test public void testSubqueryInXMLQueryCriteria() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"002\">\r\n" + 
+//            "                <Name>Screwdriver</Name>\r\n" + 
+//            "                <Quantity>100</Quantity>\r\n" + 
+//            "            </Item>\r\n" + 
+//            "            <Item ItemID=\"003\">\r\n" + 
+//            "                <Name>Goat</Name>\r\n" + 
+//            "                <Quantity>4</Quantity>\r\n" + 
+//            "            </Item>\r\n" + 
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryInXMLQueryCriteria2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"001\">\r\n" + 
+//            "                <Name>Lamp</Name>\r\n" + 
+//            "                <Quantity>5</Quantity>\r\n" + 
+//            "            </Item>\r\n" + 
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryInXMLQueryCriteria3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"001\">\r\n" + 
+//            "                <Name>Lamp</Name>\r\n" + 
+//            "                <Quantity>5</Quantity>\r\n" + 
+//            "            </Item>\r\n" + 
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE NOT (ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    public void XXXtestSubqueryInXMLQueryCriteria4() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE EXISTS (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedSubquery() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"001\">\r\n" + 
+//            "                <Name>Lamp</Name>\r\n" + 
+//            "                <Quantity>5</Quantity>\r\n" + 
+//            "            </Item>\r\n" + 
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') ) )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"001\">\r\n" + 
+//            "                <Name>Lamp</Name>\r\n" + 
+//            "                <Quantity>5</Quantity>\r\n" +
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"51\">\r\n" +
+//            "                        <Name>Chucky</Name>\r\n" +
+//            "                        <Zip>11111</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"52\">\r\n" +
+//            "                        <Name>Biff's Stuff</Name>\r\n" +
+//            "                        <Zip>22222</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"53\">\r\n" +
+//            "                        <Name>AAAA</Name>\r\n" +
+//            "                        <Zip>33333</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID > ANY (SELECT itemNum FROM stock.items WHERE itemNum IN ('001','002') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }  
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass2() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID > ANY (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('53','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    } 
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"002\">\r\n" + 
+//            "                <Name>Screwdriver</Name>\r\n" + 
+//            "                <Quantity>100</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"54\">\r\n" +
+//            "                        <Name>Nugent Co.</Name>\r\n" +
+//            "                        <Zip>44444</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"55\">\r\n" +
+//            "                        <Name>Zeta</Name>\r\n" +
+//            "                        <Zip>55555</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+//            "            <Item ItemID=\"003\">\r\n" + 
+//            "                <Name>Goat</Name>\r\n" + 
+//            "                <Quantity>4</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID < ALL (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"002\">\r\n" + 
+//            "                <Name>Screwdriver</Name>\r\n" + 
+//            "                <Quantity>100</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"54\">\r\n" +
+//            "                        <Name>Nugent Co.</Name>\r\n" +
+//            "                        <Zip>44444</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"55\">\r\n" +
+//            "                        <Name>Zeta</Name>\r\n" +
+//            "                        <Zip>55555</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+//            "            <Item ItemID=\"003\">\r\n" + 
+//            "                <Name>Goat</Name>\r\n" + 
+//            "                <Quantity>4</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID IN (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+
+    @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass4() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"54\">\r\n" +
+//            "                        <Name>Nugent Co.</Name>\r\n" +
+//            "                        <Zip>44444</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"55\">\r\n" +
+//            "                        <Name>Zeta</Name>\r\n" +
+//            "                        <Zip>55555</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers/>\r\n" + //$NON-NLS-1$
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE context(SupplierID, SupplierID) < SOME (SELECT supplierNum FROM stock.suppliers WHERE supplierNum IN ('52','54') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testCritNestedMappingClass() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+//            "            <Item ItemID=\"002\">\r\n" + 
+//            "                <Name>Screwdriver</Name>\r\n" + 
+//            "                <Quantity>100</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"54\">\r\n" +
+//            "                        <Name>Nugent Co.</Name>\r\n" +
+//            "                        <Zip>44444</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"55\">\r\n" +
+//            "                        <Name>Zeta</Name>\r\n" +
+//            "                        <Zip>55555</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+//            "            <Item ItemID=\"003\">\r\n" + 
+//            "                <Name>Goat</Name>\r\n" + 
+//            "                <Quantity>4</Quantity>\r\n" + 
+//            "                <Suppliers>\r\n" +
+//            "                    <Supplier SupplierID=\"56\">\r\n" +
+//            "                        <Name>Microsoft</Name>\r\n" +
+//            "                        <Zip>66666</Zip>\r\n" +
+//            "                    </Supplier>\r\n" +
+//            "                </Suppliers>\r\n" +
+//            "            </Item>\r\n" + 
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE SupplierID = '52'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testDefect_9893() throws Exception{
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Root>\r\n" + //$NON-NLS-1$
+            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
+            "</Root>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc9893", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr); 
+    }
+
+    @Test public void testDefect_9893_2() throws Exception{
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Root>\r\n" + //$NON-NLS-1$
+            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
+            "</Root>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemName FROM xmltest.doc9893", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr); 
+    }
+
+    @Test public void testDefect_9893_3() throws Exception{
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Root>\r\n" + //$NON-NLS-1$
+            "    <ItemName>Lamp</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Screwdriver</ItemName>\r\n" +  //$NON-NLS-1$
+            "    <ItemName>Goat</ItemName>\r\n" +  //$NON-NLS-1$
+            "</Root>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemName.* FROM xmltest.doc9893", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr); 
+    }
+
+    @Test public void testDefect_9893_4() throws Exception{
+        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item/>\r\n" +  //$NON-NLS-1$
+            "            <Item/>\r\n" +  //$NON-NLS-1$
+            "            <Item/>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        final boolean SHOULD_SUCCEED = true;
+        helpTestProcess("SELECT Item FROM xmltest.doc9c", //$NON-NLS-1$
+            expectedDoc, metadata, dataMgr, null);       
+    }
+
+    @Test public void testNestedWithStoredQueryInMappingClass() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc18", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /** homegenous, simple array elements */
+    @Test public void testWithSOAPEncoding1() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataSoap1();
+        FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, false);
+         
+        String expectedDoc = 
+             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+             "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
+             "    <ORG:TaxReport>\r\n" +  //$NON-NLS-1$
+             "        <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //$NON-NLS-1$
+             "                          xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n" + //$NON-NLS-1$
+             "                          xsi:type=\"ORG:ArrayOfTaxIDType\"\r\n" + //$NON-NLS-1$
+             " SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" +  //$NON-NLS-1$
+             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
+             "                <ID>1</ID>\r\n" +  //$NON-NLS-1$
+             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
+             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
+             "                <ID>2</ID>\r\n" +  //$NON-NLS-1$
+             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
+             "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" +  //$NON-NLS-1$
+             "                <ID>3</ID>\r\n" +  //$NON-NLS-1$
+             "            </ORG:TaxID>\r\n" +  //$NON-NLS-1$
+             "        </ORG:ArrayOfTaxID>\r\n" +  //$NON-NLS-1$
+             "    </ORG:TaxReport>\r\n" +  //$NON-NLS-1$
+             "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+     
+    /**
+     * if no data is contained in the soap elements
+     * (e.g. ORG:ArrayOfTaxID) and the schema allows it, eliminate the 
+     * whole fragment
+     */        
+    @Test public void testWithSOAPEncodingNoRows() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataSoap1();
+        FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, true);
+         
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<ORG:TaxReports xmlns:ORG=\"http://www.mm.org/dummy\">\r\n" + //$NON-NLS-1$
+            "    <ORG:TaxReport/>\r\n" +  //$NON-NLS-1$
+//            "    <ORG:TaxReport>\r\n" + 
+//            "        <ORG:ArrayOfTaxID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xsi:type=\"ORG:ArrayOfTaxIDType\" SOAP-ENC:arrayType=\"ORG:TaxIDType[]\">\r\n" + 
+//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
+//            "                <ID>1</ID>\r\n" + 
+//            "            </ORG:TaxID>\r\n" + 
+//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
+//            "                <ID>2</ID>\r\n" + 
+//            "            </ORG:TaxID>\r\n" + 
+//            "            <ORG:TaxID xsi:type=\"ORG:TaxIDType\">\r\n" + 
+//            "                <ID>3</ID>\r\n" + 
+//            "            </ORG:TaxID>\r\n" + 
+//            "        </ORG:ArrayOfTaxID>\r\n" + 
+//            "    </ORG:TaxReport>\r\n" + 
+            "</ORG:TaxReports>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.docSoap", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }  
+    
+    @Test public void testDefect12260() throws Exception{
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <numSuppliers>4</numSuppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <numSuppliers>3</numSuppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <numSuppliers>1</numSuppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+
+        // Set up capabilities to duplicate defect
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
+        caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        caps.setFunctionSupport("convert", true); //$NON-NLS-1$
+        CapabilitiesFinder capFinder = new DefaultCapabilitiesFinder(caps); 
+        
+        helpTestProcess("SELECT * FROM xmltest.doc12260", metadata, dataMgr, null, capFinder, expectedDoc); //$NON-NLS-1$
+    }
+    
+    @Test public void testDefect8373() throws Exception{
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+         
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc8373", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testDefect8373a() throws Exception{
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+         
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc8373a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testDefect8373b() throws Exception{
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
+         
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity/>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+
+        helpTestProcess("SELECT * FROM xmltest.doc8373b", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    @Test public void testDefect13617() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager13617(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item>\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }       
+
+    @Test public void testDefect13617a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager13617(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"004\"/>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT ItemID, Item.Name FROM xmltest.doc13617", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }      
+
+    /**
+     * Tests that non-zero length whitespace string will be treated like
+     * normal data 
+     * @throws Exception
+     * @since 4.2
+     */
+    @Test public void testDefect14905() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager14905(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\" \">\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"  \">\r\n" +  //$NON-NLS-1$
+            "                <Name>  </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\" \">\r\n" +  //$NON-NLS-1$
+            "                <Name> </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    @Test public void testTextUnnormalizedDefect15117() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager15117(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name> Lamp </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>  Screw  driver  </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name> Goat </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    @Test public void testTextUnnormalizedDefect15117a() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager15117a(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>\t \n&#xD;</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>  &gt;Screw&lt; \n driver  &amp;</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name> &gt;&gt;&#xD;Goat </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }      
+    
+    @Test public void testRecursiveGroupDoc() throws Exception {
+
+        FakeMetadataFacade metadata = exampleMetadata2();
+        FakeDataManager dataMgr = exampleXQTDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<group>\r\n" + //$NON-NLS-1$
+            "    <ID>2</ID>\r\n" +  //$NON-NLS-1$
+            "    <code>-1</code>\r\n" +  //$NON-NLS-1$
+            "    <supervisor>\r\n" +  //$NON-NLS-1$
+            "        <ID>4</ID>\r\n" +  //$NON-NLS-1$
+            "        <code>1</code>\r\n" +  //$NON-NLS-1$
+            "        <group>\r\n" +  //$NON-NLS-1$
+            "            <ID>6</ID>\r\n" +  //$NON-NLS-1$
+            "            <code>3</code>\r\n" +  //$NON-NLS-1$
+            "            <supervisor>\r\n" +  //$NON-NLS-1$
+            "                <ID>8</ID>\r\n" +  //$NON-NLS-1$
+            "                <code>5</code>\r\n" +  //$NON-NLS-1$
+            "                <group>\r\n" +  //$NON-NLS-1$
+            "                    <ID>10</ID>\r\n" +  //$NON-NLS-1$
+            "                    <code>7</code>\r\n" +  //$NON-NLS-1$
+            "                    <supervisor>\r\n" +  //$NON-NLS-1$
+            "                        <ID>12</ID>\r\n" +  //$NON-NLS-1$
+            "                        <code>9</code>\r\n" +  //$NON-NLS-1$
+            "                    </supervisor>\r\n" +  //$NON-NLS-1$
+            "                </group>\r\n" +  //$NON-NLS-1$
+            "            </supervisor>\r\n" +  //$NON-NLS-1$
+            "        </group>\r\n" +  //$NON-NLS-1$
+            "    </supervisor>\r\n" +  //$NON-NLS-1$
+            "</group>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xqttest.groupDoc WHERE pseudoID = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testCase2951MaxRows() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    /** test rowlimitexception() doesn't throw exception is rowlimit isn't passed */
+    @Test public void testDefect19173RowLimitException() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 4", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /** test criteria can be written backwards */
+    @Test public void testDefect19173RowLimitExceptionBackwardsCriteria() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+            "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE 4 = rowlimitexception(supplier)", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+    
+    @Test public void testCase2951MaxRows2() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /** test processing exception is thrown if row limit is passed */
+    @Test public void testDefect19173RowLimitException2() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    /** Two row limits on the same mapping class should be harmless as long as the row limits are identical. */
+    @Test public void testCase2951MaxRows2a() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierid) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /** test processing exception is thrown if row limit is passed */
+    @Test public void testDefect19173RowLimitException2a() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierid) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    /** compound criteria */
+    @Test public void testCase2951MaxRows3() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID='002' AND rowlimit(supplier) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /** compound criteria */
+    @Test public void testDefect19173RowLimitException3() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID='002' AND rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }     
+    
+    @Test public void testCase2951MaxRows4() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(item) = 2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }     
+
+    @Test public void testCase2951AndDefect19173MixTwoFunctions() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitException(item) = 6", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }     
+    
+    /** arg to rowlimit function isn't in the scope of any mapping class */
+    @Test public void testCase2951MaxRowsFails() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }     
+
+    /** two conflicting row limits on the same mapping class */
+    @Test public void testCase2951MaxRowsFails2() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** arg to rowlimitexception function isn't in the scope of any mapping class */
+    @Test public void testDefect19173RowLimitExceptionFails() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }     
+
+    /** two conflicting rowlimitexceptions on the same mapping class */
+    @Test public void testDefect19173RowLimitExceptionFails2() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    /** two conflicting rowlimit and rowlimitexceptions on the same mapping class fails planning */
+    @Test public void testDefect19173RowLimitAndRowLimitExceptionMixFails2() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    /** try rowlimit criteria written the reverse way */
+    @Test public void testCase2951MaxRows5() throws Exception {
+        
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNested(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "                <Suppliers>\r\n" + //$NON-NLS-1$
+            "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+            "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+            "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+            "                    </Supplier>\r\n" + //$NON-NLS-1$
+            "                </Suppliers>\r\n" + //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.doc8 WHERE 2 = rowlimit(supplier)", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    } 
+    
+    
+    @Test public void testNormalizationCollapse() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("SELECT * FROM xmltest.normDoc1", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    @Test public void testNormalizationReplace() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>   Screwdriver       </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>         Goat  </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Flux     Capacitor</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Milkshake</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
+            "                <Name> Feta               Matrix       </Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+ 
+        helpTestProcess("SELECT * FROM xmltest.normDoc2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    @Test public void testNormalizationPreserve() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManagerNormalization2(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name xsi:nil=\"true\"/>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>My Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>My Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"004\">\r\n" +  //$NON-NLS-1$
+            "                <Name>My Flux Capacitor</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>2</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "            <StatusUnknown ItemID=\"005\">\r\n" +  //$NON-NLS-1$
+            "                <Name>My Milkshake</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>88</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </StatusUnknown>\r\n" +  //$NON-NLS-1$
+            "            <DiscontinuedItem ItemID=\"006\">\r\n" +  //$NON-NLS-1$
+            "                <Name>My Feta Matrix</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>0</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </DiscontinuedItem>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+    
+        helpTestProcess("SELECT * FROM xmltest.normDoc3", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * Deluxe example
+     */
+    private FakeDataManager exampleDataManagerNormalization(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", " \n Screwdriver \t    \r", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "       \t\rGoat \n", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "004", "Flux \t\r\n Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "006", " Feta               Matrix       ", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }   
+    private FakeDataManager exampleDataManagerNormalization2(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+            List elementIDs = metadata.getElementIDsInGroupID(groupID);
+            List elementSymbols = createElements(elementIDs);
+
+            dataMgr.registerTuples(
+                groupID,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "My Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "My Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "004", "My Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "005", "My Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "006", "My Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }   
+    
+    private static MappingNode createXMLPlanNormalization(String normMode) {
+
+        MappingDocument doc = new MappingDocument(true);
+        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+
+        MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+        MappingElement items = cat.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+
+        //choice node, non-visual, so it has no name        
+        MappingChoiceNode choice = items.addChoiceNode(new MappingChoiceNode());
+        choice.setSource("xmltest.group.items"); //$NON-NLS-1$
+        choice.setMaxOccurrs(-1);
+        MappingCriteriaNode crit = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'okay'", false)); //$NON-NLS-1$
+        MappingElement item = crit.addChildElement(new MappingElement("Item")); //$NON-NLS-1$ 
+        item.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        item.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setNormalizeText(normMode) 
+            .setNillable(true);
+        item.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+        
+        MappingCriteriaNode crit2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'discontinued'", false)); //$NON-NLS-1$ 
+        MappingElement discontinuedItem = crit2.addChildElement(new MappingElement("DiscontinuedItem")); //$NON-NLS-1$ 
+        discontinuedItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        discontinuedItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setNormalizeText(normMode) 
+            .setNillable(true);
+        discontinuedItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$
+        
+        MappingCriteriaNode crit3 = choice.addCriteriaNode(new MappingCriteriaNode());      
+        MappingElement unknownItem = crit3.addChildElement(new MappingElement("StatusUnknown")); //$NON-NLS-1$
+        unknownItem.addAttribute(new MappingAttribute("ItemID", "xmltest.group.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+        unknownItem.addChildElement(new MappingElement("Name", "xmltest.group.items.itemName")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setNormalizeText(normMode) 
+            .setNillable(true);
+        unknownItem.addChildElement(new MappingElement("Quantity", "xmltest.group.items.itemQuantity")) //$NON-NLS-1$ //$NON-NLS-2$
+            .setDefaultValue("0"); //$NON-NLS-1$        
+        
+        MappingCriteriaNode notIncludedSibling = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$ 
+        notIncludedSibling.setExclude(true);
+
+        MappingCriteriaNode notIncludedSibling2 = choice.addCriteriaNode(new MappingCriteriaNode("xmltest.group.items.itemStatus = 'something'", false)); //$NON-NLS-1$ 
+        notIncludedSibling2.setExclude(true);
+        return doc;        
+    }
+
+    static FakeDataManager exampleDataManagerCase3225(FakeMetadataFacade metadata) {
+        FakeDataManager dataMgr = new FakeDataManager();
+    
+        try { 
+            // Group stock.items
+            FakeMetadataObject groupItems = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
+
+            // Group stock.supplier
+            FakeMetadataObject groupSuppliers = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+
+            // Group stock.orders
+            FakeMetadataObject groupOrders = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
+
+            // Group stock.employees
+            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
+            
+            // Group stock.item_supplier
+            FakeMetadataObject groupItemSupplier = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
+
+            // Items
+            List elementIDs = metadata.getElementIDsInGroupID(groupItems);
+            List elementSymbols = createElements(elementIDs);
+
+            // Supplier
+            elementIDs = metadata.getElementIDsInGroupID(groupSuppliers);
+            List supplierElementSymbols = createElements(elementIDs);
+
+            // Orders
+            elementIDs = metadata.getElementIDsInGroupID(groupOrders);
+            List ordersElementSymbols = createElements(elementIDs);
+
+            // Employees
+            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
+            List employeesElementSymbols = createElements(elementIDs);
+            
+            // Item_supplier
+            elementIDs = metadata.getElementIDsInGroupID(groupItemSupplier);
+            List itemSupplierElementSymbols = createElements(elementIDs);
+        
+            dataMgr.registerTuples(
+                groupItems,
+                elementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupItemSupplier,
+                itemSupplierElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+                    } );    
+
+
+            dataMgr.registerTuples(
+                groupSuppliers,
+                supplierElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupOrders,
+                ordersElementSymbols,
+                
+                new List[] { 
+                    Arrays.asList( new Object[] { "1", "001", "51", "2/13/05", new Integer(2), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "2", "001", "52", "3/13/05", new Integer(1), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "3", "002", "53", "4/13/05", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "4", "002", "56", "5/13/05", new Integer(1), "cancelled" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    Arrays.asList( new Object[] { "5", "003", "56", "6/13/05", new Integer(800), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                    } );    
+
+            dataMgr.registerTuples(
+                groupEmployees,
+                employeesElementSymbols,
+               
+                new List[] { 
+                    Arrays.asList( new Object[] { "1001", "51", "001", "1004", "Albert", "Pujols" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1002", "51", "001", "1004", "Jim", "Edmunds" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1003", "54", "002", "1004", "David", "Eckstein" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1004", null, null, "1009", "Tony", "LaRussa" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+                    Arrays.asList( new Object[] { "1005", "56", "001", "1007", "Derrek", "Lee" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1006", "56", "003", "1007", "Corey", "Patterson" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1007", null, null, "1010", "Dusty", "Baker" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+                    Arrays.asList( new Object[] { "1008", "56", "002", "1007", "Carlos", "Zambrano" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+                    Arrays.asList( new Object[] { "1009", null, null, null, "Bill", "DeWitt" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+                    Arrays.asList( new Object[] { "1010", null, null, null, "Some", "Guy" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+                    } );             
+            
+        } catch(Throwable e) { 
+            e.printStackTrace();
+            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        }
+        
+        return dataMgr;
+    }      
+    
+    /**
+     * Test of doc model w/o criteria, just as a baseline 
+     * @throws Exception
+     */
+    @Test public void testCase3225() throws Exception {
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        String expectedDoc = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" + //$NON-NLS-1$
+        "        <Items>\r\n" + //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" + //$NON-NLS-1$
+        "            <Item ItemID=\"002\">\r\n" + //$NON-NLS-1$
+        "                <Name>Screwdriver</Name>\r\n" + //$NON-NLS-1$
+        "                <Quantity>100</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1003\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>5/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>cancelled</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1008\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" + //$NON-NLS-1$
+        "            <Item ItemID=\"003\">\r\n" + //$NON-NLS-1$
+        "                <Name>Goat</Name>\r\n" + //$NON-NLS-1$
+        "                <Quantity>4</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>6/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>800</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1006\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" + //$NON-NLS-1$
+        "        </Items>\r\n" + //$NON-NLS-1$
+        "    </Catalog>\r\n" + //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("select * from xmltest.itemsdoc", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+
+    /**
+     * For ESpace case 3225 tests, with criteria
+     * "... where employee. at supervisorID='1004' and order.orderquantity > 1"
+     */
+    private static final String CASE_3225_WITH_CRITERIA_EXPECTED_DOC = 
+        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+        "<Catalogs>\r\n" + //$NON-NLS-1$
+        "    <Catalog>\r\n" + //$NON-NLS-1$
+        "        <Items>\r\n" + //$NON-NLS-1$
+        "            <Item ItemID=\"001\">\r\n" + //$NON-NLS-1$
+        "                <Name>Lamp</Name>\r\n" + //$NON-NLS-1$
+        "                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+        "                <Suppliers>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>2/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>2</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1001\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1002\" SupervisorID=\"1004\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders>\r\n" + //$NON-NLS-1$
+        "                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+        "                                <OrderDate>3/13/05</OrderDate>\r\n" + //$NON-NLS-1$
+        "                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+        "                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+        "                            </Order>\r\n" + //$NON-NLS-1$
+        "                        </Orders>\r\n" + //$NON-NLS-1$
+        "                        <Employees/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+        "                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees/>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+        "                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+        "                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+        "                        <Orders/>\r\n" + //$NON-NLS-1$
+        "                        <Employees>\r\n" + //$NON-NLS-1$
+        "                            <Employee EmployeeID=\"1005\" SupervisorID=\"1007\">\r\n" + //$NON-NLS-1$
+        "                                <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+        "                                <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+        "                            </Employee>\r\n" + //$NON-NLS-1$
+        "                        </Employees>\r\n" + //$NON-NLS-1$
+        "                    </Supplier>\r\n" + //$NON-NLS-1$
+        "                </Suppliers>\r\n" + //$NON-NLS-1$
+        "            </Item>\r\n" + //$NON-NLS-1$
+        "        </Items>\r\n" + //$NON-NLS-1$
+        "    </Catalog>\r\n" + //$NON-NLS-1$
+        "</Catalogs>\r\n\r\n"; //$NON-NLS-1$    
+
+	private static String EXPECTED_ORDERED_DOC9A = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+	"<Catalogs>\r\n" + //$NON-NLS-1$
+	"    <Catalog>\r\n" +  //$NON-NLS-1$
+	"        <Items>\r\n" +  //$NON-NLS-1$
+	"            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+	"                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+	"                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+	"                <Suppliers>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders>\r\n" + //$NON-NLS-1$
+	"                            <Order OrderID=\"3\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>02/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>12</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" +  //$NON-NLS-1$
+	"                            <Order OrderID=\"4\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>05/31/02</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>9</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                                <OrderStatus>processing</OrderStatus>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" + //$NON-NLS-1$
+	"                        </Orders>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                </Suppliers>\r\n" + //$NON-NLS-1$
+	"            </Item>\r\n" +              //$NON-NLS-1$
+	"            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+	"                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+	"                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+	"                <Suppliers>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"54\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Nugent Co.</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>44444</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders>\r\n" + //$NON-NLS-1$
+	"                            <Order OrderID=\"1\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>10/23/01</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>5</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" + //$NON-NLS-1$
+	"                        </Orders>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"55\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Zeta</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>55555</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders/>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders>\r\n" + //$NON-NLS-1$
+	"                            <Order OrderID=\"5\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>06/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" +  //$NON-NLS-1$
+	"                            <Order OrderID=\"6\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>07/01/02</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>1</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" + //$NON-NLS-1$
+	"                        </Orders>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                </Suppliers>\r\n" + //$NON-NLS-1$
+	"            </Item>\r\n" +  //$NON-NLS-1$
+	"            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+	"                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+	"                <Quantity>5</Quantity>\r\n" + //$NON-NLS-1$
+	"                <Suppliers>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"51\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Chucky</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>11111</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders/>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"52\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Biff's Stuff</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>22222</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders>\r\n" + //$NON-NLS-1$
+	"                            <Order OrderID=\"2\">\r\n" + //$NON-NLS-1$
+	"                                <OrderDate>12/31/01</OrderDate>\r\n" + //$NON-NLS-1$
+	"                                <OrderQuantity>87</OrderQuantity>\r\n" + //$NON-NLS-1$
+	"                                <OrderStatus>complete</OrderStatus>\r\n" + //$NON-NLS-1$
+	"                            </Order>\r\n" + //$NON-NLS-1$
+	"                        </Orders>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"53\">\r\n" + //$NON-NLS-1$
+	"                        <Name>AAAA</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>33333</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders/>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                    <Supplier SupplierID=\"56\">\r\n" + //$NON-NLS-1$
+	"                        <Name>Microsoft</Name>\r\n" + //$NON-NLS-1$
+	"                        <Zip>66666</Zip>\r\n" + //$NON-NLS-1$
+	"                        <Orders/>\r\n" + //$NON-NLS-1$
+	"                    </Supplier>\r\n" + //$NON-NLS-1$
+	"                </Suppliers>\r\n" + //$NON-NLS-1$
+	"            </Item>\r\n" +              //$NON-NLS-1$
+	"        </Items>\r\n" +  //$NON-NLS-1$
+	"    </Catalog>\r\n" +  //$NON-NLS-1$
+	"</Catalogs>\r\n\r\n";
+    
+    /**
+     * Test of query with criteria written one way.  This test is paired up 
+     * with {@link #testCase3225WithCriteriaReversed()}; both tests have the same
+     * expected results and are identical queries except their compound criteria are 
+     * written in reverse order relative to each other.  What Alan Tetrault found at
+     * ESpace is that this changes actual results, which it shouldn't.  The likely
+     * culprit is the algorithm to apply criteria to the implied context mapping class.
+     * That is, the criteria is on nodes in the scope of two nested mapping classes
+     * (the ones for orders and employees), but the implied context mapping class of both
+     * of them is the root mapping class (for items).
+     * 
+     * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
+     * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
+     * the combined criteria should limit returned items to item 001.
+     * @throws Exception
+     */
+    @Test public void testCase3225WithCriteria() throws Exception {
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        helpTestProcess("select * from xmltest.itemsdoc where employee. at supervisorID='1004' and order.orderquantity > 1", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
+    }    
+
+    /**
+     * Test of query with criteria written the other way.  This test is paired up 
+     * with {@link #testCase3225WithCriteria()}; both tests have the same
+     * expected results and are identical queries except their compound criteria are 
+     * written in reverse order relative to each other.  What Alan Tetrault found at
+     * ESpace is that this changes actual results, which it shouldn't.  The likely
+     * culprit is the algorithm to apply criteria to the implied context mapping class.
+     * That is, the criteria is on nodes in the scope of two nested mapping classes
+     * (the ones for orders and employees), but the implied context mapping class of both
+     * of them is the root mapping class (for items).
+     * 
+     * The criteria "@supervisorID='1004'" should limit the returned items to items 001 and 002,
+     * the criteria "order.orderquantity > 1" should limit the returned items to 001 and 003, so
+     * the combined criteria should limit returned items to item 001.
+     * @throws Exception
+     */
+    @Test public void testCase3225WithCriteriaReversed() throws Exception {
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        helpTestProcess("select * from xmltest.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004'", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
+    }      
+
+    /**
+     * Test the criteria from previous test, plus additional criteria explicitly
+     * on the context mapping class (in this case, the root "items" mapping class)
+     * to make sure all of the criteria is processed correctly. 
+     * @throws Exception
+     */
+    @Test public void testCase3225WithEmptyDocCriteria() throws Exception {
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs>\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" + //$NON-NLS-1$
+            "        <Items/>\r\n" + //$NON-NLS-1$
+            "    </Catalog>\r\n" + //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("select * from xmltest.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004' and item. at itemid='002'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }      
+    
+    /**
+     * This just tests selecting * from the document, nothing fancy 
+     * @throws Exception
+     * @since 4.3
+     */
+    @Test public void testBaseballPlayersDoc() throws Exception {
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1007\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Dusty</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>Baker</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1010\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Some</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>Guy</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("select * from xmltest.playersDoc", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+        
+    }
+    
+    /**
+     * This one seems to work fine - criteria mapping class is 
+     * managers while implied context mapping class is players. 
+     * Expected result is same as previous test.
+     * @throws Exception
+     * @since 4.3
+     */
+    @Test public void testBaseballPlayersDocCriteria() throws Exception {
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("select * from xmltest.playersDoc where manager. at managerid = '1004'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+        
+    }     
+    
+    /**
+     * This also seems to work fine.  The context mapping class is the 
+     * middle one (managers). 
+     * @throws Exception
+     * @since 4.3
+     */
+    @Test public void testBaseballPlayersDocContextCriteria() throws Exception {
+        
+        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+            "         </Owner>\r\n" + //$NON-NLS-1$
+            "      </Manager>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
+            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+            "   </Player>\r\n" + //$NON-NLS-1$
+            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
+        
+        helpTestProcess("select * from xmltest.playersDoc where context(manager, owner. at ownerid) = '1009'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+        
+    }    
+    
+    /**
+     * Ensures that temp tables are still visible when processing criteria
+     */
+    @Test public void testProcedureAndXML() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        helpTestProcess("call xmltest.vsp1()", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
+    /**
+     * When a element with source node is specied, it can be unbouned or bounded. In the case
+     * of bounded, but result set is returning more results then it should fail.
+     */
+    public void defer_testMinMaxOnSourceNode() throws Exception {
+        FakeMetadataFacade metadata = exampleMetadataCached();
+        FakeDataManager dataMgr = exampleDataManager(metadata);
+        String expectedDoc = 
+            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
+            "    <Catalog>\r\n" +  //$NON-NLS-1$
+            "        <Items>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
+            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
+            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
+            "            </Item>\r\n" +  //$NON-NLS-1$
+            "        </Items>\r\n" +  //$NON-NLS-1$
+            "    </Catalog>\r\n" +  //$NON-NLS-1$
+            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
+        
+        try {
+            helpTestProcess("SELECT * FROM xmltest.docBounded", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+            fail("should have failed the document restrictions."); //$NON-NLS-1$
+        } catch (TeiidProcessingException e) {
+            // pass
+        }
+    }
+
+}

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

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

Deleted: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/validator/TestValidator.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,2046 +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.validator;
-
-import static org.junit.Assert.*;
-
-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.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
-import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.parser.QueryParser;
-import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.lang.ProcedureContainer;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-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;
-
- at SuppressWarnings("nls")
-public class TestValidator {
-
-    public static Map getStoredProcedureExternalMetadata(GroupSymbol virtualProc, QueryMetadataInterface metadata)
-    throws QueryMetadataException, TeiidComponentException {
-
-        Map externalMetadata = new HashMap();
-
-        StoredProcedureInfo info = metadata.getStoredProcedureInfoForProcedure(virtualProc.getName());
-        if(info!=null) {
-            virtualProc.setMetadataID(info.getProcedureID());
-
-            // List of ElementSymbols - Map Values
-            List paramList = info.getParameters();
-            Iterator iter = paramList.iterator();
-            // Create Symbol List from parameter list
-            List symbolList = new ArrayList();
-            while(iter.hasNext()) {
-                SPParameter param = (SPParameter) iter.next();
-                if(param.getParameterType() == ParameterInfo.IN ||
-                    param.getParameterType() == ParameterInfo.INOUT) {
-                    // Create Element Symbol
-                    ElementSymbol eSymbol = new ElementSymbol(param.getName());
-                    eSymbol.setMetadataID(param);
-                    eSymbol.setType(param.getClassType());
-                    symbolList.add(eSymbol);
-                }
-            }
-            // Create external Metadata Map
-            externalMetadata = new HashMap();
-            externalMetadata.put(virtualProc, symbolList);
-        }
-
-        return externalMetadata;
-    }
-
-    public static FakeMetadataFacade exampleMetadata() {
-        // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject vModelObj2 = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        elemObj1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elemObj2.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
-        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3); //$NON-NLS-1$
-        elemObj3.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
-    
-        FakeMetadataObject group2Obj = FakeMetadataFactory.createPhysicalGroup("test.group2", modelObj);         //$NON-NLS-1$
-        FakeMetadataObject elemObj2_0 = FakeMetadataFactory.createElement("test.group2.e0", group2Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        elemObj2_0.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
-        FakeMetadataObject elemObj2_1 = FakeMetadataFactory.createElement("test.group2.e1", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2_2 = FakeMetadataFactory.createElement("test.group2.e2", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elemObj2_2.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
-    
-        FakeMetadataObject group3Obj = FakeMetadataFactory.createPhysicalGroup("test.group3", modelObj);         //$NON-NLS-1$
-        group3Obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE); 
-        FakeMetadataObject elemObj3_0 = FakeMetadataFactory.createElement("test.group3.e0", group3Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj3_1 = FakeMetadataFactory.createElement("test.group3.e1", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj3_2 = FakeMetadataFactory.createElement("test.group3.e2", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-    
-        // Create virtual group & elements.
-        QueryNode vNode = new QueryNode("vTest.vGroup", "SELECT * FROM test.group WHERE e2 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vGroup = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj2, vNode);         //$NON-NLS-1$
-        List vGroupE = FakeMetadataFactory.createElements(vGroup, 
-            new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-        QueryNode vNode2 = new QueryNode("vTest.vMap", "SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vGroup2 = FakeMetadataFactory.createVirtualGroup("vTest.vMap", vModelObj2, vNode2);         //$NON-NLS-1$
-        List vGroupE2 = FakeMetadataFactory.createElements(vGroup2, 
-            new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        ((FakeMetadataObject)vGroupE2.get(0)).putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(1)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(2)).putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(3)).putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
-    
-        // Create virtual documents
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement complexRoot = doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
-        
-        MappingElement sourceNode = complexRoot.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
-        sourceNode.setSource("test.group"); //$NON-NLS-1$
-        sourceNode.addChildElement(new MappingElement("a2", "test.group.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-        sourceNode.addChildElement(new MappingElement("b2", "test.group.e2")); //$NON-NLS-1$ //$NON-NLS-2$
-        sourceNode.addChildElement(new MappingElement("c2", "test.group.e3")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-    	FakeMetadataObject docModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("vm1.doc1", docModel, doc); //$NON-NLS-1$
-    	List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "a0", "a0.a1", "a0.a1.a2", "a0.a1.b2", "a0.a1.c2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    		new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-                        
-    	// set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(elemObj3);
-        store.addObject(vGroup);
-        store.addObjects(vGroupE);
-        store.addObject(vGroup2);
-        store.addObjects(vGroupE2);
-        store.addObject(docModel);
-        store.addObject(group2Obj);
-        store.addObject(elemObj2_0);
-        store.addObject(elemObj2_1);
-        store.addObject(elemObj2_2);
-        store.addObject(group3Obj);
-        store.addObject(elemObj3_0);
-        store.addObject(elemObj3_1);
-        store.addObject(elemObj3_2);
-        store.addObject(doc1);
-        store.addObjects(docE1);
-    	return new FakeMetadataFacade(store);
-    }
-	
-    public FakeMetadataFacade exampleMetadata1() {
-        // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
-
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3);         //$NON-NLS-1$
-
-        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        elemObj0.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-
-        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.TRUE);
-        
-        elemObj2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        elemObj2.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-        
-		// set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(elemObj3);
-		return new FakeMetadataFacade(store);
-    }
-
-    /**
-     * Group has element with type object
-     * @return FakeMetadataFacade
-     */
-    public static FakeMetadataFacade exampleMetadata2() {
-        // Create metadata objects
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
-        
-        List elements = FakeMetadataFactory.createElements(groupObj, new String[] {
-            "e0", "e1", "e2", "e3", "e4", "e5" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-        }, new String[] {
-            DataTypeManager.DefaultDataTypes.INTEGER,
-            DataTypeManager.DefaultDataTypes.STRING,
-            DataTypeManager.DefaultDataTypes.OBJECT,
-            DataTypeManager.DefaultDataTypes.BLOB,
-            DataTypeManager.DefaultDataTypes.CLOB,
-            DataTypeManager.DefaultDataTypes.XML,
-        });
-
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObjects(elements);
-        return new FakeMetadataFacade(store);
-    }
-
-    public static FakeMetadataFacade exampleMetadata3() {
-        // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
-
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-
-        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-        elemObj1.putProperty(FakeMetadataObject.Props.AUTO_INCREMENT, Boolean.TRUE);
-        elemObj1.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, "e1:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
-        
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        return new FakeMetadataFacade(store);
-    }
-
-    public static FakeMetadataFacade exampleMetadata4() {
-        // Create metadata objects 
-    	FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test");  //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject vModelObj = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
-        QueryNode vNode = new QueryNode("vTest.vGroup", "SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vGroupObj = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj, vNode); //$NON-NLS-1$
-        FakeMetadataObject vElemObj0 = FakeMetadataFactory.createElement("vTest.vGroup.e0", vGroupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject vElemObj1 = FakeMetadataFactory.createElement("vTest.vGroup.e1", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject vElemObj2 = FakeMetadataFactory.createElement("vTest.vGroup.e2", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        List elements = new ArrayList(1);
-        elements.add(vElemObj0); 
-        elements.add(vElemObj1);
-        FakeMetadataObject vGroupAp1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup.ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
-        
-        QueryNode vNode2 = new QueryNode("vTest.vGroup", "SELECT * FROM vTest.vGroup"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vGroupObj2 = FakeMetadataFactory.createVirtualGroup("vTest.vGroup2", vModelObj, vNode2); //$NON-NLS-1$
-        FakeMetadataObject vElemObj20 = FakeMetadataFactory.createElement("vTest.vGroup2.e0", vGroupObj2, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject vElemObj21 = FakeMetadataFactory.createElement("vTest.vGroup2.e1", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject vElemObj22 = FakeMetadataFactory.createElement("vTest.vGroup2.e2", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elements = new ArrayList(1);
-        elements.add(vElemObj20); 
-        elements.add(vElemObj21);
-        FakeMetadataObject vGroup2Ap1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
-        
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(vModelObj);
-        store.addObject(vGroupObj);
-        store.addObject(vElemObj0);
-        store.addObject(vElemObj1);
-        store.addObject(vElemObj2);
-        store.addObject(vGroupAp1);
-        store.addObject(vGroupObj2);
-        store.addObject(vElemObj20);
-        store.addObject(vElemObj21);
-        store.addObject(vElemObj22);
-        store.addObject(vGroup2Ap1);
-        return new FakeMetadataFacade(store);
-    }
-    
-	// ################################## TEST HELPERS ################################
-
-    static Command helpResolve(String sql, QueryMetadataInterface metadata) { 
-        return helpResolve(sql, metadata, Collections.EMPTY_MAP);
-    }
-    
-	public static Command helpResolve(String sql, QueryMetadataInterface metadata, Map externalMetadata) { 
-		Command command = null;
-		
-		try { 
-			command = QueryParser.getQueryParser().parseCommand(sql);
-			QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-		} catch(Exception e) {
-            throw new TeiidRuntimeException(e);
-		} 
-
-		return command;
-	}
-
-	static ValidatorReport helpValidate(String sql, String[] expectedStringArray, QueryMetadataInterface metadata) {
-        Command command = helpResolve(sql, metadata);
-
-        return helpRunValidator(command, expectedStringArray, metadata);
-    }
-
-    public static ValidatorReport helpRunValidator(Command command, String[] expectedStringArray, QueryMetadataInterface metadata) {
-        try {
-            ValidatorReport report = Validator.validate(command, metadata);
-            
-            examineReport(command, expectedStringArray, report);
-            return report;
-        } catch(TeiidException e) {
-			throw new TeiidRuntimeException(e);
-        }
-	}
-
-	private static void examineReport(Object command,
-			String[] expectedStringArray, ValidatorReport report) {
-		// Get invalid objects from report
-		Collection actualObjs = new ArrayList();
-		report.collectInvalidObjects(actualObjs);
-
-		// Compare expected and actual objects
-		Set<String> expectedStrings = new HashSet(Arrays.asList(expectedStringArray));
-		Set<String> actualStrings = new HashSet<String>();
-		Iterator objIter = actualObjs.iterator();
-		while(objIter.hasNext()) {
-		    LanguageObject obj = (LanguageObject) objIter.next();
-		    actualStrings.add(SQLStringVisitor.getSQLString(obj));
-		}
-
-		if(expectedStrings.size() == 0 && actualStrings.size() > 0) {
-		    fail("Expected no failures but got some: " + report.getFailureMessage()); //$NON-NLS-1$ 
-		} else if(actualStrings.size() == 0 && expectedStrings.size() > 0) {
-		    fail("Expected some failures but got none for sql = " + command); //$NON-NLS-1$
-		} else {
-		    assertEquals("Expected and actual sets of strings are not the same: ", expectedStrings, actualStrings); //$NON-NLS-1$
-		}
-	}
-
-	private void helpValidateProcedure(String procedure, String userUpdateStr, String procedureType) {
-
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
-        try {
-        	validateProcedure(userUpdateStr, metadata);
-        } catch(TeiidException e) {
-            throw new TeiidRuntimeException(e);
-        }
-	}
-
-	private void validateProcedure(String userUpdateStr,
-			QueryMetadataInterface metadata) throws QueryResolverException,
-			QueryMetadataException, TeiidComponentException,
-			QueryValidatorException {
-		ProcedureContainer command = (ProcedureContainer)helpResolve(userUpdateStr, metadata);
-		
-		Command proc = QueryResolver.expandCommand(command, metadata, AnalysisRecord.createNonRecordingRecord());
-		
-		ValidatorReport report = Validator.validate(proc, metadata);
-		if(report.hasItems()) {
-		    throw new QueryValidatorException(report.getFailureMessage());
-		}
-
-		report = Validator.validate(command, metadata);
-		if(report.hasItems()) {
-		    throw new QueryValidatorException(report.getFailureMessage());
-		}
-	}
-	
-	private void helpFailProcedure(String procedure, String userUpdateStr, String procedureType) {
-
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
-
-        try {
-        	validateProcedure(userUpdateStr, metadata);
-        	fail("Expected failures for " + procedure);
-        } catch (QueryValidatorException e) {
-        } catch(TeiidException e) {
-			throw new RuntimeException(e);
-        }
-	}	
-    
-	// ################################## ACTUAL TESTS ################################
-	
-	
-    @Test public void testSelectStarWhereNoElementsAreNotSelectable() {
-        helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-	@Test public void testValidateSelect1() {        
-        helpValidate("SELECT e1, e2 FROM test.group", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testValidateSelect2() {        
-        helpValidate("SELECT e2 FROM test.group", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-	}
- 
-	@Test public void testValidateCompare1() {        
-        helpValidate("SELECT e2 FROM vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-	}
-
-    @Test public void testValidateCompare4() {        
-        helpValidate("SELECT e3 FROM vTest.vMap WHERE e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidateCompare6() {        
-        helpValidate("SELECT e0 FROM vTest.vMap WHERE e0 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-    }
-
-	@Test public void testValidateCompareInHaving2() {        
-        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IS NULL", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-	}
-
-	@Test public void testValidateCompareInHaving3() {        
-        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IN ('a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-	}
-
-    @Test public void testValidateCompareInHaving4() {        
-        helpValidate("SELECT e3 FROM vTest.vMap GROUP BY e3 HAVING e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidateCompareInHaving5() {        
-        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-	@Test public void testInvalidAggregate1() {        
-        helpValidate("SELECT SUM(e3) FROM test.group GROUP BY e2", new String[] {"SUM(e3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testInvalidAggregate2() {        
-        helpValidate("SELECT e3 FROM test.group GROUP BY e2", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testInvalidAggregate3() {        
-        helpValidate("SELECT SUM(e2) FROM test.group GROUP BY e2", new String[] {"SUM(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testInvalidAggregate4() {        
-        helpValidate("SELECT AVG(e2) FROM test.group GROUP BY e2", new String[] {"AVG(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-    
-    @Test public void testInvalidAggregate5() {
-        helpValidate("SELECT e1 || 'x' frOM pm1.g1 GROUP BY e2 + 1", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidAggregate6() {
-        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1 HAVING e1 || 'x' > 0", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidAggregate7() {
-        helpValidate("SELECT StringKey, SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = '   '", //$NON-NLS-1$
-                     new String[] {"StringKey"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvalidAggregate8() {
-        helpValidate("SELECT max(ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
-                     new String[] {"MAX(ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvalidAggregate9() {
-        helpValidate("SELECT count(distinct ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
-                     new String[] {"COUNT(DISTINCT ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvalidAggregateIssue190644() {
-        helpValidate("SELECT e3 + 1 from pm1.g1 GROUP BY e2 + 1 HAVING e2 + 1 = 5", new String[] {"e3"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidAggregate1() {
-        helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidAggregate2() {
-        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidAggregate3() {
-        helpValidate("SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
-            "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end", //$NON-NLS-1$
-            new String[] {}, FakeMetadataFactory.exampleBQTCached());
-    }
-	@Test public void testInvalidHaving1() {        
-        helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	@Test public void testInvalidHaving2() {        
-        helpValidate("SELECT e3 FROM test.group HAVING concat(e3,'a') > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
- 
-	@Test public void testNestedAggregateInHaving() {        
-        helpValidate("SELECT e0 FROM test.group GROUP BY e0 HAVING SUM(COUNT(e0)) > 0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-    @Test public void testNestedAggregateInSelect() {        
-        helpValidate("SELECT SUM(COUNT(e0)) FROM test.group GROUP BY e0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidateCaseInGroupBy() {        
-        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE e2 WHEN 0 THEN 1 ELSE 2 END", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testValidateFunctionInGroupBy() {        
-        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testInvalidScalarSubqueryInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY (SELECT 1)", new String[] { "(SELECT 1)" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidConstantInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidReferenceInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateObjectType1() {
-        helpValidate("SELECT DISTINCT * FROM test.group", new String[] {"test.\"group\".e2", "test.\"group\".e3", "test.\"group\".e4", "test.\"group\".e5"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-    }
-
-    @Test public void testValidateObjectType2() {
-        helpValidate("SELECT * FROM test.group ORDER BY e1, e2", new String[] {"e2"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateObjectType3() {
-        helpValidate("SELECT e2 AS x FROM test.group ORDER BY x", new String[] {"x"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidateNonComparableType() {
-        helpValidate("SELECT e3 FROM test.group ORDER BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
- 
-    @Test public void testValidateNonComparableType1() {
-        helpValidate("SELECT e3 FROM test.group union SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateNonComparableType2() {
-        helpValidate("SELECT e3 FROM test.group GROUP BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidateNonComparableType3() {
-        helpValidate("SELECT e3 FROM test.group intersect SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateNonComparableType4() {
-        helpValidate("SELECT e3 FROM test.group except SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidateIntersectAll() {
-        helpValidate("SELECT e3 FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidateSetSelectInto() {
-        helpValidate("SELECT e3 into #temp FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 INTO #temp FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInsert1() {
-        helpValidate("INSERT INTO test.group (e0) VALUES (null)", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testInsert2() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (p1)"); //$NON-NLS-1$
-
-        // Create external metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-
-    @Test public void testInsert3() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (p1+2)"); //$NON-NLS-1$
-
-        // Create external metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-    
-	// non-null, no-default elements not left
-    @Test public void testInsert4() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata1();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (2)"); //$NON-NLS-1$
-
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-    
-	// non-null, no-default elements left
-    @Test public void testInsert5() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata1();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e1, e2) VALUES ('x', 'y')"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {"test.\"group\".e0"}, metadata); //$NON-NLS-1$
-    }    
-
-    @Test public void testValidateInsertElements1() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e0, e1, e2) VALUES (5, 'x', 'y')"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateInsertElements2() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e1) VALUES ('y')"); //$NON-NLS-1$
-
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-
-    @Test public void testValidateInsertElements3_autoIncNotRequired() throws Exception {
-    	helpValidate("INSERT INTO test.group (e0) VALUES (1)", new String[] {}, exampleMetadata3()); //$NON-NLS-1$
-    }
-
-    @Test public void testUpdate1() {
-        helpValidate("UPDATE test.group SET e0=null", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-        
-    @Test public void testUpdate2() {
-        helpValidate("UPDATE test.group SET e0=1, e0=2", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }  
-    
-    @Test public void testUpdateSubqueryCriteria() {
-        helpValidate("UPDATE vm1.g1 SET e1=1 WHERE exists (select * from vm1.g1)" , new String[] {"EXISTS (SELECT * FROM vm1.g1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testUpdate4() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group SET e0=p1"); //$NON-NLS-1$
-        
-        // Create external metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-
-    @Test public void testUpdate5() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group SET e0=p1+2"); //$NON-NLS-1$
-
-        // Create external metadata
-        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
-        ArrayList sqParams = new ArrayList();
-        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
-        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-        sqParams.add(in);
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sqGroup, sqParams);
-
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-
-    @Test public void testValidateUpdateElements1() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e0 = 5, e1 = 'x', e2 = 'y'"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateUpdateElements2() throws Exception {
-        QueryMetadataInterface metadata = exampleMetadata();
-
-        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e1 = 'x'"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, metadata);
-
-        helpRunValidator(command, new String[] {}, metadata);
-    }
-    @Test public void testXMLQuery1() {
-    	helpValidate("SELECT * FROM vm1.doc1", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-    }
-
-    @Test public void testXMLQuery2() {
-    	helpValidate("SELECT * FROM vm1.doc1 where a2='x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-    }
-
-    @Test public void testXMLQuery3() {
-    	helpValidate("SELECT * FROM vm1.doc1 order by a2", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-    }
-
-    @Test public void testXMLQuery6() {
-    	helpValidate("SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1", new String[] {"\"xml\"", "SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-    @Test public void testXMLQueryWithLimit() {
-    	helpValidate("SELECT * FROM vm1.doc1 limit 1", new String[] {"SELECT * FROM vm1.doc1 LIMIT 1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** test rowlimit function is valid */
-    @Test public void testXMLQueryRowLimit() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimit(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-    
-    /** rowlimit function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimit1() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=-1", new String[] {"RowLimit(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimit function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimit2() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)='x'", new String[] {"RowLimit(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimit function cannot be nested within another function (this test inserts an implicit type conversion) */
-    @Test public void testXMLQueryRowLimitNested() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=a2", new String[] {"RowLimit(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimit function cannot be nested within another function */
-    @Test public void testXMLQueryRowLimitNested2() {
-        helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimit(a2), string)=a2", new String[] {"convert(RowLimit(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimit function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimit3a() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2) = convert(a2, integer)", new String[] {"RowLimit(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimit function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimit3b() {
-        helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimit(a2)", new String[] {"convert(a2, integer) = RowLimit(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    /** rowlimit function arg must be an element symbol */
-    @Test public void testXMLQueryRowLimit4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit('x') = 3", new String[] {"rowlimit('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimit function arg must be an element symbol */
-    @Test public void testXMLQueryRowLimit5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(concat(a2, 'x')) = 3", new String[] {"rowlimit(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimit function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitConjunct() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimit(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimit function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitCompound() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    /** rowlimit function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitCompound2() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    /** rowlimit function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitCompound3() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    /** each rowlimit function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitCompound4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    /** 
-     * It doesn't make sense to use rowlimit twice on same element, but can't be
-     * invalidated here (could be two different elements but in the same 
-     * mapping class - needs to be caught in XMLPlanner)
-     */
-    @Test public void testXMLQueryRowLimitCompound5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria() {
-        helpValidate("SELECT * FROM vm1.doc1 where not(rowlimit(a2) = 3)", new String[] {"NOT (rowlimit(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria2() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (3)", new String[] {"rowlimit(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testXMLQueryRowLimitInvalidCriteria3() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) LIKE 'x'", new String[] {"rowlimit(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IS NULL", new String[] {"rowlimit(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria6() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria6a() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimit(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimit(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testXMLQueryRowLimitInvalidCriteria7() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) BETWEEN 2 AND 3", new String[] {"rowlimit(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitInvalidCriteria8() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    /** using rowlimit pseudo-function in non-XML query is invalid */
-    @Test public void testNonXMLQueryRowLimit() {        
-        helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimit(e1) = 2", new String[] {"rowlimit(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    /** test rowlimitexception function is valid */
-    @Test public void testXMLQueryRowLimitException() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimitException(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-    
-    /** rowlimitexception function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimitException1() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=-1", new String[] {"RowLimitException(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimitexception function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimitException2() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)='x'", new String[] {"RowLimitException(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimitexception function cannot be nested within another function (this test inserts an implicit type conversion) */
-    @Test public void testXMLQueryRowLimitExceptionNested() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=a2", new String[] {"RowLimitException(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimitexception function cannot be nested within another function */
-    @Test public void testXMLQueryRowLimitExceptionNested2() {
-        helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimitException(a2), string)=a2", new String[] {"convert(RowLimitException(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimitexception function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimitException3a() {
-        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2) = convert(a2, integer)", new String[] {"RowLimitException(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimitexception function operand must be nonnegative integer */
-    @Test public void testXMLQueryRowLimitException3b() {
-        helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimitException(a2)", new String[] {"convert(a2, integer) = RowLimitException(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    /** rowlimitexception function arg must be an element symbol */
-    @Test public void testXMLQueryRowLimitException4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception('x') = 3", new String[] {"rowlimitexception('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimitexception function arg must be an element symbol */
-    @Test public void testXMLQueryRowLimitException5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(concat(a2, 'x')) = 3", new String[] {"rowlimitexception(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /** rowlimitexception function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitExceptionConjunct() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimitexception(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    /** rowlimitexception function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitExceptionCompound() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    /** rowlimitexception function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitExceptionCompound2() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    /** rowlimitexception function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitExceptionCompound3() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    /** each rowlimitexception function arg must be a single conjunct */
-    @Test public void testXMLQueryRowLimitExceptionCompound4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    /** 
-     * It doesn't make sense to use rowlimitexception twice on same element, but can't be
-     * invalidated here (could be two different elements but in the same 
-     * mapping class - needs to be caught in XMLPlanner)
-     */
-    @Test public void testXMLQueryRowLimitExceptionCompound5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria() {
-        helpValidate("SELECT * FROM vm1.doc1 where not(rowlimitexception(a2) = 3)", new String[] {"NOT (rowlimitexception(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria2() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (3)", new String[] {"rowlimitexception(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria3() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) LIKE 'x'", new String[] {"rowlimitexception(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria4() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IS NULL", new String[] {"rowlimitexception(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria5() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6a() {
-        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria7() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) BETWEEN 2 AND 3", new String[] {"rowlimitexception(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria8() {
-        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-    
-    /** using rowlimit pseudo-function in non-XML query is invalid */
-    @Test public void testNonXMLQueryRowLimitException() {        
-        helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimitexception(e1) = 2", new String[] {"rowlimitexception(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }    
-
-    /** using context pseudo-function in non-XML query is invalid */
-    @Test public void testNonXMLQueryContextOperator() {        
-        helpValidate("SELECT e2 FROM vTest.vMap WHERE context(e1, e1) = 2", new String[] {"context(e1, e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }      
-    
-    @Test public void testValidateSubquery1() {        
-        helpValidate("SELECT e2 FROM (SELECT e2 FROM vTest.vMap WHERE e2 = 'a') AS x", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidateSubquery2() {        
-        helpValidate("SELECT e2 FROM (SELECT e3 FROM vTest.vMap) AS x, vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testValidateSubquery3() {        
-        helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-    }
-
-    @Test public void testValidateUnionWithSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 union all SELECT e3 FROM test.group union all select * from (SELECT e1 FROM test.group) as subquery1", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateExistsSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE EXISTS (SELECT e2 FROM vTest.vMap WHERE e2 = 'a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testValidateScalarSubquery() {        
-        helpValidate("SELECT e2, (SELECT e1 FROM vTest.vMap WHERE e2 = '3') FROM test.group2", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-
-    @Test public void testValidateAnyCompareSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE e1 < ANY (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateAllCompareSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE e1 = ALL (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateSomeCompareSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE e1 <= SOME (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateCompareSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE e1 >= (SELECT e1 FROM test.group WHERE e1 = 1)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateInClauseSubquery() {        
-        helpValidate("SELECT e2 FROM test.group2 WHERE e1 IN (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testValidateExec1() {
-        helpValidate("EXEC pm1.sq1()", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-    }
-    
-	// valid variable declared
-    @Test public void testCreateUpdateProcedure4() {
-        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 =0;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-        
-		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// validating criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
-    @Test public void testCreateUpdateProcedure5() {
-        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 + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1))\n";                 //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
-        procedure = procedure + "END\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$
-        
-		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// validating Translate CRITERIA, elements on it should be virtual group elements
-    @Test public void testCreateUpdateProcedure7() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\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$
-        
-		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// ROWS_UPDATED not assigned
-    @Test public void testCreateUpdateProcedure8() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1);\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-        
-		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-
-	// validating AssignmentStatement, more than one project symbol on the
-	// command
-    @Test public void testCreateUpdateProcedure11() {
-        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.e2, 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$
-        
-		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// validating AssignmentStatement, more than one project symbol on the
-	// command
-    @Test public void testCreateUpdateProcedure12() {
-        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.e2, 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$
-        
-		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// TranslateCriteria on criteria of the if statement
-    @Test public void testCreateUpdateProcedure13() {
-        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 + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\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$
-        
-		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// INPUT ised in command
-    @Test public void testCreateUpdateProcedure16() {
-        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 + "INSERT into pm1.g1 (pm1.g1.e1) values (INPUT.e1);\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$
-        
-		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// elements on with should be on ON
-    @Test public void testCreateUpdateProcedure17() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e1) WITH (e1 = 20, e2 = 30);\n"; //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
-        
-		helpFailProcedure(procedure, userQuery,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// failure, aggregate function in query transform
-    @Test public void testCreateUpdateProcedure18() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\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$
-
-		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-    
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// failure, aggregate function in query transform
-    @Test public void testCreateUpdateProcedure18a() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\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 y like '%a' and e3= 1"; //$NON-NLS-1$
-
-		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-	// failure, translated criteria elements not present on groups of command
-    @Test public void testCreateUpdateProcedure19() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE = CRITERIA ON (x, y);\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 y= 1"; //$NON-NLS-1$
-
-		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-	
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testCreateUpdateProcedure20() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (y = e2+1);\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 y= 1"; //$NON-NLS-1$
-
-		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testCreateUpdateProcedure25() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE > CRITERIA ON (y);\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 y > 1"; //$NON-NLS-1$
-
-		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testCreateUpdateProcedure26() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e3 = e2+1);\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$
-
-		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-
-	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
-    @Test public void testCreateUpdateProcedure27() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE LIKE CRITERIA WITH (y = e2+1);\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 y = 1"; //$NON-NLS-1$
-
-		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-    
-    @Test public void testCreateUpdateProcedure28() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
-        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE CRITERIA;\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 y = 1 or y = 2"; //$NON-NLS-1$
-
-		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-
-    // using aggregate function within a procedure - defect #8394
-    @Test public void testCreateUpdateProcedure31() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string MaxTran;\n"; //$NON-NLS-1$
-        procedure = procedure + "MaxTran = SELECT MAX(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 userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
-        helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-	// assigning null values to known datatype variable
-	@Test public void testCreateUpdateProcedure32() {
-		String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-		procedure = procedure + "DECLARE string var;\n"; //$NON-NLS-1$
-		procedure = procedure + "var = null;\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 y = 1"; //$NON-NLS-1$
-
-		helpValidateProcedure(procedure, userQuery,
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
-	}
-    
-    @Test public void testDefect13643() {
-        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 + "LOOP ON (SELECT * FROM pm1.g1) AS myCursor\n"; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "var1 = SELECT COUNT(*) FROM myCursor;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\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 y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testValidHaving() {
-        helpValidate(
-            "SELECT intnum " + //$NON-NLS-1$
-            "FROM bqt1.smalla " + //$NON-NLS-1$
-            "GROUP BY intnum " + //$NON-NLS-1$
-            "HAVING SUM(floatnum) > 1",  //$NON-NLS-1$
-            new String[] { }, FakeMetadataFactory.exampleBQTCached());
-    } 
-    
-    @Test public void testValidHaving2() {
-        String sql =  "SELECT intkey FROM bqt1.smalla WHERE intkey = 1 " + //$NON-NLS-1$
-            "GROUP BY intkey HAVING intkey = 1";         //$NON-NLS-1$
-        helpValidate(sql, new String[] {}, FakeMetadataFactory.exampleBQTCached());
-    } 
-    
-    @Test public void testVirtualProcedure(){
-          helpValidate("EXEC pm1.vsp1()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
-    }
-        
-    @Test public void testSelectWithNoFrom() {        
-        helpValidate("SELECT 5", new String[] {}, exampleMetadata()); //$NON-NLS-1$
-    }
-    
-    @Test public void testSelectIntoTempGroup() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
-        helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    /**
-     * Defect 24346
-     */
-    @Test public void testInvalidSelectIntoTempGroup() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    /**
-     * Defect 24346 with type mismatch
-     */
-    @Test public void testInvalidSelectIntoTempGroup1() {
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "create local temporary table #myTempTable (e1 integer);\n";         //$NON-NLS-1$
-        procedure = procedure + "SELECT e1 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
-        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
-        procedure = procedure + "END\n"; //$NON-NLS-1$
-
-        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-
-    
-    @Test public void testSelectIntoPhysicalGroup() {
-        helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
-
-        helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
-        helpValidate("SELECT e0, e1, e2 INTO test.group3 FROM test.group2", new String[] {"test.group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testSelectIntoElementsNotUpdateable() {
-    	helpValidate("SELECT e0, e1, e2 INTO test.group2 FROM test.group3", new String[] {"test.group2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidSelectIntoTooManyElements() {
-    	helpValidate("SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testInvalidSelectIntoTooFewElements() {
-    	helpValidate("SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testInvalidSelectIntoIncorrectTypes() {
-        helpValidate("SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testSelectIntoWithStar() {
-        helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-    }
-    
-    @Test public void testInvalidSelectIntoWithStar() {
-        helpValidate("SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1", new String[] {"SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1;\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 y = 1"; //$NON-NLS-1$
-
-        helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testSelectIntoVirtualGroup() {
-        helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-        
-        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
-        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
-
-        helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-    
-    @Test public void testVirtualProcedure2(){
-          helpValidate("EXEC pm1.vsp13()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
-    }
-
-    //procedure that has another procedure in the transformation
-    @Test public void testVirtualProcedure3(){
-        helpValidate("EXEC pm1.vsp27()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
-    }
-    
-    @Test public void testNonEmbeddedSubcommand_defect11000() {        
-        helpValidate("SELECT e0 FROM vTest.vGroup", new String[0], exampleMetadata()); //$NON-NLS-1$ 
-    }
-    
-    @Test public void testValidateObjectInComparison() throws Exception {
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE ObjectValue = 5";   //$NON-NLS-1$
-        ValidatorReport report = helpValidate(sql, new String[] {"ObjectValue = 5"}, FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
-        assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: ObjectValue = 5.", report.toString()); //$NON-NLS-1$
-    }
-
-    @Test public void testValidateAssignmentWithFunctionOnParameter_InServer() throws Exception{
-        String sql = "EXEC pm1.vsp36(5)";  //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        Command command = new QueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, metadata);
-        
-        // Validate
-        ValidatorReport report = Validator.validate(command, metadata); 
-        assertEquals(0, report.getItems().size());                      
-    }
-
-    @Test public void testDefect9917() throws Exception{
-    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        String sql = "SELECT lookup('pm1.g1', 'e1a', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
-        Command command = new QueryParser().parseCommand(sql);
-        try{
-        	QueryResolver.resolveCommand(command, metadata); 
-        	fail("Did not get exception"); //$NON-NLS-1$
-        }catch(QueryResolverException e){
-        	//expected
-        }
-        
-        sql = "SELECT lookup('pm1.g1a', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
-        command = new QueryParser().parseCommand(sql);
-        try{
-        	QueryResolver.resolveCommand(command, metadata); 
-        	fail("Did not get exception"); //$NON-NLS-1$
-        }catch(QueryResolverException e){
-        	//expected
-        }
-    }
-    
-    @Test public void testLookupKeyElementComparable() throws Exception {
-    	QueryMetadataInterface metadata = exampleMetadata2();
-        String sql = "SELECT lookup('test.group', 'e2', 'e3', convert(e2, blob)) AS x FROM test.group"; //$NON-NLS-1$
-        Command command = QueryParser.getQueryParser().parseCommand(sql);
-    	QueryResolver.resolveCommand(command, metadata); 
-        
-        ValidatorReport report = Validator.validate(command, metadata);
-        assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: test.\"group\".e3.", report.toString()); //$NON-NLS-1$
-    }
-    
-    @Test public void testDefect12107() throws Exception{
-    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        String sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e2', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
-        Command command = helpResolve(sql, metadata);
-        sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
-        command = helpResolve(sql, metadata);
-        ValidatorReport report = Validator.validate(command, metadata);
-        assertEquals("The aggregate function SUM cannot be used with non-numeric expressions: SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2))", report.toString()); //$NON-NLS-1$
-    }
-    
-    private ValidatorReport helpValidateInModeler(String procName, String procSql, QueryMetadataInterface metadata) throws Exception {
-        Command command = new QueryParser().parseCommand(procSql);
-        
-        GroupSymbol group = new GroupSymbol(procName);
-        Map externalMetadata = getStoredProcedureExternalMetadata(group, metadata);
-        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
-        
-        // Validate
-        return Validator.validate(command, metadata);         
-    }
-
-    @Test public void testValidateDynamicCommandWithNonTempGroup_InModeler() throws Exception{
-        // SQL is same as pm1.vsp36() in example1 
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into pm1.g3; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
-        assertEquals(1, report.getItems().size());
-        assertEquals("Wrong number of elements being SELECTed INTO the target table. Expected 4 elements, but was 1.", report.toString()); //$NON-NLS-1$
-    }
-    
-    @Test public void testDynamicDupUsing() throws Exception {
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into #temp using id=1, id=2; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
-        assertEquals(1, report.getItems().size());
-        assertEquals("Elements cannot appear more than once in a SET or USING clause.  The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
-    }    
-    
-    @Test public void testValidateAssignmentWithFunctionOnParameter_InModeler() throws Exception{
-        // SQL is same as pm1.vsp36() in example1 
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
-        assertEquals(0, report.getItems().size());                      
-    }
-    
-    @Test public void testDefect12533() {
-        String sql = "SELECT BQT1.SmallA.DateValue, BQT2.SmallB.ObjectValue FROM BQT1.SmallA, BQT2.SmallB " +  //$NON-NLS-1$
-            "WHERE BQT1.SmallA.DateValue = BQT2.SmallB.DateValue AND BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue " + //$NON-NLS-1$
-            "AND BQT1.SmallA.IntKey < 30 AND BQT2.SmallB.IntKey < 30 ORDER BY BQT1.SmallA.DateValue"; //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-        
-        // Validate
-        helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata);  //$NON-NLS-1$ 
-    }
-
-    @Test public void testDefect16772() throws Exception{
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
-        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
-        assertEquals("Expected report to have no validation failures", false, report.hasItems()); //$NON-NLS-1$
-    }
-	
-	@Test public void testDefect14886() throws Exception{        
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        Command command = new QueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, new HashMap(), metadata, AnalysisRecord.createNonRecordingRecord());
-        
-        // Validate
-        ValidatorReport report = Validator.validate(command, metadata); 
-        // Validate
-        assertEquals(1, report.getItems().size());  	
-    }
-	
-    @Test public void testDefect21389() throws Exception{        
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; INSERT INTO #temptable (e1) VALUES ('a'); END"; //$NON-NLS-1$      
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
-        
-        Command command = new QueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, new HashMap(), metadata, AnalysisRecord.createNonRecordingRecord());
-        
-        // Validate
-        ValidatorReport report = Validator.validate(command, metadata); 
-        // Validate
-        assertEquals(0, report.getItems().size());      
-    }
-    
-    @Test public void testMakeNotDep() {
-        helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKENOTDEP group2, group3", new String[0], exampleMetadata()); //$NON-NLS-1$
-    }
-    @Test public void testInvalidMakeNotDep() {
-    	helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKEDEP group2 MAKENOTDEP group2, group3", new String[] {"OPTION MAKEDEP group2 MAKENOTDEP group2, group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidLimit() {
-        helpValidate("SELECT * FROM pm1.g1 LIMIT -5", new String[] {"LIMIT -5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidLimit_Offset() {
-    	helpValidate("SELECT * FROM pm1.g1 LIMIT -1, 100", new String[] {"LIMIT -1, 100"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    /**
-     * Test case 4237.  This test simulates the way the modeler transformation 
-     * panel uses the query resolver and validator to validate a transformation for
-     * a virtual procedure.  The modeler has to supply external metadata for the 
-     * virtual procedure group and parameter names (simulated in this test).
-     * 
-     * This virtual procedure calls a physical stored procedure directly.  
-     */
-    @Test public void testCase4237() {
-
-        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
-        Map externalMetadata = helpCreateCase4237ExternalMetadata(metadata);
-        
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"; //$NON-NLS-1$ 
-        Command command = helpResolve(sql, metadata, externalMetadata);
-        helpRunValidator(command, new String[0], metadata);
-    }
-
-    /**
-     * This test was already working before the case was logged, due for some reason
-     * to the exec() statement being inside an inline view.  This is a control test. 
-     */
-    @Test public void testCase4237InlineView() {
-
-        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
-        Map externalMetadata = helpCreateCase4237ExternalMetadata(metadata);
-        
-        String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM (EXEC pm1.sp(vm1.sp.in1)) AS FOO; END"; //$NON-NLS-1$ 
-        Command command = helpResolve(sql, metadata, externalMetadata);
-        helpRunValidator(command, new String[0], metadata);
-    }    
-    
-    /**
-     * Set up external metadata describing the virtual procedure and parameters 
-     * @param metadata FakeMetadataFacade
-     * @return external metadata Map
-     */
-    private Map helpCreateCase4237ExternalMetadata(FakeMetadataFacade metadata) {
-        GroupSymbol sp = new GroupSymbol("vm1.sp");//$NON-NLS-1$ 
-        FakeMetadataObject spObj = metadata.getStore().findObject("vm1.sp", FakeMetadataObject.PROCEDURE);//$NON-NLS-1$ 
-        sp.setMetadataID(spObj);
-        ElementSymbol param = new ElementSymbol("vm1.sp.in1");//$NON-NLS-1$ 
-        List paramIDs = (List)spObj.getProperty(FakeMetadataObject.Props.PARAMS);
-        Iterator i = paramIDs.iterator();
-        while (i.hasNext()) {
-            FakeMetadataObject paramID = (FakeMetadataObject)i.next();
-            if (paramID.getProperty(FakeMetadataObject.Props.DIRECTION).equals(new Integer(ParameterInfo.IN))) {
-                param.setMetadataID(paramID);
-                break;
-            }
-        }
-        
-        Map externalMetadata = new HashMap();
-        externalMetadata.put(sp, Arrays.asList(new ElementSymbol[] { param }));
- 
-        return externalMetadata;
-    }
-
-    /**
-     * Create fake metadata for this case.  Need a physical stored procedure and
-     * a virtual stored procedure which calls the physical one. 
-     * @return
-     */
-    private FakeMetadataFacade helpCreateCase4237VirtualProcedureMetadata() {
-        FakeMetadataObject physicalModel = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject resultSet = FakeMetadataFactory.createResultSet("pm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject returnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, resultSet);  //$NON-NLS-1$
-        FakeMetadataObject inParam = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject storedProcedure = FakeMetadataFactory.createStoredProcedure("pm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { returnParam, inParam }), "pm1.sp2");  //$NON-NLS-1$ //$NON-NLS-2$
-        
-        FakeMetadataObject virtualModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
-        FakeMetadataObject virtualResultSet = FakeMetadataFactory.createResultSet("vm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject virtualReturnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, virtualResultSet);  //$NON-NLS-1$
-        FakeMetadataObject virtualInParam = FakeMetadataFactory.createParameter("in1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode queryNode = new QueryNode("vm1.sp", "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject virtualStoredProcedure = FakeMetadataFactory.createVirtualProcedure("vm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { virtualReturnParam, virtualInParam }), queryNode);  //$NON-NLS-1$
-                
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(physicalModel);
-        store.addObject(resultSet);
-        store.addObject(storedProcedure);
-        store.addObject(virtualModel);
-        store.addObject(virtualResultSet);
-        store.addObject(virtualStoredProcedure);
-        return new FakeMetadataFacade(store);
-    }       
-    
-    @Test public void testSelectIntoWithNull() {
-        helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
-    }
-    
-    @Test public void testCreateWithNonSortablePrimaryKey() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        Command command = helpResolve("create local temporary table x (column1 string, column2 clob, primary key (column2))", metadata); //$NON-NLS-1$
-        helpRunValidator(command, new String[] {"column2"}, FakeMetadataFactory.example1Cached()); 
-    }
-        
-    @Test public void testDropNonTemporary() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
-        helpRunValidator(command, new String[] {command.toString()}, FakeMetadataFactory.example1Cached()); 
-    }
-    
-    @Test public void testNestedContexts() {
-        helpValidate("SELECT * FROM vm1.doc1 where context(a0, context(a0, a2))='x'", new String[] {"context(a0, context(a0, a2))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testValidContextElement() {
-        helpValidate("SELECT * FROM vm1.doc1 where context(1, a2)='x'", new String[] {"context(1, a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInsertIntoVirtualWithQuery() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        Command command = helpResolve("insert into vm1.g1 select 1, 2, true, 3", metadata); //$NON-NLS-1$
-        ValidatorReport report = Validator.validate(command, metadata);
-        assertTrue(report.getItems().isEmpty());
-    }
-    
-    @Test public void testDynamicIntoDeclaredTemp() throws Exception {
-        StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE  ") //$NON-NLS-1$
-                                .append("BEGIN\n") //$NON-NLS-1$
-                                .append("CREATE LOCAL TEMPORARY TABLE x (column1 string);") //$NON-NLS-1$
-                                .append("execute string 'SELECT e1 FROM pm1.g2' as e1 string INTO x;\n") //$NON-NLS-1$
-                                .append("select column1 from x;\n") //$NON-NLS-1$
-                                .append("END\n"); //$NON-NLS-1$
-        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
-        assertEquals(report.toString(), 0, report.getItems().size());
-    }
-    
-    @Test public void testVariablesGroupSelect() {
-        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
-        procedure += "BEGIN\n"; //$NON-NLS-1$
-        procedure += "DECLARE integer VARIABLES.var1 = 1;\n"; //$NON-NLS-1$
-        procedure += "select * from variables;\n"; //$NON-NLS-1$
-        procedure += "END\n"; //$NON-NLS-1$
-        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        Command command = helpResolve(procedure, metadata);
-        helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
-    }
-    
-    @Test public void testClobEquals() {
-        TestValidator.helpValidate("SELECT * FROM test.group where e4 = '1'", new String[] {"e4 = '1'"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-    
-    /**
-     *  Should not fail since the update changing set is not really criteria
-     */
-    @Test public void testUpdateWithClob() {
-        TestValidator.helpValidate("update test.group set e4 = ?", new String[] {}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ 
-    }
-
-    @Test public void testBlobLessThan() {
-        TestValidator.helpValidate("SELECT * FROM test.group where e3 < ?", new String[] {"e3 < ?"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-    
-	@Test public void testValidateCompare2() {        
-        helpValidate("SELECT e2 FROM test.group WHERE e4 IS NULL", new String[] {}, exampleMetadata2()); //$NON-NLS-1$ 
-	}
-
-	@Test public void testValidateCompare3() {        
-        helpValidate("SELECT e2 FROM test.group WHERE e4 IN ('a')", new String[] {"e4 IN ('a')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-    @Test public void testValidateCompare5() {        
-        helpValidate("SELECT e2 FROM test.group WHERE e4 BETWEEN '1' AND '2'", new String[] {"e4 BETWEEN '1' AND '2'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-	@Test public void testValidateCompareInHaving1() {        
-        helpValidate("SELECT e1 FROM test.group GROUP BY e1 HAVING convert(e1, clob) = 'a'", new String[] {"convert(e1, clob) = 'a'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	@Test public void testValidateNoExpressionName() {        
-        helpValidate("SELECT xmlelement(name a, xmlattributes('1'))", new String[] {"XMLATTRIBUTES('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	@Test public void testValidateNoExpressionName1() {        
-        helpValidate("SELECT xmlforest('1')", new String[] {"XMLFOREST('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-    @Test public void testXpathValueValid_defect15088() {
-        String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', 'a/b/c')"; //$NON-NLS-1$
-        helpValidate(userSql, new String[] {}, FakeMetadataFactory.exampleBQTCached());        
-    }
-
-    @Test public void testXpathValueInvalid_defect15088() throws Exception {
-        String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"; //$NON-NLS-1$
-        helpValidate(userSql, new String[] {"xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"}, FakeMetadataFactory.exampleBQTCached());
-    }
-    
-    @Test public void testTextTableNegativeWidth() {        
-        helpValidate("SELECT * from texttable(null columns x string width -1) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH -1) AS x"}, RealMetadataFactory.exampleBQTCached()); 
-	}
-    
-    @Test public void testTextTableNoWidth() {        
-        helpValidate("SELECT * from texttable(null columns x string width 1, y integer) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1, y integer) AS x"}, RealMetadataFactory.exampleBQTCached()); 
-	}
-
-    @Test public void testTextTableInvalidDelimiter() {        
-        helpValidate("SELECT * from texttable(null columns x string width 1 DELIMITER 'z') as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1 DELIMITER 'z') AS x"}, RealMetadataFactory.exampleBQTCached()); 
-	}
-    
-    @Test public void testXMLNamespaces() {
-    	helpValidate("select xmlforest(xmlnamespaces(no default, default 'http://foo'), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES(NO DEFAULT, DEFAULT 'http://foo')"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXMLNamespacesReserved() {
-    	helpValidate("select xmlforest(xmlnamespaces('http://foo' as xmlns), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS xmlns)"}, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testXMLTablePassingMultipleContext() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>'), xmlparse(DOCUMENT '<b/>')) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>'), XMLPARSE(DOCUMENT '<b/>')) AS x"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Ignore("this is actually handled by saxon and will show up during resolving")
-    @Test public void testXMLTablePassingSameName() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing {x '<a/>'} as a, {x '<b/>'} as a) as x", new String[] {"xmltable('/' passing e1, e1 || 'x') as x"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXMLTablePassingContextType() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXMLTableMultipleOrdinals() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing XMLPARSE(DOCUMENT '<a/>') columns x for ordinality, y for ordinality) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS x FOR ORDINALITY, y FOR ORDINALITY) AS x"}, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testXMLTableContextRequired() {
-    	helpValidate("select * from xmltable('/a/b' passing convert('<a/>', xml) as a columns x for ordinality, c integer path '.') as x", new String[] {"XMLTABLE('/a/b' PASSING convert('<a/>', xml) AS a COLUMNS x FOR ORDINALITY, c integer PATH '.') AS x"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXMLQueryPassingContextType() {
-    	helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testQueryString() {
-    	helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXmlNameValidation() throws Exception {
-    	helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, FakeMetadataFactory.example1Cached());
-    }
-
-    @Test public void testXmlParse() throws Exception {
-    	helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testDecode() throws Exception {
-    	helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, FakeMetadataFactory.example1Cached());
-    }
-    
-    @Test public void testValidateXMLAGG() {        
-        helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-    
-    @Test public void testValidateBooleanAgg() {        
-        helpValidate("SELECT EVERY(e1) from pm1.g1", new String[] {"EVERY(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-    
-    @Test public void testValidateStatAgg() {        
-        helpValidate("SELECT stddev_pop(distinct e2) from pm1.g1", new String[] {"STDDEV_POP(DISTINCT e2)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-    
-    @Test public void testValidateScalarSubqueryTooManyColumns() {        
-        helpValidate("SELECT e2, (SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidIntoSubquery() {
-    	helpValidate("SELECT e2, (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidIntoSubquery1() {
-    	helpValidate("SELECT e2 FROM pm1.g2 WHERE EXISTS (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidIntoSubquery2() {
-    	helpValidate("SELECT * FROM (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') x", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    @Test public void testInvalidIntoSubquery3() {
-    	helpValidate("SELECT e2 FROM pm1.g2 WHERE e2 in (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testInvalidIntoSubquery4() throws Exception {
-        StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE\n") //$NON-NLS-1$
-                                .append("BEGIN\n") //$NON-NLS-1$
-                                .append("loop on (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') as x\n") //$NON-NLS-1$
-                                .append("BEGIN\nSELECT 1;\nEND\nSELECT 1\n;END\n"); //$NON-NLS-1$
-        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
-        
-        // Validate
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
-        examineReport(procedure, new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, report);
-    }
-    
-    @Test public void testDisallowUpdateOnMultisourceElement() throws Exception {  
-    	Set<String> models = new HashSet<String>();
-    	models.add("pm1");
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", "UPDATE PM1.G1 set SOURCE_NAME='blah'", new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
-        assertEquals(report.toString(), 1, report.getItems().size());
-    }
-    
-    @Test public void testDisallowProjectIntoMultiSource() throws Exception {  
-    	Set<String> models = new HashSet<String>();
-    	models.add("pm1");
-        helpValidate("insert into pm1.g1 select * from pm1.g1", new String[] {"pm1.g1"}, new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
-    }
-    
-    @Test public void testTextAggEncoding() throws Exception {
-    	helpValidate("select textagg(for e1 encoding abc) from pm1.g1", new String[] {"TEXTAGG(FOR e1 ENCODING abc)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
-    }
-    
-    @Test public void testTextAggHeader() throws Exception {
-    	helpValidate("select textagg(for e1 || 1 HEADER) from pm1.g1", new String[] {"TEXTAGG(FOR (e1 || 1) HEADER)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java (from rev 2774, trunk/engine/src/test/java/org/teiid/query/validator/TestValidator.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/engine/src/test/java/org/teiid/query/validator/TestValidator.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,2028 @@
+/*
+ * 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.validator;
+
+import static org.junit.Assert.*;
+
+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.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryResolverException;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
+import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.StoredProcedureInfo;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.ProcedureContainer;
+import org.teiid.query.sql.lang.SPParameter;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+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;
+
+ at SuppressWarnings("nls")
+public class TestValidator {
+
+    public static Map getStoredProcedureExternalMetadata(GroupSymbol virtualProc, QueryMetadataInterface metadata)
+    throws QueryMetadataException, TeiidComponentException {
+
+        Map externalMetadata = new HashMap();
+
+        StoredProcedureInfo info = metadata.getStoredProcedureInfoForProcedure(virtualProc.getName());
+        if(info!=null) {
+            virtualProc.setMetadataID(info.getProcedureID());
+
+            // List of ElementSymbols - Map Values
+            List paramList = info.getParameters();
+            Iterator iter = paramList.iterator();
+            // Create Symbol List from parameter list
+            List symbolList = new ArrayList();
+            while(iter.hasNext()) {
+                SPParameter param = (SPParameter) iter.next();
+                if(param.getParameterType() == ParameterInfo.IN ||
+                    param.getParameterType() == ParameterInfo.INOUT) {
+                    // Create Element Symbol
+                    ElementSymbol eSymbol = new ElementSymbol(param.getName());
+                    eSymbol.setMetadataID(param);
+                    eSymbol.setType(param.getClassType());
+                    symbolList.add(eSymbol);
+                }
+            }
+            // Create external Metadata Map
+            externalMetadata = new HashMap();
+            externalMetadata.put(virtualProc, symbolList);
+        }
+
+        return externalMetadata;
+    }
+
+    public static FakeMetadataFacade exampleMetadata() {
+        // Create metadata objects        
+        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
+        FakeMetadataObject vModelObj2 = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
+        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
+        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
+        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        elemObj1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
+        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        elemObj2.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3); //$NON-NLS-1$
+        elemObj3.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
+    
+        FakeMetadataObject group2Obj = FakeMetadataFactory.createPhysicalGroup("test.group2", modelObj);         //$NON-NLS-1$
+        FakeMetadataObject elemObj2_0 = FakeMetadataFactory.createElement("test.group2.e0", group2Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        elemObj2_0.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
+        FakeMetadataObject elemObj2_1 = FakeMetadataFactory.createElement("test.group2.e1", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject elemObj2_2 = FakeMetadataFactory.createElement("test.group2.e2", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        elemObj2_2.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
+    
+        FakeMetadataObject group3Obj = FakeMetadataFactory.createPhysicalGroup("test.group3", modelObj);         //$NON-NLS-1$
+        group3Obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE); 
+        FakeMetadataObject elemObj3_0 = FakeMetadataFactory.createElement("test.group3.e0", group3Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject elemObj3_1 = FakeMetadataFactory.createElement("test.group3.e1", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject elemObj3_2 = FakeMetadataFactory.createElement("test.group3.e2", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+    
+        // Create virtual group & elements.
+        QueryNode vNode = new QueryNode("vTest.vGroup", "SELECT * FROM test.group WHERE e2 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject vGroup = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj2, vNode);         //$NON-NLS-1$
+        List vGroupE = FakeMetadataFactory.createElements(vGroup, 
+            new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+
+        QueryNode vNode2 = new QueryNode("vTest.vMap", "SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject vGroup2 = FakeMetadataFactory.createVirtualGroup("vTest.vMap", vModelObj2, vNode2);         //$NON-NLS-1$
+        List vGroupE2 = FakeMetadataFactory.createElements(vGroup2, 
+            new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        ((FakeMetadataObject)vGroupE2.get(0)).putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
+        ((FakeMetadataObject)vGroupE2.get(1)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
+        ((FakeMetadataObject)vGroupE2.get(2)).putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+        ((FakeMetadataObject)vGroupE2.get(3)).putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
+    
+        // Create virtual documents
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement complexRoot = doc.addChildElement(new MappingElement("a0")); //$NON-NLS-1$
+        
+        MappingElement sourceNode = complexRoot.addChildElement(new MappingElement("a1")); //$NON-NLS-1$
+        sourceNode.setSource("test.group"); //$NON-NLS-1$
+        sourceNode.addChildElement(new MappingElement("a2", "test.group.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+        sourceNode.addChildElement(new MappingElement("b2", "test.group.e2")); //$NON-NLS-1$ //$NON-NLS-2$
+        sourceNode.addChildElement(new MappingElement("c2", "test.group.e3")); //$NON-NLS-1$ //$NON-NLS-2$
+        
+    	FakeMetadataObject docModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
+        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("vm1.doc1", docModel, doc); //$NON-NLS-1$
+    	List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "a0", "a0.a1", "a0.a1.a2", "a0.a1.b2", "a0.a1.c2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    		new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+                        
+    	// set up validator metadata
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(modelObj);
+        store.addObject(groupObj);
+        store.addObject(elemObj0);
+        store.addObject(elemObj1);
+        store.addObject(elemObj2);
+        store.addObject(elemObj3);
+        store.addObject(vGroup);
+        store.addObjects(vGroupE);
+        store.addObject(vGroup2);
+        store.addObjects(vGroupE2);
+        store.addObject(docModel);
+        store.addObject(group2Obj);
+        store.addObject(elemObj2_0);
+        store.addObject(elemObj2_1);
+        store.addObject(elemObj2_2);
+        store.addObject(group3Obj);
+        store.addObject(elemObj3_0);
+        store.addObject(elemObj3_1);
+        store.addObject(elemObj3_2);
+        store.addObject(doc1);
+        store.addObjects(docE1);
+    	return new FakeMetadataFacade(store);
+    }
+	
+    public FakeMetadataFacade exampleMetadata1() {
+        // Create metadata objects        
+        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
+        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
+
+        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3);         //$NON-NLS-1$
+
+        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
+        elemObj0.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
+
+        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
+        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.TRUE);
+        
+        elemObj2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
+        elemObj2.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
+        
+		// set up validator metadata
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(modelObj);
+        store.addObject(groupObj);
+        store.addObject(elemObj0);
+        store.addObject(elemObj1);
+        store.addObject(elemObj2);
+        store.addObject(elemObj3);
+		return new FakeMetadataFacade(store);
+    }
+
+    /**
+     * Group has element with type object
+     * @return FakeMetadataFacade
+     */
+    public static FakeMetadataFacade exampleMetadata2() {
+        // Create metadata objects
+        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
+        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
+        
+        List elements = FakeMetadataFactory.createElements(groupObj, new String[] {
+            "e0", "e1", "e2", "e3", "e4", "e5" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+        }, new String[] {
+            DataTypeManager.DefaultDataTypes.INTEGER,
+            DataTypeManager.DefaultDataTypes.STRING,
+            DataTypeManager.DefaultDataTypes.OBJECT,
+            DataTypeManager.DefaultDataTypes.BLOB,
+            DataTypeManager.DefaultDataTypes.CLOB,
+            DataTypeManager.DefaultDataTypes.XML,
+        });
+
+        // set up validator metadata
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(modelObj);
+        store.addObject(groupObj);
+        store.addObjects(elements);
+        return new FakeMetadataFacade(store);
+    }
+
+    public static FakeMetadataFacade exampleMetadata3() {
+        // Create metadata objects        
+        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
+        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
+
+        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+
+        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
+        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
+        elemObj1.putProperty(FakeMetadataObject.Props.AUTO_INCREMENT, Boolean.TRUE);
+        elemObj1.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, "e1:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
+        
+        // set up validator metadata
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(modelObj);
+        store.addObject(groupObj);
+        store.addObject(elemObj0);
+        store.addObject(elemObj1);
+        return new FakeMetadataFacade(store);
+    }
+
+    public static FakeMetadataFacade exampleMetadata4() {
+        // Create metadata objects 
+    	FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test");  //$NON-NLS-1$
+        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
+        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        FakeMetadataObject vModelObj = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
+        QueryNode vNode = new QueryNode("vTest.vGroup", "SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$ 
+        FakeMetadataObject vGroupObj = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj, vNode); //$NON-NLS-1$
+        FakeMetadataObject vElemObj0 = FakeMetadataFactory.createElement("vTest.vGroup.e0", vGroupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject vElemObj1 = FakeMetadataFactory.createElement("vTest.vGroup.e1", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject vElemObj2 = FakeMetadataFactory.createElement("vTest.vGroup.e2", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        List elements = new ArrayList(1);
+        elements.add(vElemObj0); 
+        elements.add(vElemObj1);
+        FakeMetadataObject vGroupAp1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup.ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
+        
+        QueryNode vNode2 = new QueryNode("vTest.vGroup", "SELECT * FROM vTest.vGroup"); //$NON-NLS-1$ //$NON-NLS-2$ 
+        FakeMetadataObject vGroupObj2 = FakeMetadataFactory.createVirtualGroup("vTest.vGroup2", vModelObj, vNode2); //$NON-NLS-1$
+        FakeMetadataObject vElemObj20 = FakeMetadataFactory.createElement("vTest.vGroup2.e0", vGroupObj2, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
+        FakeMetadataObject vElemObj21 = FakeMetadataFactory.createElement("vTest.vGroup2.e1", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        FakeMetadataObject vElemObj22 = FakeMetadataFactory.createElement("vTest.vGroup2.e2", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        elements = new ArrayList(1);
+        elements.add(vElemObj20); 
+        elements.add(vElemObj21);
+        FakeMetadataObject vGroup2Ap1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
+        
+        // set up validator metadata
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(modelObj);
+        store.addObject(groupObj);
+        store.addObject(elemObj0);
+        store.addObject(elemObj1);
+        store.addObject(elemObj2);
+        store.addObject(vModelObj);
+        store.addObject(vGroupObj);
+        store.addObject(vElemObj0);
+        store.addObject(vElemObj1);
+        store.addObject(vElemObj2);
+        store.addObject(vGroupAp1);
+        store.addObject(vGroupObj2);
+        store.addObject(vElemObj20);
+        store.addObject(vElemObj21);
+        store.addObject(vElemObj22);
+        store.addObject(vGroup2Ap1);
+        return new FakeMetadataFacade(store);
+    }
+    
+	// ################################## TEST HELPERS ################################
+
+    static Command helpResolve(String sql, QueryMetadataInterface metadata) { 
+        return helpResolve(sql, metadata, Collections.EMPTY_MAP);
+    }
+    
+	public static Command helpResolve(String sql, QueryMetadataInterface metadata, Map externalMetadata) { 
+		Command command = null;
+		
+		try { 
+			command = QueryParser.getQueryParser().parseCommand(sql);
+			QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+		} catch(Exception e) {
+            throw new TeiidRuntimeException(e);
+		} 
+
+		return command;
+	}
+
+	static ValidatorReport helpValidate(String sql, String[] expectedStringArray, QueryMetadataInterface metadata) {
+        Command command = helpResolve(sql, metadata);
+
+        return helpRunValidator(command, expectedStringArray, metadata);
+    }
+
+    public static ValidatorReport helpRunValidator(Command command, String[] expectedStringArray, QueryMetadataInterface metadata) {
+        try {
+            ValidatorReport report = Validator.validate(command, metadata);
+            
+            examineReport(command, expectedStringArray, report);
+            return report;
+        } catch(TeiidException e) {
+			throw new TeiidRuntimeException(e);
+        }
+	}
+
+	private static void examineReport(Object command,
+			String[] expectedStringArray, ValidatorReport report) {
+		// Get invalid objects from report
+		Collection actualObjs = new ArrayList();
+		report.collectInvalidObjects(actualObjs);
+
+		// Compare expected and actual objects
+		Set<String> expectedStrings = new HashSet(Arrays.asList(expectedStringArray));
+		Set<String> actualStrings = new HashSet<String>();
+		Iterator objIter = actualObjs.iterator();
+		while(objIter.hasNext()) {
+		    LanguageObject obj = (LanguageObject) objIter.next();
+		    actualStrings.add(SQLStringVisitor.getSQLString(obj));
+		}
+
+		if(expectedStrings.size() == 0 && actualStrings.size() > 0) {
+		    fail("Expected no failures but got some: " + report.getFailureMessage()); //$NON-NLS-1$ 
+		} else if(actualStrings.size() == 0 && expectedStrings.size() > 0) {
+		    fail("Expected some failures but got none for sql = " + command); //$NON-NLS-1$
+		} else {
+		    assertEquals("Expected and actual sets of strings are not the same: ", expectedStrings, actualStrings); //$NON-NLS-1$
+		}
+	}
+
+	private void helpValidateProcedure(String procedure, String userUpdateStr, String procedureType) {
+
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+        try {
+        	validateProcedure(userUpdateStr, metadata);
+        } catch(TeiidException e) {
+            throw new TeiidRuntimeException(e);
+        }
+	}
+
+	private void validateProcedure(String userUpdateStr,
+			QueryMetadataInterface metadata) throws QueryResolverException,
+			QueryMetadataException, TeiidComponentException,
+			QueryValidatorException {
+		ProcedureContainer command = (ProcedureContainer)helpResolve(userUpdateStr, metadata);
+		
+		Command proc = QueryResolver.expandCommand(command, metadata, AnalysisRecord.createNonRecordingRecord());
+		
+		ValidatorReport report = Validator.validate(proc, metadata);
+		if(report.hasItems()) {
+		    throw new QueryValidatorException(report.getFailureMessage());
+		}
+
+		report = Validator.validate(command, metadata);
+		if(report.hasItems()) {
+		    throw new QueryValidatorException(report.getFailureMessage());
+		}
+	}
+	
+	private void helpFailProcedure(String procedure, String userUpdateStr, String procedureType) {
+
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+
+        try {
+        	validateProcedure(userUpdateStr, metadata);
+        	fail("Expected failures for " + procedure);
+        } catch (QueryValidatorException e) {
+        } catch(TeiidException e) {
+			throw new RuntimeException(e);
+        }
+	}	
+    
+	// ################################## ACTUAL TESTS ################################
+	
+	
+    @Test public void testSelectStarWhereNoElementsAreNotSelectable() {
+        helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+	@Test public void testValidateSelect1() {        
+        helpValidate("SELECT e1, e2 FROM test.group", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testValidateSelect2() {        
+        helpValidate("SELECT e2 FROM test.group", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+	}
+ 
+	@Test public void testValidateCompare1() {        
+        helpValidate("SELECT e2 FROM vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+	}
+
+    @Test public void testValidateCompare4() {        
+        helpValidate("SELECT e3 FROM vTest.vMap WHERE e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidateCompare6() {        
+        helpValidate("SELECT e0 FROM vTest.vMap WHERE e0 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+    }
+
+	@Test public void testValidateCompareInHaving2() {        
+        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IS NULL", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+	}
+
+	@Test public void testValidateCompareInHaving3() {        
+        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 IN ('a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+	}
+
+    @Test public void testValidateCompareInHaving4() {        
+        helpValidate("SELECT e3 FROM vTest.vMap GROUP BY e3 HAVING e3 LIKE 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidateCompareInHaving5() {        
+        helpValidate("SELECT e2 FROM vTest.vMap GROUP BY e2 HAVING e2 BETWEEN 1000 AND 2000", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+	@Test public void testInvalidAggregate1() {        
+        helpValidate("SELECT SUM(e3) FROM test.group GROUP BY e2", new String[] {"SUM(e3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testInvalidAggregate2() {        
+        helpValidate("SELECT e3 FROM test.group GROUP BY e2", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testInvalidAggregate3() {        
+        helpValidate("SELECT SUM(e2) FROM test.group GROUP BY e2", new String[] {"SUM(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testInvalidAggregate4() {        
+        helpValidate("SELECT AVG(e2) FROM test.group GROUP BY e2", new String[] {"AVG(e2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+    
+    @Test public void testInvalidAggregate5() {
+        helpValidate("SELECT e1 || 'x' frOM pm1.g1 GROUP BY e2 + 1", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidAggregate6() {
+        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1 HAVING e1 || 'x' > 0", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidAggregate7() {
+        helpValidate("SELECT StringKey, SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = '   '", //$NON-NLS-1$
+                     new String[] {"StringKey"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvalidAggregate8() {
+        helpValidate("SELECT max(ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
+                     new String[] {"MAX(ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvalidAggregate9() {
+        helpValidate("SELECT count(distinct ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
+                     new String[] {"COUNT(DISTINCT ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvalidAggregateIssue190644() {
+        helpValidate("SELECT e3 + 1 from pm1.g1 GROUP BY e2 + 1 HAVING e2 + 1 = 5", new String[] {"e3"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidAggregate1() {
+        helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidAggregate2() {
+        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidAggregate3() {
+        helpValidate("SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
+            "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end", //$NON-NLS-1$
+            new String[] {}, FakeMetadataFactory.exampleBQTCached());
+    }
+	@Test public void testInvalidHaving1() {        
+        helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	@Test public void testInvalidHaving2() {        
+        helpValidate("SELECT e3 FROM test.group HAVING concat(e3,'a') > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+ 
+	@Test public void testNestedAggregateInHaving() {        
+        helpValidate("SELECT e0 FROM test.group GROUP BY e0 HAVING SUM(COUNT(e0)) > 0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+    @Test public void testNestedAggregateInSelect() {        
+        helpValidate("SELECT SUM(COUNT(e0)) FROM test.group GROUP BY e0", new String[] {"COUNT(e0)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidateCaseInGroupBy() {        
+        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE e2 WHEN 0 THEN 1 ELSE 2 END", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testValidateFunctionInGroupBy() {        
+        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testInvalidScalarSubqueryInGroupBy() {        
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY (SELECT 1)", new String[] { "(SELECT 1)" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidConstantInGroupBy() {        
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidReferenceInGroupBy() {        
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateObjectType1() {
+        helpValidate("SELECT DISTINCT * FROM test.group", new String[] {"test.\"group\".e2", "test.\"group\".e3", "test.\"group\".e4", "test.\"group\".e5"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    }
+
+    @Test public void testValidateObjectType2() {
+        helpValidate("SELECT * FROM test.group ORDER BY e1, e2", new String[] {"e2"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateObjectType3() {
+        helpValidate("SELECT e2 AS x FROM test.group ORDER BY x", new String[] {"x"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidateNonComparableType() {
+        helpValidate("SELECT e3 FROM test.group ORDER BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+ 
+    @Test public void testValidateNonComparableType1() {
+        helpValidate("SELECT e3 FROM test.group union SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateNonComparableType2() {
+        helpValidate("SELECT e3 FROM test.group GROUP BY e3", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidateNonComparableType3() {
+        helpValidate("SELECT e3 FROM test.group intersect SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateNonComparableType4() {
+        helpValidate("SELECT e3 FROM test.group except SELECT e3 FROM test.group", new String[] {"e3"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidateIntersectAll() {
+        helpValidate("SELECT e3 FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidateSetSelectInto() {
+        helpValidate("SELECT e3 into #temp FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 INTO #temp FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInsert1() {
+        helpValidate("INSERT INTO test.group (e0) VALUES (null)", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testInsert2() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (p1)"); //$NON-NLS-1$
+
+        // Create external metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+
+    @Test public void testInsert3() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (p1+2)"); //$NON-NLS-1$
+
+        // Create external metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+    
+	// non-null, no-default elements not left
+    @Test public void testInsert4() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata1();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e0) VALUES (2)"); //$NON-NLS-1$
+
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+    
+	// non-null, no-default elements left
+    @Test public void testInsert5() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata1();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group (e1, e2) VALUES ('x', 'y')"); //$NON-NLS-1$
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {"test.\"group\".e0"}, metadata); //$NON-NLS-1$
+    }    
+
+    @Test public void testValidateInsertElements1() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e0, e1, e2) VALUES (5, 'x', 'y')"); //$NON-NLS-1$
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateInsertElements2() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("INSERT INTO test.group2 (e1) VALUES ('y')"); //$NON-NLS-1$
+
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+
+    @Test public void testValidateInsertElements3_autoIncNotRequired() throws Exception {
+    	helpValidate("INSERT INTO test.group (e0) VALUES (1)", new String[] {}, exampleMetadata3()); //$NON-NLS-1$
+    }
+
+    @Test public void testUpdate1() {
+        helpValidate("UPDATE test.group SET e0=null", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+        
+    @Test public void testUpdate2() {
+        helpValidate("UPDATE test.group SET e0=1, e0=2", new String[] {"e0"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }  
+    
+    @Test public void testUpdate4() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group SET e0=p1"); //$NON-NLS-1$
+        
+        // Create external metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+
+    @Test public void testUpdate5() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group SET e0=p1+2"); //$NON-NLS-1$
+
+        // Create external metadata
+        GroupSymbol sqGroup = new GroupSymbol("pm1.sq5"); //$NON-NLS-1$
+        ArrayList sqParams = new ArrayList();
+        ElementSymbol in = new ElementSymbol("pm1.sq5.p1"); //$NON-NLS-1$
+        in.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+        sqParams.add(in);
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sqGroup, sqParams);
+
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+
+    @Test public void testValidateUpdateElements1() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e0 = 5, e1 = 'x', e2 = 'y'"); //$NON-NLS-1$
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {"e2", "e0"}, metadata); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateUpdateElements2() throws Exception {
+        QueryMetadataInterface metadata = exampleMetadata();
+
+        Command command = QueryParser.getQueryParser().parseCommand("UPDATE test.group2 SET e1 = 'x'"); //$NON-NLS-1$
+        QueryResolver.resolveCommand(command, metadata);
+
+        helpRunValidator(command, new String[] {}, metadata);
+    }
+    @Test public void testXMLQuery1() {
+    	helpValidate("SELECT * FROM vm1.doc1", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+    }
+
+    @Test public void testXMLQuery2() {
+    	helpValidate("SELECT * FROM vm1.doc1 where a2='x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+    }
+
+    @Test public void testXMLQuery3() {
+    	helpValidate("SELECT * FROM vm1.doc1 order by a2", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+    }
+
+    @Test public void testXMLQuery6() {
+    	helpValidate("SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1", new String[] {"\"xml\"", "SELECT * FROM vm1.doc1 UNION SELECT * FROM vm1.doc1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+    @Test public void testXMLQueryWithLimit() {
+    	helpValidate("SELECT * FROM vm1.doc1 limit 1", new String[] {"SELECT * FROM vm1.doc1 LIMIT 1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** test rowlimit function is valid */
+    @Test public void testXMLQueryRowLimit() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimit(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+    
+    /** rowlimit function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimit1() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=-1", new String[] {"RowLimit(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimit function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimit2() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)='x'", new String[] {"RowLimit(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimit function cannot be nested within another function (this test inserts an implicit type conversion) */
+    @Test public void testXMLQueryRowLimitNested() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2)=a2", new String[] {"RowLimit(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimit function cannot be nested within another function */
+    @Test public void testXMLQueryRowLimitNested2() {
+        helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimit(a2), string)=a2", new String[] {"convert(RowLimit(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimit function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimit3a() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimit(a2) = convert(a2, integer)", new String[] {"RowLimit(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimit function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimit3b() {
+        helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimit(a2)", new String[] {"convert(a2, integer) = RowLimit(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    /** rowlimit function arg must be an element symbol */
+    @Test public void testXMLQueryRowLimit4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit('x') = 3", new String[] {"rowlimit('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimit function arg must be an element symbol */
+    @Test public void testXMLQueryRowLimit5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(concat(a2, 'x')) = 3", new String[] {"rowlimit(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimit function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitConjunct() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimit(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimit function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitCompound() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    /** rowlimit function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitCompound2() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    /** rowlimit function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitCompound3() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    /** each rowlimit function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitCompound4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    /** 
+     * It doesn't make sense to use rowlimit twice on same element, but can't be
+     * invalidated here (could be two different elements but in the same 
+     * mapping class - needs to be caught in XMLPlanner)
+     */
+    @Test public void testXMLQueryRowLimitCompound5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = 3 AND rowlimit(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria() {
+        helpValidate("SELECT * FROM vm1.doc1 where not(rowlimit(a2) = 3)", new String[] {"NOT (rowlimit(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria2() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (3)", new String[] {"rowlimit(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testXMLQueryRowLimitInvalidCriteria3() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) LIKE 'x'", new String[] {"rowlimit(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IS NULL", new String[] {"rowlimit(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria6() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimit(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria6a() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimit(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimit(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testXMLQueryRowLimitInvalidCriteria7() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) BETWEEN 2 AND 3", new String[] {"rowlimit(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitInvalidCriteria8() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimit(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    /** using rowlimit pseudo-function in non-XML query is invalid */
+    @Test public void testNonXMLQueryRowLimit() {        
+        helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimit(e1) = 2", new String[] {"rowlimit(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    /** test rowlimitexception function is valid */
+    @Test public void testXMLQueryRowLimitException() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = RowLimitException(a2)", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+    
+    /** rowlimitexception function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimitException1() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=-1", new String[] {"RowLimitException(a2) = -1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimitexception function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimitException2() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)='x'", new String[] {"RowLimitException(a2) = 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimitexception function cannot be nested within another function (this test inserts an implicit type conversion) */
+    @Test public void testXMLQueryRowLimitExceptionNested() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2)=a2", new String[] {"RowLimitException(a2) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimitexception function cannot be nested within another function */
+    @Test public void testXMLQueryRowLimitExceptionNested2() {
+        helpValidate("SELECT * FROM vm1.doc1 where convert(RowLimitException(a2), string)=a2", new String[] {"convert(RowLimitException(a2), string) = a2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimitexception function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimitException3a() {
+        helpValidate("SELECT * FROM vm1.doc1 where RowLimitException(a2) = convert(a2, integer)", new String[] {"RowLimitException(a2) = convert(a2, integer)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimitexception function operand must be nonnegative integer */
+    @Test public void testXMLQueryRowLimitException3b() {
+        helpValidate("SELECT * FROM vm1.doc1 where convert(a2, integer) = RowLimitException(a2)", new String[] {"convert(a2, integer) = RowLimitException(a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    /** rowlimitexception function arg must be an element symbol */
+    @Test public void testXMLQueryRowLimitException4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception('x') = 3", new String[] {"rowlimitexception('x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimitexception function arg must be an element symbol */
+    @Test public void testXMLQueryRowLimitException5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(concat(a2, 'x')) = 3", new String[] {"rowlimitexception(concat(a2, 'x'))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /** rowlimitexception function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitExceptionConjunct() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 OR a2 = 'x'", new String[] {"(rowlimitexception(a2) = 3) OR (a2 = 'x')"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    /** rowlimitexception function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitExceptionCompound() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND a2 = 'x'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    /** rowlimitexception function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitExceptionCompound2() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND concat(a2, 'y') = 'xy'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    /** rowlimitexception function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitExceptionCompound3() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND (concat(a2, 'y') = 'xy' OR concat(a2, 'y') = 'zy')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    /** each rowlimitexception function arg must be a single conjunct */
+    @Test public void testXMLQueryRowLimitExceptionCompound4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(c2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    /** 
+     * It doesn't make sense to use rowlimitexception twice on same element, but can't be
+     * invalidated here (could be two different elements but in the same 
+     * mapping class - needs to be caught in XMLPlanner)
+     */
+    @Test public void testXMLQueryRowLimitExceptionCompound5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = 3 AND rowlimitexception(a2) = 4", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria() {
+        helpValidate("SELECT * FROM vm1.doc1 where not(rowlimitexception(a2) = 3)", new String[] {"NOT (rowlimitexception(a2) = 3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria2() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (3)", new String[] {"rowlimitexception(a2) IN (3)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria3() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) LIKE 'x'", new String[] {"rowlimitexception(a2) LIKE 'x'"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria4() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IS NULL", new String[] {"rowlimitexception(a2) IS NULL"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria5() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) IN (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END", new String[] {"2 = CASE WHEN rowlimitexception(a2) = 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria6a() {
+        helpValidate("SELECT * FROM vm1.doc1 where 2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END", new String[] {"2 = CASE rowlimitexception(a2) WHEN 2 THEN 2 END"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria7() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) BETWEEN 2 AND 3", new String[] {"rowlimitexception(a2) BETWEEN 2 AND 3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    @Test public void testXMLQueryRowLimitExceptionInvalidCriteria8() {
+        helpValidate("SELECT * FROM vm1.doc1 where rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)", new String[] {"rowlimitexception(a2) = ANY (SELECT e0 FROM vTest.vMap)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+    
+    /** using rowlimit pseudo-function in non-XML query is invalid */
+    @Test public void testNonXMLQueryRowLimitException() {        
+        helpValidate("SELECT e2 FROM vTest.vMap WHERE rowlimitexception(e1) = 2", new String[] {"rowlimitexception(e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }    
+
+    /** using context pseudo-function in non-XML query is invalid */
+    @Test public void testNonXMLQueryContextOperator() {        
+        helpValidate("SELECT e2 FROM vTest.vMap WHERE context(e1, e1) = 2", new String[] {"context(e1, e1)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }      
+    
+    @Test public void testValidateSubquery1() {        
+        helpValidate("SELECT e2 FROM (SELECT e2 FROM vTest.vMap WHERE e2 = 'a') AS x", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidateSubquery2() {        
+        helpValidate("SELECT e2 FROM (SELECT e3 FROM vTest.vMap) AS x, vTest.vMap WHERE e2 = 'a'", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testValidateSubquery3() {        
+        helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    }
+
+    @Test public void testValidateUnionWithSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 union all SELECT e3 FROM test.group union all select * from (SELECT e1 FROM test.group) as subquery1", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateExistsSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE EXISTS (SELECT e2 FROM vTest.vMap WHERE e2 = 'a')", new String[] {}, exampleMetadata()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testValidateScalarSubquery() {        
+        helpValidate("SELECT e2, (SELECT e1 FROM vTest.vMap WHERE e2 = '3') FROM test.group2", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$ 
+    }
+
+    @Test public void testValidateAnyCompareSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE e1 < ANY (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateAllCompareSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE e1 = ALL (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateSomeCompareSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE e1 <= SOME (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateCompareSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE e1 >= (SELECT e1 FROM test.group WHERE e1 = 1)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateInClauseSubquery() {        
+        helpValidate("SELECT e2 FROM test.group2 WHERE e1 IN (SELECT e1 FROM test.group)", new String[] {"e1"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testValidateExec1() {
+        helpValidate("EXEC pm1.sq1()", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    }
+    
+	// valid variable declared
+    @Test public void testCreateUpdateProcedure4() {
+        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 =0;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+        
+		helpValidateProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// validating criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
+    @Test public void testCreateUpdateProcedure5() {
+        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 + "if(HAS CRITERIA ON (vm1.g1.E1, vm1.g1.e1))\n";                 //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n";         //$NON-NLS-1$
+        procedure = procedure + "END\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$
+        
+		helpValidateProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// validating Translate CRITERIA, elements on it should be virtual group elements
+    @Test public void testCreateUpdateProcedure7() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1, vm1.g1.e1 = 2);\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$
+        
+		helpValidateProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// ROWS_UPDATED not assigned
+    @Test public void testCreateUpdateProcedure8() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e1 from pm1.g1 where Translate CRITERIA WITH (vm1.g1.e1 = 1);\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+        
+		helpFailProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+
+	// validating AssignmentStatement, more than one project symbol on the
+	// command
+    @Test public void testCreateUpdateProcedure11() {
+        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.e2, 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$
+        
+		helpFailProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// validating AssignmentStatement, more than one project symbol on the
+	// command
+    @Test public void testCreateUpdateProcedure12() {
+        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.e2, 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$
+        
+		helpFailProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// TranslateCriteria on criteria of the if statement
+    @Test public void testCreateUpdateProcedure13() {
+        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 + "if(TRANSLATE CRITERIA ON (vm1.g1.e1) WITH (vm1.g1.e1 = 1))\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\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$
+        
+		helpFailProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// INPUT ised in command
+    @Test public void testCreateUpdateProcedure16() {
+        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 + "INSERT into pm1.g1 (pm1.g1.e1) values (INPUT.e1);\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$
+        
+		helpValidateProcedure(procedure, userUpdateStr,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// elements on with should be on ON
+    @Test public void testCreateUpdateProcedure17() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1, pm1.g2 where TRANSLATE = CRITERIA ON (e1) WITH (e1 = 20, e2 = 30);\n"; //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED =0;\n";         //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
+        
+		helpFailProcedure(procedure, userQuery,
+									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// failure, aggregate function in query transform
+    @Test public void testCreateUpdateProcedure18() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\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$
+
+		helpFailProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+    
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// failure, aggregate function in query transform
+    @Test public void testCreateUpdateProcedure18a() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA ON (e3);\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 y like '%a' and e3= 1"; //$NON-NLS-1$
+
+		helpFailProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+	// failure, translated criteria elements not present on groups of command
+    @Test public void testCreateUpdateProcedure19() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE = CRITERIA ON (x, y);\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 y= 1"; //$NON-NLS-1$
+
+		helpFailProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+	
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testCreateUpdateProcedure20() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (y = e2+1);\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 y= 1"; //$NON-NLS-1$
+
+		helpValidateProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testCreateUpdateProcedure25() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE > CRITERIA ON (y);\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 y > 1"; //$NON-NLS-1$
+
+		helpFailProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testCreateUpdateProcedure26() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g1.e2 from pm1.g1 where TRANSLATE = CRITERIA WITH (e3 = e2+1);\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$
+
+		helpValidateProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
+    @Test public void testCreateUpdateProcedure27() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE integer var1;\n"; //$NON-NLS-1$
+        procedure = procedure + "Select pm1.g2.e2 from pm1.g2 where TRANSLATE LIKE CRITERIA WITH (y = e2+1);\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 y = 1"; //$NON-NLS-1$
+
+		helpValidateProcedure(procedure, userQuery, 
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+
+    // using aggregate function within a procedure - defect #8394
+    @Test public void testCreateUpdateProcedure31() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string MaxTran;\n"; //$NON-NLS-1$
+        procedure = procedure + "MaxTran = SELECT MAX(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 userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+        helpValidateProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+	// assigning null values to known datatype variable
+	@Test public void testCreateUpdateProcedure32() {
+		String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+		procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+		procedure = procedure + "DECLARE string var;\n"; //$NON-NLS-1$
+		procedure = procedure + "var = null;\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 y = 1"; //$NON-NLS-1$
+
+		helpValidateProcedure(procedure, userQuery,
+				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+	}
+    
+    @Test public void testDefect13643() {
+        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 + "LOOP ON (SELECT * FROM pm1.g1) AS myCursor\n"; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "var1 = SELECT COUNT(*) FROM myCursor;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\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 y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery, 
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testValidHaving() {
+        helpValidate(
+            "SELECT intnum " + //$NON-NLS-1$
+            "FROM bqt1.smalla " + //$NON-NLS-1$
+            "GROUP BY intnum " + //$NON-NLS-1$
+            "HAVING SUM(floatnum) > 1",  //$NON-NLS-1$
+            new String[] { }, FakeMetadataFactory.exampleBQTCached());
+    } 
+    
+    @Test public void testValidHaving2() {
+        String sql =  "SELECT intkey FROM bqt1.smalla WHERE intkey = 1 " + //$NON-NLS-1$
+            "GROUP BY intkey HAVING intkey = 1";         //$NON-NLS-1$
+        helpValidate(sql, new String[] {}, FakeMetadataFactory.exampleBQTCached());
+    } 
+    
+    @Test public void testVirtualProcedure(){
+          helpValidate("EXEC pm1.vsp1()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    }
+        
+    @Test public void testSelectWithNoFrom() {        
+        helpValidate("SELECT 5", new String[] {}, exampleMetadata()); //$NON-NLS-1$
+    }
+    
+    @Test public void testSelectIntoTempGroup() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+        helpValidateProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    /**
+     * Defect 24346
+     */
+    @Test public void testInvalidSelectIntoTempGroup() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3, e4 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    /**
+     * Defect 24346 with type mismatch
+     */
+    @Test public void testInvalidSelectIntoTempGroup1() {
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "create local temporary table #myTempTable (e1 integer);\n";         //$NON-NLS-1$
+        procedure = procedure + "SELECT e1 INTO #myTempTable FROM pm1.g2;\n";         //$NON-NLS-1$
+        procedure = procedure + "ROWS_UPDATED = SELECT COUNT(*) FROM #myTempTable;\n"; //$NON-NLS-1$
+        procedure = procedure + "END\n"; //$NON-NLS-1$
+
+        String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+
+    
+    @Test public void testSelectIntoPhysicalGroup() {
+        helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
+
+        helpValidateProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
+        helpValidate("SELECT e0, e1, e2 INTO test.group3 FROM test.group2", new String[] {"test.group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testSelectIntoElementsNotUpdateable() {
+    	helpValidate("SELECT e0, e1, e2 INTO test.group2 FROM test.group3", new String[] {"test.group2"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidSelectIntoTooManyElements() {
+    	helpValidate("SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testInvalidSelectIntoTooFewElements() {
+    	helpValidate("SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testInvalidSelectIntoIncorrectTypes() {
+        helpValidate("SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testSelectIntoWithStar() {
+        helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    }
+    
+    @Test public void testInvalidSelectIntoWithStar() {
+        helpValidate("SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1", new String[] {"SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1;\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 y = 1"; //$NON-NLS-1$
+
+        helpFailProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testSelectIntoVirtualGroup() {
+        helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        
+        String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
+        procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
+        procedure = procedure + "SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2;\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 y = 1"; //$NON-NLS-1$
+
+        helpValidateProcedure(procedure, userQuery,
+                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+    }
+    
+    @Test public void testVirtualProcedure2(){
+          helpValidate("EXEC pm1.vsp13()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    }
+
+    //procedure that has another procedure in the transformation
+    @Test public void testVirtualProcedure3(){
+        helpValidate("EXEC pm1.vsp27()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    }
+    
+    @Test public void testNonEmbeddedSubcommand_defect11000() {        
+        helpValidate("SELECT e0 FROM vTest.vGroup", new String[0], exampleMetadata()); //$NON-NLS-1$ 
+    }
+    
+    @Test public void testValidateObjectInComparison() throws Exception {
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE ObjectValue = 5";   //$NON-NLS-1$
+        ValidatorReport report = helpValidate(sql, new String[] {"ObjectValue = 5"}, FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+        assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: ObjectValue = 5.", report.toString()); //$NON-NLS-1$
+    }
+
+    @Test public void testValidateAssignmentWithFunctionOnParameter_InServer() throws Exception{
+        String sql = "EXEC pm1.vsp36(5)";  //$NON-NLS-1$
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        Command command = new QueryParser().parseCommand(sql);
+        QueryResolver.resolveCommand(command, metadata);
+        
+        // Validate
+        ValidatorReport report = Validator.validate(command, metadata); 
+        assertEquals(0, report.getItems().size());                      
+    }
+
+    @Test public void testDefect9917() throws Exception{
+    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        String sql = "SELECT lookup('pm1.g1', 'e1a', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+        Command command = new QueryParser().parseCommand(sql);
+        try{
+        	QueryResolver.resolveCommand(command, metadata); 
+        	fail("Did not get exception"); //$NON-NLS-1$
+        }catch(QueryResolverException e){
+        	//expected
+        }
+        
+        sql = "SELECT lookup('pm1.g1a', 'e1', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
+        command = new QueryParser().parseCommand(sql);
+        try{
+        	QueryResolver.resolveCommand(command, metadata); 
+        	fail("Did not get exception"); //$NON-NLS-1$
+        }catch(QueryResolverException e){
+        	//expected
+        }
+    }
+    
+    @Test public void testLookupKeyElementComparable() throws Exception {
+    	QueryMetadataInterface metadata = exampleMetadata2();
+        String sql = "SELECT lookup('test.group', 'e2', 'e3', convert(e2, blob)) AS x FROM test.group"; //$NON-NLS-1$
+        Command command = QueryParser.getQueryParser().parseCommand(sql);
+    	QueryResolver.resolveCommand(command, metadata); 
+        
+        ValidatorReport report = Validator.validate(command, metadata);
+        assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used as LOOKUP key columns: test.\"group\".e3.", report.toString()); //$NON-NLS-1$
+    }
+    
+    @Test public void testDefect12107() throws Exception{
+    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        String sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e2', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
+        Command command = helpResolve(sql, metadata);
+        sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
+        command = helpResolve(sql, metadata);
+        ValidatorReport report = Validator.validate(command, metadata);
+        assertEquals("The aggregate function SUM cannot be used with non-numeric expressions: SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2))", report.toString()); //$NON-NLS-1$
+    }
+    
+    private ValidatorReport helpValidateInModeler(String procName, String procSql, QueryMetadataInterface metadata) throws Exception {
+        Command command = new QueryParser().parseCommand(procSql);
+        
+        GroupSymbol group = new GroupSymbol(procName);
+        Map externalMetadata = getStoredProcedureExternalMetadata(group, metadata);
+        QueryResolver.resolveCommand(command, externalMetadata, metadata, AnalysisRecord.createNonRecordingRecord());
+        
+        // Validate
+        return Validator.validate(command, metadata);         
+    }
+
+    @Test public void testValidateDynamicCommandWithNonTempGroup_InModeler() throws Exception{
+        // SQL is same as pm1.vsp36() in example1 
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into pm1.g3; END";  //$NON-NLS-1$        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
+        assertEquals(1, report.getItems().size());
+        assertEquals("Wrong number of elements being SELECTed INTO the target table. Expected 4 elements, but was 1.", report.toString()); //$NON-NLS-1$
+    }
+    
+    @Test public void testDynamicDupUsing() throws Exception {
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into #temp using id=1, id=2; END";  //$NON-NLS-1$        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
+        assertEquals(1, report.getItems().size());
+        assertEquals("Elements cannot appear more than once in a SET or USING clause.  The following elements are duplicated: [DVARS.id]", report.toString()); //$NON-NLS-1$
+    }    
+    
+    @Test public void testValidateAssignmentWithFunctionOnParameter_InModeler() throws Exception{
+        // SQL is same as pm1.vsp36() in example1 
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END";  //$NON-NLS-1$        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
+        assertEquals(0, report.getItems().size());                      
+    }
+    
+    @Test public void testDefect12533() {
+        String sql = "SELECT BQT1.SmallA.DateValue, BQT2.SmallB.ObjectValue FROM BQT1.SmallA, BQT2.SmallB " +  //$NON-NLS-1$
+            "WHERE BQT1.SmallA.DateValue = BQT2.SmallB.DateValue AND BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue " + //$NON-NLS-1$
+            "AND BQT1.SmallA.IntKey < 30 AND BQT2.SmallB.IntKey < 30 ORDER BY BQT1.SmallA.DateValue"; //$NON-NLS-1$
+        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        
+        // Validate
+        helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata);  //$NON-NLS-1$ 
+    }
+
+    @Test public void testDefect16772() throws Exception{
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
+        assertEquals("Expected report to have no validation failures", false, report.hasItems()); //$NON-NLS-1$
+    }
+	
+	@Test public void testDefect14886() throws Exception{        
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN END";  //$NON-NLS-1$        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        Command command = new QueryParser().parseCommand(sql);
+        QueryResolver.resolveCommand(command, new HashMap(), metadata, AnalysisRecord.createNonRecordingRecord());
+        
+        // Validate
+        ValidatorReport report = Validator.validate(command, metadata); 
+        // Validate
+        assertEquals(1, report.getItems().size());  	
+    }
+	
+    @Test public void testDefect21389() throws Exception{        
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; INSERT INTO #temptable (e1) VALUES ('a'); END"; //$NON-NLS-1$      
+        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
+        e1.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
+        
+        Command command = new QueryParser().parseCommand(sql);
+        QueryResolver.resolveCommand(command, new HashMap(), metadata, AnalysisRecord.createNonRecordingRecord());
+        
+        // Validate
+        ValidatorReport report = Validator.validate(command, metadata); 
+        // Validate
+        assertEquals(0, report.getItems().size());      
+    }
+    
+    @Test public void testMakeNotDep() {
+        helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKENOTDEP group2, group3", new String[0], exampleMetadata()); //$NON-NLS-1$
+    }
+    @Test public void testInvalidMakeNotDep() {
+    	helpValidate("select group2.e1, group3.e2 from group2, group3 WHERE group2.e0 = group3.e0 OPTION MAKEDEP group2 MAKENOTDEP group2, group3", new String[] {"OPTION MAKEDEP group2 MAKENOTDEP group2, group3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidLimit() {
+        helpValidate("SELECT * FROM pm1.g1 LIMIT -5", new String[] {"LIMIT -5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidLimit_Offset() {
+    	helpValidate("SELECT * FROM pm1.g1 LIMIT -1, 100", new String[] {"LIMIT -1, 100"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    /**
+     * Test case 4237.  This test simulates the way the modeler transformation 
+     * panel uses the query resolver and validator to validate a transformation for
+     * a virtual procedure.  The modeler has to supply external metadata for the 
+     * virtual procedure group and parameter names (simulated in this test).
+     * 
+     * This virtual procedure calls a physical stored procedure directly.  
+     */
+    @Test public void testCase4237() {
+
+        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
+        Map externalMetadata = helpCreateCase4237ExternalMetadata(metadata);
+        
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"; //$NON-NLS-1$ 
+        Command command = helpResolve(sql, metadata, externalMetadata);
+        helpRunValidator(command, new String[0], metadata);
+    }
+
+    /**
+     * This test was already working before the case was logged, due for some reason
+     * to the exec() statement being inside an inline view.  This is a control test. 
+     */
+    @Test public void testCase4237InlineView() {
+
+        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
+        Map externalMetadata = helpCreateCase4237ExternalMetadata(metadata);
+        
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM (EXEC pm1.sp(vm1.sp.in1)) AS FOO; END"; //$NON-NLS-1$ 
+        Command command = helpResolve(sql, metadata, externalMetadata);
+        helpRunValidator(command, new String[0], metadata);
+    }    
+    
+    /**
+     * Set up external metadata describing the virtual procedure and parameters 
+     * @param metadata FakeMetadataFacade
+     * @return external metadata Map
+     */
+    private Map helpCreateCase4237ExternalMetadata(FakeMetadataFacade metadata) {
+        GroupSymbol sp = new GroupSymbol("vm1.sp");//$NON-NLS-1$ 
+        FakeMetadataObject spObj = metadata.getStore().findObject("vm1.sp", FakeMetadataObject.PROCEDURE);//$NON-NLS-1$ 
+        sp.setMetadataID(spObj);
+        ElementSymbol param = new ElementSymbol("vm1.sp.in1");//$NON-NLS-1$ 
+        List paramIDs = (List)spObj.getProperty(FakeMetadataObject.Props.PARAMS);
+        Iterator i = paramIDs.iterator();
+        while (i.hasNext()) {
+            FakeMetadataObject paramID = (FakeMetadataObject)i.next();
+            if (paramID.getProperty(FakeMetadataObject.Props.DIRECTION).equals(new Integer(ParameterInfo.IN))) {
+                param.setMetadataID(paramID);
+                break;
+            }
+        }
+        
+        Map externalMetadata = new HashMap();
+        externalMetadata.put(sp, Arrays.asList(new ElementSymbol[] { param }));
+ 
+        return externalMetadata;
+    }
+
+    /**
+     * Create fake metadata for this case.  Need a physical stored procedure and
+     * a virtual stored procedure which calls the physical one. 
+     * @return
+     */
+    private FakeMetadataFacade helpCreateCase4237VirtualProcedureMetadata() {
+        FakeMetadataObject physicalModel = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
+        FakeMetadataObject resultSet = FakeMetadataFactory.createResultSet("pm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        FakeMetadataObject returnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, resultSet);  //$NON-NLS-1$
+        FakeMetadataObject inParam = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        FakeMetadataObject storedProcedure = FakeMetadataFactory.createStoredProcedure("pm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { returnParam, inParam }), "pm1.sp2");  //$NON-NLS-1$ //$NON-NLS-2$
+        
+        FakeMetadataObject virtualModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
+        FakeMetadataObject virtualResultSet = FakeMetadataFactory.createResultSet("vm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        FakeMetadataObject virtualReturnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, virtualResultSet);  //$NON-NLS-1$
+        FakeMetadataObject virtualInParam = FakeMetadataFactory.createParameter("in1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        QueryNode queryNode = new QueryNode("vm1.sp", "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        FakeMetadataObject virtualStoredProcedure = FakeMetadataFactory.createVirtualProcedure("vm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { virtualReturnParam, virtualInParam }), queryNode);  //$NON-NLS-1$
+                
+        FakeMetadataStore store = new FakeMetadataStore();
+        store.addObject(physicalModel);
+        store.addObject(resultSet);
+        store.addObject(storedProcedure);
+        store.addObject(virtualModel);
+        store.addObject(virtualResultSet);
+        store.addObject(virtualStoredProcedure);
+        return new FakeMetadataFacade(store);
+    }       
+    
+    @Test public void testSelectIntoWithNull() {
+        helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    }
+    
+    @Test public void testCreateWithNonSortablePrimaryKey() {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        Command command = helpResolve("create local temporary table x (column1 string, column2 clob, primary key (column2))", metadata); //$NON-NLS-1$
+        helpRunValidator(command, new String[] {"column2"}, FakeMetadataFactory.example1Cached()); 
+    }
+        
+    @Test public void testDropNonTemporary() {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
+        helpRunValidator(command, new String[] {command.toString()}, FakeMetadataFactory.example1Cached()); 
+    }
+    
+    @Test public void testNestedContexts() {
+        helpValidate("SELECT * FROM vm1.doc1 where context(a0, context(a0, a2))='x'", new String[] {"context(a0, context(a0, a2))"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testValidContextElement() {
+        helpValidate("SELECT * FROM vm1.doc1 where context(1, a2)='x'", new String[] {"context(1, a2)"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInsertIntoVirtualWithQuery() throws Exception {
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        Command command = helpResolve("insert into vm1.g1 select 1, 2, true, 3", metadata); //$NON-NLS-1$
+        ValidatorReport report = Validator.validate(command, metadata);
+        assertTrue(report.getItems().isEmpty());
+    }
+    
+    @Test public void testDynamicIntoDeclaredTemp() throws Exception {
+        StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE  ") //$NON-NLS-1$
+                                .append("BEGIN\n") //$NON-NLS-1$
+                                .append("CREATE LOCAL TEMPORARY TABLE x (column1 string);") //$NON-NLS-1$
+                                .append("execute string 'SELECT e1 FROM pm1.g2' as e1 string INTO x;\n") //$NON-NLS-1$
+                                .append("select column1 from x;\n") //$NON-NLS-1$
+                                .append("END\n"); //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
+        assertEquals(report.toString(), 0, report.getItems().size());
+    }
+    
+    @Test public void testVariablesGroupSelect() {
+        String procedure = "CREATE VIRTUAL PROCEDURE "; //$NON-NLS-1$
+        procedure += "BEGIN\n"; //$NON-NLS-1$
+        procedure += "DECLARE integer VARIABLES.var1 = 1;\n"; //$NON-NLS-1$
+        procedure += "select * from variables;\n"; //$NON-NLS-1$
+        procedure += "END\n"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        Command command = helpResolve(procedure, metadata);
+        helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
+    }
+    
+    @Test public void testClobEquals() {
+        TestValidator.helpValidate("SELECT * FROM test.group where e4 = '1'", new String[] {"e4 = '1'"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ 
+    }
+    
+    /**
+     *  Should not fail since the update changing set is not really criteria
+     */
+    @Test public void testUpdateWithClob() {
+        TestValidator.helpValidate("update test.group set e4 = ?", new String[] {}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ 
+    }
+
+    @Test public void testBlobLessThan() {
+        TestValidator.helpValidate("SELECT * FROM test.group where e3 < ?", new String[] {"e3 < ?"}, TestValidator.exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$ 
+    }
+    
+	@Test public void testValidateCompare2() {        
+        helpValidate("SELECT e2 FROM test.group WHERE e4 IS NULL", new String[] {}, exampleMetadata2()); //$NON-NLS-1$ 
+	}
+
+	@Test public void testValidateCompare3() {        
+        helpValidate("SELECT e2 FROM test.group WHERE e4 IN ('a')", new String[] {"e4 IN ('a')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+    @Test public void testValidateCompare5() {        
+        helpValidate("SELECT e2 FROM test.group WHERE e4 BETWEEN '1' AND '2'", new String[] {"e4 BETWEEN '1' AND '2'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+	@Test public void testValidateCompareInHaving1() {        
+        helpValidate("SELECT e1 FROM test.group GROUP BY e1 HAVING convert(e1, clob) = 'a'", new String[] {"convert(e1, clob) = 'a'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	@Test public void testValidateNoExpressionName() {        
+        helpValidate("SELECT xmlelement(name a, xmlattributes('1'))", new String[] {"XMLATTRIBUTES('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	@Test public void testValidateNoExpressionName1() {        
+        helpValidate("SELECT xmlforest('1')", new String[] {"XMLFOREST('1')"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+    @Test public void testXpathValueValid_defect15088() {
+        String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', 'a/b/c')"; //$NON-NLS-1$
+        helpValidate(userSql, new String[] {}, FakeMetadataFactory.exampleBQTCached());        
+    }
+
+    @Test public void testXpathValueInvalid_defect15088() throws Exception {
+        String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"; //$NON-NLS-1$
+        helpValidate(userSql, new String[] {"xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"}, FakeMetadataFactory.exampleBQTCached());
+    }
+    
+    @Test public void testTextTableNegativeWidth() {        
+        helpValidate("SELECT * from texttable(null columns x string width -1) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH -1) AS x"}, RealMetadataFactory.exampleBQTCached()); 
+	}
+    
+    @Test public void testTextTableNoWidth() {        
+        helpValidate("SELECT * from texttable(null columns x string width 1, y integer) as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1, y integer) AS x"}, RealMetadataFactory.exampleBQTCached()); 
+	}
+
+    @Test public void testTextTableInvalidDelimiter() {        
+        helpValidate("SELECT * from texttable(null columns x string width 1 DELIMITER 'z') as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1 DELIMITER 'z') AS x"}, RealMetadataFactory.exampleBQTCached()); 
+	}
+    
+    @Test public void testXMLNamespaces() {
+    	helpValidate("select xmlforest(xmlnamespaces(no default, default 'http://foo'), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES(NO DEFAULT, DEFAULT 'http://foo')"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXMLNamespacesReserved() {
+    	helpValidate("select xmlforest(xmlnamespaces('http://foo' as xmlns), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS xmlns)"}, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testXMLTablePassingMultipleContext() {
+    	helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>'), xmlparse(DOCUMENT '<b/>')) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>'), XMLPARSE(DOCUMENT '<b/>')) AS x"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Ignore("this is actually handled by saxon and will show up during resolving")
+    @Test public void testXMLTablePassingSameName() {
+    	helpValidate("select * from pm1.g1, xmltable('/' passing {x '<a/>'} as a, {x '<b/>'} as a) as x", new String[] {"xmltable('/' passing e1, e1 || 'x') as x"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXMLTablePassingContextType() {
+    	helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXMLTableMultipleOrdinals() {
+    	helpValidate("select * from pm1.g1, xmltable('/' passing XMLPARSE(DOCUMENT '<a/>') columns x for ordinality, y for ordinality) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS x FOR ORDINALITY, y FOR ORDINALITY) AS x"}, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testXMLTableContextRequired() {
+    	helpValidate("select * from xmltable('/a/b' passing convert('<a/>', xml) as a columns x for ordinality, c integer path '.') as x", new String[] {"XMLTABLE('/a/b' PASSING convert('<a/>', xml) AS a COLUMNS x FOR ORDINALITY, c integer PATH '.') AS x"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXMLQueryPassingContextType() {
+    	helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testQueryString() {
+    	helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXmlNameValidation() throws Exception {
+    	helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, FakeMetadataFactory.example1Cached());
+    }
+
+    @Test public void testXmlParse() throws Exception {
+    	helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testDecode() throws Exception {
+    	helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, FakeMetadataFactory.example1Cached());
+    }
+    
+    @Test public void testValidateXMLAGG() {        
+        helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+    
+    @Test public void testValidateBooleanAgg() {        
+        helpValidate("SELECT EVERY(e1) from pm1.g1", new String[] {"EVERY(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+    
+    @Test public void testValidateStatAgg() {        
+        helpValidate("SELECT stddev_pop(distinct e2) from pm1.g1", new String[] {"STDDEV_POP(DISTINCT e2)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+    
+    @Test public void testValidateScalarSubqueryTooManyColumns() {        
+        helpValidate("SELECT e2, (SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidIntoSubquery() {
+    	helpValidate("SELECT e2, (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidIntoSubquery1() {
+    	helpValidate("SELECT e2 FROM pm1.g2 WHERE EXISTS (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidIntoSubquery2() {
+    	helpValidate("SELECT * FROM (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') x", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testInvalidIntoSubquery3() {
+    	helpValidate("SELECT e2 FROM pm1.g2 WHERE e2 in (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testInvalidIntoSubquery4() throws Exception {
+        StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE\n") //$NON-NLS-1$
+                                .append("BEGIN\n") //$NON-NLS-1$
+                                .append("loop on (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') as x\n") //$NON-NLS-1$
+                                .append("BEGIN\nSELECT 1;\nEND\nSELECT 1\n;END\n"); //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
+        examineReport(procedure, new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, report);
+    }
+    
+    @Test public void testDisallowUpdateOnMultisourceElement() throws Exception {  
+    	Set<String> models = new HashSet<String>();
+    	models.add("pm1");
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", "UPDATE PM1.G1 set SOURCE_NAME='blah'", new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
+        assertEquals(report.toString(), 1, report.getItems().size());
+    }
+    
+    @Test public void testDisallowProjectIntoMultiSource() throws Exception {  
+    	Set<String> models = new HashSet<String>();
+    	models.add("pm1");
+        helpValidate("insert into pm1.g1 select * from pm1.g1", new String[] {"pm1.g1"}, new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
+    }
+    
+    @Test public void testTextAggEncoding() throws Exception {
+    	helpValidate("select textagg(for e1 encoding abc) from pm1.g1", new String[] {"TEXTAGG(FOR e1 ENCODING abc)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    }
+    
+    @Test public void testTextAggHeader() throws Exception {
+    	helpValidate("select textagg(for e1 || 1 HEADER) from pm1.g1", new String[] {"TEXTAGG(FOR (e1 || 1) HEADER)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml
===================================================================
--- trunk/hibernate-dialect/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/hibernate-dialect/pom.xml (from rev 2777, trunk/hibernate-dialect/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/hibernate-dialect/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/jboss-integration/pom.xml
===================================================================
--- trunk/jboss-integration/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/jboss-integration/pom.xml (from rev 2777, trunk/jboss-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/jboss-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,726 +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.adminapi.jboss;
-
-import java.io.InputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.jboss.deployers.spi.management.ManagementView;
-import org.jboss.deployers.spi.management.deploy.DeploymentManager;
-import org.jboss.managed.api.ComponentType;
-import org.jboss.managed.api.DeploymentTemplateInfo;
-import org.jboss.managed.api.ManagedComponent;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.plugins.DefaultFieldsImpl;
-import org.jboss.managed.plugins.WritethroughManagedPropertyImpl;
-import org.jboss.metatype.api.types.CollectionMetaType;
-import org.jboss.metatype.api.types.EnumMetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.CollectionValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.MetaValueFactory;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.jboss.profileservice.spi.NoSuchDeploymentException;
-import org.jboss.profileservice.spi.ProfileKey;
-import org.jboss.virtual.VFS;
-import org.teiid.adminapi.AdminComponentException;
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.AdminObject;
-import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.CacheStatistics;
-import org.teiid.adminapi.PropertyDefinition;
-import org.teiid.adminapi.Request;
-import org.teiid.adminapi.Session;
-import org.teiid.adminapi.Transaction;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.WorkerPoolStatistics;
-import org.teiid.adminapi.VDB.ConnectionType;
-import org.teiid.adminapi.impl.CacheStatisticsMetadata;
-import org.teiid.adminapi.impl.PropertyDefinitionMetadata;
-import org.teiid.adminapi.impl.RequestMetadata;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.TransactionMetadata;
-import org.teiid.adminapi.impl.TranslatorMetaData;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
-import org.teiid.jboss.IntegrationPlugin;
-
-public class Admin implements org.teiid.adminapi.Admin, Serializable {	
-	private static final String CONNECTOR_PREFIX = "connector-"; //$NON-NLS-1$
-	private static final ProfileKey DEFAULT_PROFILE_KEY = new ProfileKey(ProfileKey.DEFAULT);
-	private static final long serialVersionUID = 7081309086056911304L;
-	private static ComponentType VDBTYPE = new ComponentType("teiid", "vdb");//$NON-NLS-1$ //$NON-NLS-2$
-	private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp");//$NON-NLS-1$ //$NON-NLS-2$	
-	private static String DQPNAME = "RuntimeEngineDeployer"; //$NON-NLS-1$
-	private static ComponentType TRANSLATOR_TYPE = new ComponentType("teiid", "translator");//$NON-NLS-1$ //$NON-NLS-2$
-	
-	private static final String[] DS_TYPES = {"XA", "NoTx", "LocalTx"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	private static final String[] CF_TYPES = {"NoTx", "Tx"}; //$NON-NLS-1$ //$NON-NLS-2$
-	
-	
-	private ManagementView view;
-	private DeploymentManager deploymentMgr;
-	
-	
-	static {
-		VFS.init();
-	}
-	
-	public Admin(ManagementView view, DeploymentManager deployMgr) {
-		this.view = view;
-		this.view.load();
-				
-		this.deploymentMgr =  deployMgr;
-        try {
-        	this.deploymentMgr.loadProfile(DEFAULT_PROFILE_KEY);
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
-	}
-	
-	private ManagementView getView() throws AdminProcessingException {
-		if (this.view == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("admin_connection_closed")); //$NON-NLS-1$
-		}
-		this.view.load();
-		return this.view;
-	}
-	
-	private DeploymentManager getDeploymentManager() throws AdminProcessingException{
-		if (this.deploymentMgr == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("admin_connection_closed")); //$NON-NLS-1$
-		}
-		return this.deploymentMgr;
-	}
-	
-	public void close() {
-		this.view = null;
-		this.deploymentMgr = null;
-	}	
-	
-//	private DQPManagement getDQPManagement() throws Exception {
-//		final ManagedComponent mc = getView().getComponent(DQPManagementView.class.getName(), DQPTYPE);	
-//		
-//		return (DQPManagement)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {DQPManagement.class}, new InvocationHandler() {
-//			@Override
-//			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
-//				
-//				MetaValue value = ManagedUtil.executeOperation(mc, method.getName());
-//				Class returnType = method.getReturnType();
-//				if (returnType.equals(Void.class)) {
-//					return value;
-//				}
-//				return null;
-//			}
-//		});
-//	}
-	
-	@Override
-	public Collection<Translator> getTranslators() throws AdminException {
-		ArrayList<Translator> factories = new ArrayList<Translator>();
-		try {
-			Set<ManagedComponent> mcSet = getView().getComponentsForType(TRANSLATOR_TYPE);
-			for (ManagedComponent mc:mcSet) {
-				factories.add(AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class));
-			}
-		} catch (Exception e) {
-			throw new AdminComponentException(e);
-		}
-		return factories;
-	}
-
-	@Override
-	public Translator getTranslator(String deployedName) throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(deployedName, TRANSLATOR_TYPE);
-			if (mc != null) {
-				return AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class);
-			}
-			return null;
-		} catch(Exception e) {
-			throw new AdminProcessingException(e.getMessage(), e);
-		}
-	}
-
-    boolean matches(String regEx, String value) {
-        regEx = regEx.replaceAll(AdminObject.ESCAPED_WILDCARD, ".*"); //$NON-NLS-1$ 
-        regEx = regEx.replaceAll(AdminObject.ESCAPED_DELIMITER, ""); //$NON-NLS-1$ 
-        return value.matches(regEx);
-    }	
-    
-	@Override
-	public void deployVDB(String fileName, InputStream vdb) throws AdminException {
-		if (!fileName.endsWith(".vdb") && !fileName.endsWith("-vdb.xml")) {//$NON-NLS-1$ //$NON-NLS-2$
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("bad_vdb_extension")); //$NON-NLS-1$
-		}
-		ManagedUtil.deployArchive(getDeploymentManager(), fileName, vdb, false);
-	}
-
-	
-	@Override
-	public void deleteVDB(String vdbName, int vdbVersion) throws AdminException {
-		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
-		if (mc != null) {
-			ManagedUtil.removeArchive(getDeploymentManager(), mc.getDeployment().getName());
-		}
-	}	
-	
-	@Override
-	public VDB getVDB(String vdbName, int vdbVersion) throws AdminException{
-		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
-		if (mc != null) {
-			return AdminObjectBuilder.buildAO(mc, VDBMetaData.class);
-		}
-		return null;
-	}
-	
-	private ManagedComponent getVDBManagedComponent(String vdbName, int vdbVersion) throws AdminException{
-		try {
-			Set<ManagedComponent> vdbComponents = getView().getComponentsForType(VDBTYPE);
-			for (ManagedComponent mc: vdbComponents) {
-				String name = ManagedUtil.getSimpleValue(mc, "name", String.class);//$NON-NLS-1$
-			    int version = ManagedUtil.getSimpleValue(mc, "version", Integer.class);//$NON-NLS-1$
-			    if (name.equalsIgnoreCase(vdbName) && version == vdbVersion) {
-			    	return mc;
-			    }
-			}
-			return null;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}	
-	}
-	
-	@Override
-	public Set<VDB> getVDBs() throws AdminException {
-		try {
-			Set<VDB> vdbs = new HashSet<VDB>();
-			Set<ManagedComponent> vdbComponents = getView().getComponentsForType(VDBTYPE);
-			for (ManagedComponent mc: vdbComponents) {
-				vdbs.add(AdminObjectBuilder.buildAO(mc, VDBMetaData.class));
-			}
-			return vdbs;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}
-	}
-		
-	@Override
-	public Collection<Session> getSessions() throws AdminException {
-		try {
-			Collection<Session> sessionList = new ArrayList<Session>();
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			MetaValue value = ManagedUtil.executeOperation(mc, "getActiveSessions");//$NON-NLS-1$
-			MetaValue[] sessions = ((CollectionValueSupport)value).getElements();
-			for (MetaValue mv:sessions) {
-				sessionList.add((SessionMetadata)MetaValueFactory.getInstance().unwrap(mv, SessionMetadata.class));
-			}
-			return sessionList;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}		
-	}
-	
-	@Override
-	public void terminateSession(String sessionId) throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			ManagedUtil.executeOperation(mc, "terminateSession", SimpleValueSupport.wrap(sessionId));//$NON-NLS-1$
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}     	
-	}	
-	
-	@Override
-    public Collection<Request> getRequests() throws AdminException {
-		try {
-			Collection<Request> requestList = new ArrayList<Request>();
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			MetaValue value = ManagedUtil.executeOperation(mc, "getRequests");//$NON-NLS-1$
-			MetaValue[] requests = ((CollectionValueSupport)value).getElements();			
-			for (MetaValue mv:requests) {
-				requestList.add((RequestMetadata)MetaValueFactory.getInstance().unwrap(mv, RequestMetadata.class));
-			}
-			return requestList;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}    	
-    }
-    
-	@Override
-    public Collection<Request> getRequestsForSession(String sessionId) throws AdminException {
-		try {
-			Collection<Request> requestList = new ArrayList<Request>();
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			MetaValue value = ManagedUtil.executeOperation(mc, "getRequestsForSession", SimpleValueSupport.wrap(sessionId));//$NON-NLS-1$
-			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
-			for (MetaValue mv:requests) {
-				requestList.add((RequestMetadata)MetaValueFactory.getInstance().unwrap(mv, RequestMetadata.class));
-			}
-			return requestList;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}     	
-    }
-	
-	@Override
-	public void cancelRequest(String sessionId, long executionId) throws AdminException{
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			ManagedUtil.executeOperation(mc, "cancelRequest", SimpleValueSupport.wrap(sessionId), SimpleValueSupport.wrap(executionId));//$NON-NLS-1$
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}     	
-	}
-	
-	@Override
-	public Collection<String> getCacheTypes() throws AdminException {
-		try {
-			Collection<String> requestList = new ArrayList<String>();
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			MetaValue value = ManagedUtil.executeOperation(mc, "getCacheTypes");//$NON-NLS-1$
-			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
-			for (MetaValue mv:requests) {
-				requestList.add(ManagedUtil.stringValue(mv));
-			}
-			return requestList;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} 
-	}	
-	
-	@Override
-	public void clearCache(String cacheType) throws AdminException{
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			ManagedUtil.executeOperation(mc, "clearCache", SimpleValueSupport.wrap(cacheType));//$NON-NLS-1$
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} 		
-	}
-	
-	@Override
-	public Collection<Transaction> getTransactions() throws AdminException {
-		try {
-			Collection<Transaction> txnList = new ArrayList<Transaction>();
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			MetaValue value = ManagedUtil.executeOperation(mc, "getTransactions");//$NON-NLS-1$
-			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
-			for (MetaValue mv:requests) {
-				txnList.add((TransactionMetadata)MetaValueFactory.getInstance().unwrap(mv, TransactionMetadata.class));
-			}
-			return txnList;
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}  
-	}	
-	
-	@Override
-	public void terminateTransaction(String xid) throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			ManagedUtil.executeOperation(mc, "terminateTransaction", MetaValueFactory.getInstance().create(xid));//$NON-NLS-1$
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} 	
-	}
-	
-	@Override
-	public WorkerPoolStatistics getWorkerPoolStats() throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);
-			MetaValue value = ManagedUtil.executeOperation(mc, "getWorkerPoolStatistics");//$NON-NLS-1$
-			return (WorkerPoolStatistics)MetaValueFactory.getInstance().unwrap(value, WorkerPoolStatisticsMetadata.class);	
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}
-	}	
-	
-	
-	@Override
-	public Collection<PropertyDefinition> getTemplatePropertyDefinitions(String templateName) throws AdminException {
-		
-		DeploymentTemplateInfo info = null;
-		
-		try {
-			
-			try {
-				info = getView().getTemplate(templateName);
-			} catch (Exception e) {
-				// ignore..
-			}
-			
-			if (info == null && !templateName.startsWith(TranslatorMetaData.TRANSLATOR_PREFIX)) {
-				info = getView().getTemplate(TranslatorMetaData.TRANSLATOR_PREFIX+templateName);
-			}
-			if(info == null) {
-				throw new AdminProcessingException(IntegrationPlugin.Util.getString("template_not_found", templateName)); //$NON-NLS-1$
-			}
-			
-			ArrayList<PropertyDefinition> props = new ArrayList<PropertyDefinition>();
-			Map<String, ManagedProperty> propertyMap = info.getProperties();
-			
-			for (ManagedProperty mp:propertyMap.values()) {
-					if (!includeInTemplate(mp)) {
-						continue;
-					}
-					PropertyDefinitionMetadata p = new PropertyDefinitionMetadata();
-					p.setName(mp.getName());
-					p.setDescription(mp.getDescription());
-					p.setDisplayName(mp.getMappedName());
-					if (mp.getDefaultValue() != null) {
-						p.setDefaultValue(((SimpleValueSupport)mp.getDefaultValue()).getValue());
-					}
-					p.setPropertyTypeClassName(mp.getMetaType().getTypeName());
-					p.setModifiable(!mp.isReadOnly());
-					
-					if (mp.getField("masked", Boolean.class) != null) {//$NON-NLS-1$
-						p.setMasked(mp.getField("masked", Boolean.class));//$NON-NLS-1$
-					}
-					else {
-						p.setMasked(false);
-					}
-					
-					if (mp.getField("advanced", Boolean.class) != null) {//$NON-NLS-1$
-						p.setAdvanced(mp.getField("advanced", Boolean.class));//$NON-NLS-1$
-					}
-					else {
-						p.setAdvanced(true);
-					}
-					if (mp.getLegalValues() != null) {
-						HashSet<String> values = new HashSet<String>();
-						for (MetaValue value:mp.getLegalValues()) {
-							values.add(ManagedUtil.stringValue(value));
-						}
-						p.setAllowedValues(values);
-					}
-					
-					p.setRequired(mp.isMandatory());
-					props.add(p);
-			};
-			return props;
-		} catch (NoSuchDeploymentException e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} catch(Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}
-	}	
-	
-    private boolean includeInTemplate(ManagedProperty mp) {
-    	Boolean teiidProperty = mp.getField("teiid-property", Boolean.class);//$NON-NLS-1$
-		if ( teiidProperty != null && teiidProperty.booleanValue()) {
-			return true;
-		}
-		if (mp.isMandatory() && mp.getDefaultValue() == null) {
-			return true;
-		}
-		return false;
-	}
-    
-    @Override
-    public void changeVDBConnectionType(String vdbName, int vdbVersion,
-    		ConnectionType type) throws AdminException {
-    	ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
-		if (mc == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-    	ManagedProperty connectionTypeProperty = mc.getProperty("connectionType"); //$NON-NLS-1$
-    	if (connectionTypeProperty != null) {
-    		connectionTypeProperty.setValue(ManagedUtil.wrap(new EnumMetaType(ConnectionType.values()), type != null ?type.name():ConnectionType.BY_VERSION.name()));
-    	}
-		
-		try {
-			getView().updateComponent(mc);
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}
-    }
-
-	@Override
-	public void assignToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String translatorName, String dsName) throws AdminException {
-		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
-		if (mc == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-		ManagedProperty mp = mc.getProperty("models");//$NON-NLS-1$
-		List<ManagedObject> models = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
-		ManagedObject managedModel = null;
-		if (models != null && !models.isEmpty()) {
-			for(ManagedObject mo:models) {
-				String name = ManagedUtil.getSimpleValue(mo, "name", String.class); //$NON-NLS-1$
-				if (modelName.equals(name)) {
-					managedModel = mo;
-				}
-			}		
-		}
-		
-		if (managedModel == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("model_not_found", modelName, vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-        ManagedProperty sourceMappings = managedModel.getProperty("sourceMappings");//$NON-NLS-1$
-        if (sourceMappings != null){
-            List<ManagedObject> mappings = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(sourceMappings.getValue());
-            for (ManagedObject mo:mappings) {
-                String sName = ManagedUtil.getSimpleValue(mo, "name", String.class);//$NON-NLS-1$
-                if (sName.equals(sourceName)) {
-                	
-                	ManagedProperty translatorProperty = mo.getProperty("translatorName"); //$NON-NLS-1$
-                	if (translatorProperty == null) {
-                		translatorProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("translatorName")); //$NON-NLS-1$
-                	}
-                	translatorProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, translatorName));
-                	
-                	// set the jndi name for the ds.
-                	ManagedProperty jndiProperty = mo.getProperty("connectionJndiName"); //$NON-NLS-1$
-                	if (jndiProperty == null) {
-                		jndiProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("connectionJndiName")); //$NON-NLS-1$
-                	}
-                	jndiProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, dsName));
-                }
-            }
-        } else {
-        	//TODO: this can be in the default situation when no source mappings are specified
-        	throw new AdminProcessingException(IntegrationPlugin.Util.getString("sourcename_not_found", sourceName, vdbName, vdbVersion, modelName)); //$NON-NLS-1$
-        }
-        
-		try {
-			getView().updateComponent(mc);
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}		        
-	}
-
-	private void manageRoleToDataPolicy(String vdbName, int vdbVersion, String policyName, String role, boolean add)  throws AdminException {
-		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
-		if (mc == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-		ManagedProperty mp = mc.getProperty("dataPolicies");//$NON-NLS-1$
-		List<ManagedObject> policies = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
-		ManagedObject managedPolicy = null;
-		if (policies != null && !policies.isEmpty()) {
-			for(ManagedObject mo:policies) {
-				String name = ManagedUtil.getSimpleValue(mo, "name", String.class); //$NON-NLS-1$
-				if (policyName.equals(name)) {
-					managedPolicy = mo;
-				}
-			}		
-		}
-		
-		if (managedPolicy == null) {
-			throw new AdminProcessingException(IntegrationPlugin.Util.getString("policy_not_found", policyName, vdbName, vdbVersion)); //$NON-NLS-1$
-		}
-		
-		if (role != null) {
-	        ManagedProperty mappedRoleNames = managedPolicy.getProperty("mappedRoleNames");//$NON-NLS-1$
-	        CollectionValueSupport roleCollection = (CollectionValueSupport)mappedRoleNames.getValue();
-	        ArrayList<MetaValue> modifiedRoleNames = new ArrayList<MetaValue>();
-	        if (roleCollection != null) {
-		        MetaValue[] roleNames = roleCollection.getElements();
-		        for (MetaValue mv:roleNames) {
-		        	String existing = (String)((SimpleValueSupport)mv).getValue();
-		        	if (!existing.equals(role)) {
-		        		modifiedRoleNames.add(mv);
-		        	}
-		        }
-	        }
-	        else {
-	        	roleCollection = new CollectionValueSupport(new CollectionMetaType("java.util.List", SimpleMetaType.STRING)); //$NON-NLS-1$
-	        	mappedRoleNames.setValue(roleCollection);
-	        }
-	        
-	        if (add) {
-	        	modifiedRoleNames.add(ManagedUtil.wrap(SimpleMetaType.STRING, role));
-	        }
-	        
-	        roleCollection.setElements(modifiedRoleNames.toArray(new MetaValue[modifiedRoleNames.size()]));
-		} else {
-			ManagedProperty anyAuthenticated = managedPolicy.getProperty("anyAuthenticated");//$NON-NLS-1$
-			anyAuthenticated.setValue(SimpleValueSupport.wrap(add));
-		}
-		
-		try {
-			getView().updateComponent(mc);
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}		
-	}
-
-	
-	@Override
-	public void addDataRoleMapping(String vdbName, int vdbVersion, String policyName, String role)  throws AdminException {
-		manageRoleToDataPolicy(vdbName, vdbVersion, policyName, role, true);
-	}
-	
-	@Override
-	public void removeDataRoleMapping(String vdbName, int vdbVersion, String policyName, String role)  throws AdminException{
-		manageRoleToDataPolicy(vdbName, vdbVersion, policyName, role, false);
-	}	
-	
-	@Override
-	public void setAnyAuthenticatedForDataRole(String vdbName, int vdbVersion,
-			String dataRole, boolean anyAuthenticated) throws AdminException {
-		manageRoleToDataPolicy(vdbName, vdbVersion, dataRole, null, anyAuthenticated);
-	}
-
-	@Override
-	public void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
-			ManagedUtil.executeOperation(mc, "mergeVDBs",  //$NON-NLS-1$
-					SimpleValueSupport.wrap(sourceVDBName), 
-					SimpleValueSupport.wrap(sourceVDBVersion), 
-					SimpleValueSupport.wrap(targetVDBName), 
-					SimpleValueSupport.wrap(targetVDBVersion));
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}   		
-	}
-
-	private ManagedComponent getDatasource(String deployedName) throws Exception {
-		ManagedComponent mc = null;
-		for (String type:DS_TYPES) {
-			ComponentType ct = new ComponentType("DataSource", type); //$NON-NLS-1$
-			mc = getView().getComponent(deployedName, ct);
-			if (mc != null) {
-				return mc;
-			}				
-		}		
-		for (String type:CF_TYPES) {
-			ComponentType ct = new ComponentType("ConnectionFactory", type); //$NON-NLS-1$
-			mc = getView().getComponent(deployedName, ct);
-			if (mc != null) {
-				return mc;
-			}				
-		}
-		return mc;
-	}
-	
-	
-	@Override
-	public void createDataSource(String deploymentName, String templateName, Properties properties) throws AdminException {
-		try {
-			ManagedComponent mc = getDatasource(deploymentName);
-			if (mc != null) {
-				throw new AdminProcessingException(IntegrationPlugin.Util.getString("datasource_exists",deploymentName)); //$NON-NLS-1$;	
-			}
-			
-			DeploymentTemplateInfo info = getView().getTemplate(templateName);
-			if(info == null) {
-				throw new AdminProcessingException(IntegrationPlugin.Util.getString("datasource_template_not_found", templateName)); //$NON-NLS-1$
-			}
-			
-			// template properties specific to the template
-			Map<String, ManagedProperty> propertyMap = info.getProperties();
-			
-			// walk through the supplied properties and assign properly to template
-			for (String key:properties.stringPropertyNames()) {
-				ManagedProperty mp = propertyMap.get(key);
-				if (mp != null) {
-					String value = properties.getProperty(key);
-					if (!ManagedUtil.sameValue(mp.getDefaultValue(), value)){
-						mp.setValue(SimpleValueSupport.wrap(value));
-					}
-				}
-			}
-			info.getProperties().get("jndi-name").setValue(SimpleValueSupport.wrap(deploymentName)); //$NON-NLS-1$
-			getView().applyTemplate(deploymentName, info);
-		} catch (NoSuchDeploymentException e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} catch(Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		} 
-	}
-
-	@Override
-	public void deleteDataSource(String deployedName) throws AdminException {
-		try {
-			ManagedComponent mc = getDatasource(deployedName);
-			if (mc != null) {
-				ManagedUtil.removeArchive(getDeploymentManager(),mc.getDeployment().getName());
-			}
-		} catch (Exception e) {
-			throw new AdminComponentException(e);
-		}
-	}
-
-	@Override
-	public Collection<String> getDataSourceNames() throws AdminException {
-		ArrayList<String> names = new ArrayList<String>();
-		try {
-			for (String type:DS_TYPES) {
-				ComponentType ct = new ComponentType("DataSource", type); //$NON-NLS-1$
-				Set<ManagedComponent> mcs = getView().getComponentsForType(ct);
-				for (ManagedComponent mc:mcs) {
-					names.add(((SimpleValue)mc.getProperty("jndi-name").getValue()).getValue().toString()); //$NON-NLS-1$
-				}
-			}		
-			for (String type:CF_TYPES) {
-				ComponentType ct = new ComponentType("ConnectionFactory", type); //$NON-NLS-1$
-				Set<ManagedComponent> mcs = getView().getComponentsForType(ct);
-				for (ManagedComponent mc:mcs) {
-					names.add(((SimpleValue)mc.getProperty("jndi-name").getValue()).getValue().toString()); //$NON-NLS-1$
-				}			
-			}
-		} catch (Exception e) {
-			throw new AdminComponentException(e);
-		}
-		return names;
-	}
-	
-	@Override
-	public Set<String> getDataSourceTemplateNames() throws AdminException{
-		Set<String> names = getView().getTemplateNames();
-		HashSet<String> matched = new HashSet<String>();
-		for(String name:names) {
-			if (name.startsWith(CONNECTOR_PREFIX)) {
-				matched.add(name);
-			}
-		}
-		return matched;		
-	}
-
-	@Override
-	public CacheStatistics getCacheStats(String cacheType) throws AdminException {
-		try {
-			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);
-			MetaValue value = ManagedUtil.executeOperation(mc, "getCacheStatistics", SimpleValueSupport.wrap(cacheType));//$NON-NLS-1$
-			return (CacheStatistics)MetaValueFactory.getInstance().unwrap(value, CacheStatisticsMetadata.class);	
-		} catch (Exception e) {
-			throw new AdminComponentException(e.getMessage(), e);
-		}
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java (from rev 2774, trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,737 @@
+/*
+ * 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.adminapi.jboss;
+
+import java.io.InputStream;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.deployers.spi.management.deploy.DeploymentManager;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedComponent;
+import org.jboss.managed.api.ManagedObject;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.DefaultFieldsImpl;
+import org.jboss.managed.plugins.WritethroughManagedPropertyImpl;
+import org.jboss.metatype.api.types.CollectionMetaType;
+import org.jboss.metatype.api.types.EnumMetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.MetaValueFactory;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.profileservice.spi.NoSuchDeploymentException;
+import org.jboss.profileservice.spi.ProfileKey;
+import org.jboss.virtual.VFS;
+import org.teiid.adminapi.AdminComponentException;
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.AdminObject;
+import org.teiid.adminapi.AdminProcessingException;
+import org.teiid.adminapi.CacheStatistics;
+import org.teiid.adminapi.PropertyDefinition;
+import org.teiid.adminapi.Request;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.Transaction;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.WorkerPoolStatistics;
+import org.teiid.adminapi.VDB.ConnectionType;
+import org.teiid.adminapi.impl.CacheStatisticsMetadata;
+import org.teiid.adminapi.impl.PropertyDefinitionMetadata;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.TransactionMetadata;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
+import org.teiid.jboss.IntegrationPlugin;
+
+public class Admin implements org.teiid.adminapi.Admin, Serializable {	
+	private static final String CONNECTOR_PREFIX = "connector-"; //$NON-NLS-1$
+	private static final ProfileKey DEFAULT_PROFILE_KEY = new ProfileKey(ProfileKey.DEFAULT);
+	private static final long serialVersionUID = 7081309086056911304L;
+	private static ComponentType VDBTYPE = new ComponentType("teiid", "vdb");//$NON-NLS-1$ //$NON-NLS-2$
+	private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp");//$NON-NLS-1$ //$NON-NLS-2$	
+	private static String DQPNAME = "RuntimeEngineDeployer"; //$NON-NLS-1$
+	private static ComponentType TRANSLATOR_TYPE = new ComponentType("teiid", "translator");//$NON-NLS-1$ //$NON-NLS-2$
+	
+	private static final String[] DS_TYPES = {"XA", "NoTx", "LocalTx"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	private static final String[] CF_TYPES = {"NoTx", "Tx"}; //$NON-NLS-1$ //$NON-NLS-2$
+	
+	
+	private ManagementView view;
+	private DeploymentManager deploymentMgr;
+	
+	
+	static {
+		VFS.init();
+	}
+	
+	public Admin(ManagementView view, DeploymentManager deployMgr) {
+		this.view = view;
+		this.view.load();
+				
+		this.deploymentMgr =  deployMgr;
+        try {
+        	this.deploymentMgr.loadProfile(DEFAULT_PROFILE_KEY);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+	}
+	
+	private ManagementView getView() throws AdminProcessingException {
+		if (this.view == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("admin_connection_closed")); //$NON-NLS-1$
+		}
+		this.view.load();
+		return this.view;
+	}
+	
+	private DeploymentManager getDeploymentManager() throws AdminProcessingException{
+		if (this.deploymentMgr == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("admin_connection_closed")); //$NON-NLS-1$
+		}
+		return this.deploymentMgr;
+	}
+	
+	public void close() {
+		this.view = null;
+		this.deploymentMgr = null;
+	}	
+	
+//	private DQPManagement getDQPManagement() throws Exception {
+//		final ManagedComponent mc = getView().getComponent(DQPManagementView.class.getName(), DQPTYPE);	
+//		
+//		return (DQPManagement)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {DQPManagement.class}, new InvocationHandler() {
+//			@Override
+//			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+//				
+//				MetaValue value = ManagedUtil.executeOperation(mc, method.getName());
+//				Class returnType = method.getReturnType();
+//				if (returnType.equals(Void.class)) {
+//					return value;
+//				}
+//				return null;
+//			}
+//		});
+//	}
+	
+	@Override
+	public Collection<Translator> getTranslators() throws AdminException {
+		ArrayList<Translator> factories = new ArrayList<Translator>();
+		try {
+			Set<ManagedComponent> mcSet = getView().getComponentsForType(TRANSLATOR_TYPE);
+			for (ManagedComponent mc:mcSet) {
+				factories.add(AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class));
+			}
+		} catch (Exception e) {
+			throw new AdminComponentException(e);
+		}
+		return factories;
+	}
+
+	@Override
+	public Translator getTranslator(String deployedName) throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(deployedName, TRANSLATOR_TYPE);
+			if (mc != null) {
+				return AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class);
+			}
+			return null;
+		} catch(Exception e) {
+			throw new AdminProcessingException(e.getMessage(), e);
+		}
+	}
+
+    boolean matches(String regEx, String value) {
+        regEx = regEx.replaceAll(AdminObject.ESCAPED_WILDCARD, ".*"); //$NON-NLS-1$ 
+        regEx = regEx.replaceAll(AdminObject.ESCAPED_DELIMITER, ""); //$NON-NLS-1$ 
+        return value.matches(regEx);
+    }	
+    
+	@Override
+	public void deployVDB(String fileName, InputStream vdb) throws AdminException {
+		if (!fileName.endsWith(".vdb") && !fileName.endsWith("-vdb.xml")) {//$NON-NLS-1$ //$NON-NLS-2$
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("bad_vdb_extension")); //$NON-NLS-1$
+		}
+		ManagedUtil.deployArchive(getDeploymentManager(), fileName, vdb, false);
+	}
+
+	
+	@Override
+	public void deleteVDB(String vdbName, int vdbVersion) throws AdminException {
+		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+		if (mc != null) {
+			ManagedUtil.removeArchive(getDeploymentManager(), mc.getDeployment().getName());
+		}
+	}	
+	
+	@Override
+	public VDB getVDB(String vdbName, int vdbVersion) throws AdminException{
+		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+		if (mc != null) {
+			return AdminObjectBuilder.buildAO(mc, VDBMetaData.class);
+		}
+		return null;
+	}
+	
+	private ManagedComponent getVDBManagedComponent(String vdbName, int vdbVersion) throws AdminException{
+		try {
+			Set<ManagedComponent> vdbComponents = getView().getComponentsForType(VDBTYPE);
+			for (ManagedComponent mc: vdbComponents) {
+				String name = ManagedUtil.getSimpleValue(mc, "name", String.class);//$NON-NLS-1$
+			    int version = ManagedUtil.getSimpleValue(mc, "version", Integer.class);//$NON-NLS-1$
+			    if (name.equalsIgnoreCase(vdbName) && version == vdbVersion) {
+			    	return mc;
+			    }
+			}
+			return null;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}	
+	}
+	
+	@Override
+	public Set<VDB> getVDBs() throws AdminException {
+		try {
+			Set<VDB> vdbs = new HashSet<VDB>();
+			Set<ManagedComponent> vdbComponents = getView().getComponentsForType(VDBTYPE);
+			for (ManagedComponent mc: vdbComponents) {
+				vdbs.add(AdminObjectBuilder.buildAO(mc, VDBMetaData.class));
+			}
+			return vdbs;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}
+	}
+		
+	@Override
+	public Collection<Session> getSessions() throws AdminException {
+		try {
+			Collection<Session> sessionList = new ArrayList<Session>();
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			MetaValue value = ManagedUtil.executeOperation(mc, "getActiveSessions");//$NON-NLS-1$
+			MetaValue[] sessions = ((CollectionValueSupport)value).getElements();
+			for (MetaValue mv:sessions) {
+				sessionList.add((SessionMetadata)MetaValueFactory.getInstance().unwrap(mv, SessionMetadata.class));
+			}
+			return sessionList;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}		
+	}
+	
+	@Override
+	public void terminateSession(String sessionId) throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "terminateSession", SimpleValueSupport.wrap(sessionId));//$NON-NLS-1$
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}     	
+	}	
+	
+	@Override
+    public Collection<Request> getRequests() throws AdminException {
+		try {
+			Collection<Request> requestList = new ArrayList<Request>();
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			MetaValue value = ManagedUtil.executeOperation(mc, "getRequests");//$NON-NLS-1$
+			MetaValue[] requests = ((CollectionValueSupport)value).getElements();			
+			for (MetaValue mv:requests) {
+				requestList.add((RequestMetadata)MetaValueFactory.getInstance().unwrap(mv, RequestMetadata.class));
+			}
+			return requestList;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}    	
+    }
+    
+	@Override
+    public Collection<Request> getRequestsForSession(String sessionId) throws AdminException {
+		try {
+			Collection<Request> requestList = new ArrayList<Request>();
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			MetaValue value = ManagedUtil.executeOperation(mc, "getRequestsForSession", SimpleValueSupport.wrap(sessionId));//$NON-NLS-1$
+			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
+			for (MetaValue mv:requests) {
+				requestList.add((RequestMetadata)MetaValueFactory.getInstance().unwrap(mv, RequestMetadata.class));
+			}
+			return requestList;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}     	
+    }
+	
+	@Override
+	public void cancelRequest(String sessionId, long executionId) throws AdminException{
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "cancelRequest", SimpleValueSupport.wrap(sessionId), SimpleValueSupport.wrap(executionId));//$NON-NLS-1$
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}     	
+	}
+	
+	@Override
+	public Collection<String> getCacheTypes() throws AdminException {
+		try {
+			Collection<String> requestList = new ArrayList<String>();
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			MetaValue value = ManagedUtil.executeOperation(mc, "getCacheTypes");//$NON-NLS-1$
+			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
+			for (MetaValue mv:requests) {
+				requestList.add(ManagedUtil.stringValue(mv));
+			}
+			return requestList;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} 
+	}	
+	
+	@Override
+	public void clearCache(String cacheType) throws AdminException{
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "clearCache", SimpleValueSupport.wrap(cacheType));//$NON-NLS-1$
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} 		
+	}
+	
+	@Override
+	public void clearCache(String cacheType, String vdbName, int version) throws AdminException{
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "clearCache", SimpleValueSupport.wrap(cacheType), //$NON-NLS-1$
+					SimpleValueSupport.wrap(vdbName), SimpleValueSupport.wrap(version));
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} 		
+	}
+	
+	@Override
+	public Collection<Transaction> getTransactions() throws AdminException {
+		try {
+			Collection<Transaction> txnList = new ArrayList<Transaction>();
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			MetaValue value = ManagedUtil.executeOperation(mc, "getTransactions");//$NON-NLS-1$
+			MetaValue[] requests = ((CollectionValueSupport)value).getElements();
+			for (MetaValue mv:requests) {
+				txnList.add((TransactionMetadata)MetaValueFactory.getInstance().unwrap(mv, TransactionMetadata.class));
+			}
+			return txnList;
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}  
+	}	
+	
+	@Override
+	public void terminateTransaction(String xid) throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "terminateTransaction", MetaValueFactory.getInstance().create(xid));//$NON-NLS-1$
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} 	
+	}
+	
+	@Override
+	public WorkerPoolStatistics getWorkerPoolStats() throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);
+			MetaValue value = ManagedUtil.executeOperation(mc, "getWorkerPoolStatistics");//$NON-NLS-1$
+			return (WorkerPoolStatistics)MetaValueFactory.getInstance().unwrap(value, WorkerPoolStatisticsMetadata.class);	
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}
+	}	
+	
+	
+	@Override
+	public Collection<PropertyDefinition> getTemplatePropertyDefinitions(String templateName) throws AdminException {
+		
+		DeploymentTemplateInfo info = null;
+		
+		try {
+			
+			try {
+				info = getView().getTemplate(templateName);
+			} catch (Exception e) {
+				// ignore..
+			}
+			
+			if (info == null && !templateName.startsWith(TranslatorMetaData.TRANSLATOR_PREFIX)) {
+				info = getView().getTemplate(TranslatorMetaData.TRANSLATOR_PREFIX+templateName);
+			}
+			if(info == null) {
+				throw new AdminProcessingException(IntegrationPlugin.Util.getString("template_not_found", templateName)); //$NON-NLS-1$
+			}
+			
+			ArrayList<PropertyDefinition> props = new ArrayList<PropertyDefinition>();
+			Map<String, ManagedProperty> propertyMap = info.getProperties();
+			
+			for (ManagedProperty mp:propertyMap.values()) {
+					if (!includeInTemplate(mp)) {
+						continue;
+					}
+					PropertyDefinitionMetadata p = new PropertyDefinitionMetadata();
+					p.setName(mp.getName());
+					p.setDescription(mp.getDescription());
+					p.setDisplayName(mp.getMappedName());
+					if (mp.getDefaultValue() != null) {
+						p.setDefaultValue(((SimpleValueSupport)mp.getDefaultValue()).getValue());
+					}
+					p.setPropertyTypeClassName(mp.getMetaType().getTypeName());
+					p.setModifiable(!mp.isReadOnly());
+					
+					if (mp.getField("masked", Boolean.class) != null) {//$NON-NLS-1$
+						p.setMasked(mp.getField("masked", Boolean.class));//$NON-NLS-1$
+					}
+					else {
+						p.setMasked(false);
+					}
+					
+					if (mp.getField("advanced", Boolean.class) != null) {//$NON-NLS-1$
+						p.setAdvanced(mp.getField("advanced", Boolean.class));//$NON-NLS-1$
+					}
+					else {
+						p.setAdvanced(true);
+					}
+					if (mp.getLegalValues() != null) {
+						HashSet<String> values = new HashSet<String>();
+						for (MetaValue value:mp.getLegalValues()) {
+							values.add(ManagedUtil.stringValue(value));
+						}
+						p.setAllowedValues(values);
+					}
+					
+					p.setRequired(mp.isMandatory());
+					props.add(p);
+			};
+			return props;
+		} catch (NoSuchDeploymentException e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} catch(Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}
+	}	
+	
+    private boolean includeInTemplate(ManagedProperty mp) {
+    	Boolean teiidProperty = mp.getField("teiid-property", Boolean.class);//$NON-NLS-1$
+		if ( teiidProperty != null && teiidProperty.booleanValue()) {
+			return true;
+		}
+		if (mp.isMandatory() && mp.getDefaultValue() == null) {
+			return true;
+		}
+		return false;
+	}
+    
+    @Override
+    public void changeVDBConnectionType(String vdbName, int vdbVersion,
+    		ConnectionType type) throws AdminException {
+    	ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+		if (mc == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+    	ManagedProperty connectionTypeProperty = mc.getProperty("connectionType"); //$NON-NLS-1$
+    	if (connectionTypeProperty != null) {
+    		connectionTypeProperty.setValue(ManagedUtil.wrap(new EnumMetaType(ConnectionType.values()), type != null ?type.name():ConnectionType.BY_VERSION.name()));
+    	}
+		
+		try {
+			getView().updateComponent(mc);
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}
+    }
+
+	@Override
+	public void assignToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String translatorName, String dsName) throws AdminException {
+		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+		if (mc == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+		ManagedProperty mp = mc.getProperty("models");//$NON-NLS-1$
+		List<ManagedObject> models = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
+		ManagedObject managedModel = null;
+		if (models != null && !models.isEmpty()) {
+			for(ManagedObject mo:models) {
+				String name = ManagedUtil.getSimpleValue(mo, "name", String.class); //$NON-NLS-1$
+				if (modelName.equals(name)) {
+					managedModel = mo;
+				}
+			}		
+		}
+		
+		if (managedModel == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("model_not_found", modelName, vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+        ManagedProperty sourceMappings = managedModel.getProperty("sourceMappings");//$NON-NLS-1$
+        if (sourceMappings != null){
+            List<ManagedObject> mappings = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(sourceMappings.getValue());
+            for (ManagedObject mo:mappings) {
+                String sName = ManagedUtil.getSimpleValue(mo, "name", String.class);//$NON-NLS-1$
+                if (sName.equals(sourceName)) {
+                	
+                	ManagedProperty translatorProperty = mo.getProperty("translatorName"); //$NON-NLS-1$
+                	if (translatorProperty == null) {
+                		translatorProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("translatorName")); //$NON-NLS-1$
+                	}
+                	translatorProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, translatorName));
+                	
+                	// set the jndi name for the ds.
+                	ManagedProperty jndiProperty = mo.getProperty("connectionJndiName"); //$NON-NLS-1$
+                	if (jndiProperty == null) {
+                		jndiProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("connectionJndiName")); //$NON-NLS-1$
+                	}
+                	jndiProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, dsName));
+                }
+            }
+        } else {
+        	//TODO: this can be in the default situation when no source mappings are specified
+        	throw new AdminProcessingException(IntegrationPlugin.Util.getString("sourcename_not_found", sourceName, vdbName, vdbVersion, modelName)); //$NON-NLS-1$
+        }
+        
+		try {
+			getView().updateComponent(mc);
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}		        
+	}
+
+	private void manageRoleToDataPolicy(String vdbName, int vdbVersion, String policyName, String role, boolean add)  throws AdminException {
+		ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
+		if (mc == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("vdb_not_found", vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+		ManagedProperty mp = mc.getProperty("dataPolicies");//$NON-NLS-1$
+		List<ManagedObject> policies = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
+		ManagedObject managedPolicy = null;
+		if (policies != null && !policies.isEmpty()) {
+			for(ManagedObject mo:policies) {
+				String name = ManagedUtil.getSimpleValue(mo, "name", String.class); //$NON-NLS-1$
+				if (policyName.equals(name)) {
+					managedPolicy = mo;
+				}
+			}		
+		}
+		
+		if (managedPolicy == null) {
+			throw new AdminProcessingException(IntegrationPlugin.Util.getString("policy_not_found", policyName, vdbName, vdbVersion)); //$NON-NLS-1$
+		}
+		
+		if (role != null) {
+	        ManagedProperty mappedRoleNames = managedPolicy.getProperty("mappedRoleNames");//$NON-NLS-1$
+	        CollectionValueSupport roleCollection = (CollectionValueSupport)mappedRoleNames.getValue();
+	        ArrayList<MetaValue> modifiedRoleNames = new ArrayList<MetaValue>();
+	        if (roleCollection != null) {
+		        MetaValue[] roleNames = roleCollection.getElements();
+		        for (MetaValue mv:roleNames) {
+		        	String existing = (String)((SimpleValueSupport)mv).getValue();
+		        	if (!existing.equals(role)) {
+		        		modifiedRoleNames.add(mv);
+		        	}
+		        }
+	        }
+	        else {
+	        	roleCollection = new CollectionValueSupport(new CollectionMetaType("java.util.List", SimpleMetaType.STRING)); //$NON-NLS-1$
+	        	mappedRoleNames.setValue(roleCollection);
+	        }
+	        
+	        if (add) {
+	        	modifiedRoleNames.add(ManagedUtil.wrap(SimpleMetaType.STRING, role));
+	        }
+	        
+	        roleCollection.setElements(modifiedRoleNames.toArray(new MetaValue[modifiedRoleNames.size()]));
+		} else {
+			ManagedProperty anyAuthenticated = managedPolicy.getProperty("anyAuthenticated");//$NON-NLS-1$
+			anyAuthenticated.setValue(SimpleValueSupport.wrap(add));
+		}
+		
+		try {
+			getView().updateComponent(mc);
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}		
+	}
+
+	
+	@Override
+	public void addDataRoleMapping(String vdbName, int vdbVersion, String policyName, String role)  throws AdminException {
+		manageRoleToDataPolicy(vdbName, vdbVersion, policyName, role, true);
+	}
+	
+	@Override
+	public void removeDataRoleMapping(String vdbName, int vdbVersion, String policyName, String role)  throws AdminException{
+		manageRoleToDataPolicy(vdbName, vdbVersion, policyName, role, false);
+	}	
+	
+	@Override
+	public void setAnyAuthenticatedForDataRole(String vdbName, int vdbVersion,
+			String dataRole, boolean anyAuthenticated) throws AdminException {
+		manageRoleToDataPolicy(vdbName, vdbVersion, dataRole, null, anyAuthenticated);
+	}
+
+	@Override
+	public void mergeVDBs(String sourceVDBName, int sourceVDBVersion, String targetVDBName, int targetVDBVersion) throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);	
+			ManagedUtil.executeOperation(mc, "mergeVDBs",  //$NON-NLS-1$
+					SimpleValueSupport.wrap(sourceVDBName), 
+					SimpleValueSupport.wrap(sourceVDBVersion), 
+					SimpleValueSupport.wrap(targetVDBName), 
+					SimpleValueSupport.wrap(targetVDBVersion));
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}   		
+	}
+
+	private ManagedComponent getDatasource(String deployedName) throws Exception {
+		ManagedComponent mc = null;
+		for (String type:DS_TYPES) {
+			ComponentType ct = new ComponentType("DataSource", type); //$NON-NLS-1$
+			mc = getView().getComponent(deployedName, ct);
+			if (mc != null) {
+				return mc;
+			}				
+		}		
+		for (String type:CF_TYPES) {
+			ComponentType ct = new ComponentType("ConnectionFactory", type); //$NON-NLS-1$
+			mc = getView().getComponent(deployedName, ct);
+			if (mc != null) {
+				return mc;
+			}				
+		}
+		return mc;
+	}
+	
+	
+	@Override
+	public void createDataSource(String deploymentName, String templateName, Properties properties) throws AdminException {
+		try {
+			ManagedComponent mc = getDatasource(deploymentName);
+			if (mc != null) {
+				throw new AdminProcessingException(IntegrationPlugin.Util.getString("datasource_exists",deploymentName)); //$NON-NLS-1$;	
+			}
+			
+			DeploymentTemplateInfo info = getView().getTemplate(templateName);
+			if(info == null) {
+				throw new AdminProcessingException(IntegrationPlugin.Util.getString("datasource_template_not_found", templateName)); //$NON-NLS-1$
+			}
+			
+			// template properties specific to the template
+			Map<String, ManagedProperty> propertyMap = info.getProperties();
+			
+			// walk through the supplied properties and assign properly to template
+			for (String key:properties.stringPropertyNames()) {
+				ManagedProperty mp = propertyMap.get(key);
+				if (mp != null) {
+					String value = properties.getProperty(key);
+					if (!ManagedUtil.sameValue(mp.getDefaultValue(), value)){
+						mp.setValue(SimpleValueSupport.wrap(value));
+					}
+				}
+			}
+			info.getProperties().get("jndi-name").setValue(SimpleValueSupport.wrap(deploymentName)); //$NON-NLS-1$
+			getView().applyTemplate(deploymentName, info);
+		} catch (NoSuchDeploymentException e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} catch(Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		} 
+	}
+
+	@Override
+	public void deleteDataSource(String deployedName) throws AdminException {
+		try {
+			ManagedComponent mc = getDatasource(deployedName);
+			if (mc != null) {
+				ManagedUtil.removeArchive(getDeploymentManager(),mc.getDeployment().getName());
+			}
+		} catch (Exception e) {
+			throw new AdminComponentException(e);
+		}
+	}
+
+	@Override
+	public Collection<String> getDataSourceNames() throws AdminException {
+		ArrayList<String> names = new ArrayList<String>();
+		try {
+			for (String type:DS_TYPES) {
+				ComponentType ct = new ComponentType("DataSource", type); //$NON-NLS-1$
+				Set<ManagedComponent> mcs = getView().getComponentsForType(ct);
+				for (ManagedComponent mc:mcs) {
+					names.add(((SimpleValue)mc.getProperty("jndi-name").getValue()).getValue().toString()); //$NON-NLS-1$
+				}
+			}		
+			for (String type:CF_TYPES) {
+				ComponentType ct = new ComponentType("ConnectionFactory", type); //$NON-NLS-1$
+				Set<ManagedComponent> mcs = getView().getComponentsForType(ct);
+				for (ManagedComponent mc:mcs) {
+					names.add(((SimpleValue)mc.getProperty("jndi-name").getValue()).getValue().toString()); //$NON-NLS-1$
+				}			
+			}
+		} catch (Exception e) {
+			throw new AdminComponentException(e);
+		}
+		return names;
+	}
+	
+	@Override
+	public Set<String> getDataSourceTemplateNames() throws AdminException{
+		Set<String> names = getView().getTemplateNames();
+		HashSet<String> matched = new HashSet<String>();
+		for(String name:names) {
+			if (name.startsWith(CONNECTOR_PREFIX)) {
+				matched.add(name);
+			}
+		}
+		return matched;		
+	}
+
+	@Override
+	public CacheStatistics getCacheStats(String cacheType) throws AdminException {
+		try {
+			ManagedComponent mc = getView().getComponent(DQPNAME, DQPTYPE);
+			MetaValue value = ManagedUtil.executeOperation(mc, "getCacheStatistics", SimpleValueSupport.wrap(cacheType));//$NON-NLS-1$
+			return (CacheStatistics)MetaValueFactory.getInstance().unwrap(value, CacheStatisticsMetadata.class);	
+		} catch (Exception e) {
+			throw new AdminComponentException(e.getMessage(), e);
+		}
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,317 +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.adminapi.jboss;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.jboss.deployers.spi.management.deploy.DeploymentManager;
-import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
-import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
-import org.jboss.managed.api.ManagedCommon;
-import org.jboss.managed.api.ManagedOperation;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.metatype.api.types.MapCompositeMetaType;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.CollectionValue;
-import org.jboss.metatype.api.values.EnumValue;
-import org.jboss.metatype.api.values.MapCompositeValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.PropertiesMetaValue;
-import org.jboss.metatype.api.values.SimpleValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
-import org.jboss.profileservice.spi.DeploymentOption;
-import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.core.TeiidRuntimeException;
-import org.teiid.jboss.IntegrationPlugin;
-
-
-public class ManagedUtil {
-	
-	public static boolean sameValue(MetaValue v1, String v2) {
-		if (v1 == null || v2 == null) {
-			return false;
-		}
-		
-		MetaType type = v1.getMetaType();
-		if (v1 instanceof SimpleValue && type instanceof SimpleMetaType) {
-			SimpleMetaType st = (SimpleMetaType)type;
-			SimpleValue sv = wrap(st, v2);
-			return sv.compareTo((SimpleValue)v1) == 0;
-		}
-		return false;
-	}
-	
-	public static boolean sameValue(MetaValue v1, MetaValue v2) {
-		if (v1 == null || v2 == null) {
-			return false;
-		}
-		
-		if (v1 instanceof SimpleValue && v2 instanceof SimpleValue) {
-			return ((SimpleValue)v1).compareTo((SimpleValue)v2) == 0;
-		}
-		return false;
-	}
-
-	public static MapCompositeValueSupport compositeValueMap(Map<String, String> map) {
-		MapCompositeValueSupport metaValue = new MapCompositeValueSupport(SimpleMetaType.STRING);
-		for (String key : map.keySet()) {
-			MetaValue value = SimpleValueSupport.wrap(map.get(key));
-			metaValue.put(key, value);
-		}
-		return metaValue;
-	}	
-	
-	public static String stringValue(MetaValue v1) {
-		if (v1 != null) {
-			MetaType type = v1.getMetaType();
-			if (type instanceof SimpleMetaType) {
-				SimpleValue simple = (SimpleValue)v1;
-				return simple.getValue().toString();
-			}
-			throw new TeiidRuntimeException("Failed to convert value to string value"); //$NON-NLS-1$
-		}
-		return null;
-	}	
-	
-	public static <T> T getSimpleValue(ManagedCommon mc, String prop, Class<T> expectedType) {
-		 ManagedProperty mp = mc.getProperty(prop);
-		 if (mp != null) {
-			 MetaType metaType = mp.getMetaType();
-			 if (metaType.isSimple()) {
-		            SimpleValue simpleValue = (SimpleValue)mp.getValue();
-		            return expectedType.cast((simpleValue != null) ? simpleValue.getValue() : null);
-			 }
-			 else if (metaType.isEnum()) {
-				 EnumValue enumValue = (EnumValue)mp.getValue();
-				 return expectedType.cast((enumValue != null) ? enumValue.getValue() : null);
-			 }
-			 throw new IllegalArgumentException(prop+ " is not a simple type"); //$NON-NLS-1$
-		 }
-		 return null;
-	}	
-	
-	public static Properties getPropertiesValue(ManagedCommon mc, String prop) {
-		 ManagedProperty mp = mc.getProperty(prop);
-		 if (mp != null) {
-			 MetaType metaType = mp.getMetaType();
-			 if (metaType.isProperties()) {
-				 return (PropertiesMetaValue)mp.getValue();
-			 }
-			 else if (metaType.isComposite()) {
-				Properties props = new Properties();
-				MapCompositeValueSupport map = (MapCompositeValueSupport) mp.getValue();
-				MapCompositeMetaType type = map.getMetaType();
-				for (String key : type.keySet()) {
-					MetaValue value = map.get(key);
-					props.setProperty(key, stringValue(value));
-				}
-				return props;
-			 }
-			 throw new IllegalArgumentException(prop+ " is not a properties type"); //$NON-NLS-1$
-		 }
-		 return null;
-	}	
-	
-	public static <T> void getCollectionValue(ManagedCommon mc, String prop, Collection<T> list, Class<T> expectedType) {
-		 ManagedProperty mp = mc.getProperty(prop);
-		 if (mp != null) {
-			 MetaType metaType = mp.getMetaType();
-			 if (metaType.isCollection()) {
-				 CollectionValue collectionValue = (CollectionValue)mp.getValue();
-				 for(MetaValue value:collectionValue.getElements()) {
-					 if (value.getMetaType().isSimple()) {
-						 SimpleValue simpleValue = (SimpleValue)value;
-						 list.add(expectedType.cast(simpleValue.getValue()));
-					 }
-					 else {
-						 throw new IllegalArgumentException(prop+ " is not a simple type"); //$NON-NLS-1$
-					 }
-				 }
-			 }
-		 }
-	}
-	
-	public static SimpleValue wrap(MetaType type, String value) {
-		if (type instanceof SimpleMetaType) {
-			SimpleMetaType st = (SimpleMetaType)type;
-			
-			if (SimpleMetaType.BIGDECIMAL.equals(st)) {
-				return new SimpleValueSupport(st, new BigDecimal(value));
-			} else if (SimpleMetaType.BIGINTEGER.equals(st)) {
-				return new SimpleValueSupport(st, new BigInteger(value));
-			} else if (SimpleMetaType.BOOLEAN.equals(st)) {
-				return new SimpleValueSupport(st, Boolean.valueOf(value));
-			} else if (SimpleMetaType.BOOLEAN_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Boolean.valueOf(value).booleanValue());
-			} else if (SimpleMetaType.BYTE.equals(st)) {
-				return new SimpleValueSupport(st, new Byte(value.getBytes()[0]));
-			} else if (SimpleMetaType.BYTE_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, value.getBytes()[0]);
-			} else if (SimpleMetaType.CHARACTER.equals(st)) {
-				return new SimpleValueSupport(st, new Character(value.charAt(0)));
-			} else if (SimpleMetaType.CHARACTER_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st,value.charAt(0));
-			} else if (SimpleMetaType.DATE.equals(st)) {
-				try {
-					return new SimpleValueSupport(st, SimpleDateFormat.getInstance().parse(value));
-				} catch (ParseException e) {
-					throw new TeiidRuntimeException(e, IntegrationPlugin.Util.getString("failed_to_convert", type.getClassName())); //$NON-NLS-1$
-				}
-			} else if (SimpleMetaType.DOUBLE.equals(st)) {
-				return new SimpleValueSupport(st, Double.valueOf(value));
-			} else if (SimpleMetaType.DOUBLE_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Double.parseDouble(value));
-			} else if (SimpleMetaType.FLOAT.equals(st)) {
-				return new SimpleValueSupport(st, Float.parseFloat(value));
-			} else if (SimpleMetaType.FLOAT_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Float.valueOf(value));
-			} else if (SimpleMetaType.INTEGER.equals(st)) {
-				return new SimpleValueSupport(st, Integer.valueOf(value));
-			} else if (SimpleMetaType.INTEGER_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Integer.parseInt(value));
-			} else if (SimpleMetaType.LONG.equals(st)) {
-				return new SimpleValueSupport(st, Long.valueOf(value));
-			} else if (SimpleMetaType.LONG_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Long.parseLong(value));
-			} else if (SimpleMetaType.SHORT.equals(st)) {
-				return new SimpleValueSupport(st, Short.valueOf(value));
-			} else if (SimpleMetaType.SHORT_PRIMITIVE.equals(st)) {
-				return new SimpleValueSupport(st, Short.parseShort(value));
-			} else if (SimpleMetaType.STRING.equals(st)) {
-				return new SimpleValueSupport(st,value);
-			}
-		}
-		throw new TeiidRuntimeException(IntegrationPlugin.Util.getString("failed_to_convert", type.getClassName())); //$NON-NLS-1$
-	}
-	
-	public static void deployArchive(DeploymentManager deploymentManager, String fileName, final InputStream resource, boolean deployExploded) throws AdminProcessingException {
-		deployArchive(deploymentManager, fileName, getTempURL(resource), deployExploded);
-	}
-	
-	public static void deployArchive(DeploymentManager deploymentManager, String fileName, URL resourceURL, boolean deployExploded) throws AdminProcessingException {
-		List<DeploymentOption> deploymentOptions = new ArrayList<DeploymentOption>();
-		if (deployExploded) {
-			deploymentOptions.add(DeploymentOption.Explode);
-		}
-		// try to deploy
-		DeploymentProgress progress = null;
-		try {
-			progress = deploymentManager.distribute(fileName, resourceURL, deploymentOptions.toArray(new DeploymentOption[deploymentOptions.size()]));
-			execute(progress, IntegrationPlugin.Util.getString("distribute_failed", fileName)); //$NON-NLS-1$
-		} catch (Exception e) {
-			handleException(e);
-		}
-		
-		// Now that we've successfully distributed the deployment, we need to
-		// start it.
-		String[] deploymentNames = progress.getDeploymentID().getRepositoryNames();
-		try {
-			progress = deploymentManager.start(deploymentNames);
-			execute(progress, IntegrationPlugin.Util.getString("deployment_start_failed", fileName)); //$NON-NLS-1$ 
-		} catch(Exception e) {
-			try {
-				// if failed to start remove it.
-				execute(deploymentManager.remove(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$ 
-			} catch (Exception e1) {
-				handleException(e1);
-			}
-			handleException(e);
-		}
-	}
-
-	static URL getTempURL(final InputStream resource) {
-		try {
-			return new URL(null, "temp:#temp", new URLStreamHandler() { //$NON-NLS-1$
-				
-				@Override
-				protected URLConnection openConnection(URL u) throws IOException {
-					return new URLConnection(u) {
-						
-						@Override
-						public void connect() throws IOException {
-							
-						}
-						
-						@Override
-						public InputStream getInputStream() throws IOException {
-							return resource;
-						}
-					};
-				}
-			});
-		} catch (MalformedURLException e2) {
-			throw new TeiidRuntimeException(e2);
-		}
-	}
-
-	public static void handleException(Exception e) throws AdminProcessingException {
-		if (e instanceof AdminProcessingException) {
-			throw (AdminProcessingException)e;
-		}
-		throw new AdminProcessingException(e.getMessage(), e);
-	}
-
-	public static void execute(DeploymentProgress progress, String errorMessage) throws AdminProcessingException {
-	    progress.run();
-	    DeploymentStatus status =  progress.getDeploymentStatus();
-	    
-		if (status.isFailed()) {
-			if (status.getFailure() != null) {
-				throw new AdminProcessingException(status.getFailure().getMessage(), status.getFailure());
-			}
-			throw new AdminProcessingException(errorMessage);				
-		}
-	}
-
-	public static void removeArchive(DeploymentManager deploymentManager, String... deploymentNames) throws AdminProcessingException{
-		try {
-			execute(deploymentManager.stop(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$
-			execute(deploymentManager.remove(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$ 
-		} catch (Exception e) {
-			handleException(e);
-		}
-	}
-	
-	public static MetaValue executeOperation(ManagedCommon mc, String operation, MetaValue... args) {
-		for (ManagedOperation mo:mc.getOperations()) {
-			if (mo.getName().equals(operation)) {
-				return mo.invoke(args);
-			}
-		}
-		throw new TeiidRuntimeException(IntegrationPlugin.Util.getString("no_operation", operation)); //$NON-NLS-1$ 
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java (from rev 2774, trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/adminapi/jboss/ManagedUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,323 @@
+/*
+ * 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.adminapi.jboss;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.jboss.deployers.spi.management.deploy.DeploymentManager;
+import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
+import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
+import org.jboss.managed.api.ManagedCommon;
+import org.jboss.managed.api.ManagedOperation;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.metatype.api.types.EnumMetaType;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CollectionValue;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.values.EnumValueSupport;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.PropertiesMetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.profileservice.spi.DeploymentOption;
+import org.teiid.adminapi.AdminProcessingException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.jboss.IntegrationPlugin;
+
+
+public class ManagedUtil {
+	
+	public static boolean sameValue(MetaValue v1, String v2) {
+		if (v1 == null || v2 == null) {
+			return false;
+		}
+		
+		MetaType type = v1.getMetaType();
+		if (v1 instanceof SimpleValue && type instanceof SimpleMetaType) {
+			SimpleMetaType st = (SimpleMetaType)type;
+			SimpleValue sv = wrap(st, v2);
+			return sv.compareTo((SimpleValue)v1) == 0;
+		}
+		return false;
+	}
+	
+	public static boolean sameValue(MetaValue v1, MetaValue v2) {
+		if (v1 == null || v2 == null) {
+			return false;
+		}
+		
+		if (v1 instanceof SimpleValue && v2 instanceof SimpleValue) {
+			return ((SimpleValue)v1).compareTo((SimpleValue)v2) == 0;
+		}
+		return false;
+	}
+
+	public static MapCompositeValueSupport compositeValueMap(Map<String, String> map) {
+		MapCompositeValueSupport metaValue = new MapCompositeValueSupport(SimpleMetaType.STRING);
+		for (String key : map.keySet()) {
+			MetaValue value = SimpleValueSupport.wrap(map.get(key));
+			metaValue.put(key, value);
+		}
+		return metaValue;
+	}	
+	
+	public static String stringValue(MetaValue v1) {
+		if (v1 != null) {
+			MetaType type = v1.getMetaType();
+			if (type instanceof SimpleMetaType) {
+				SimpleValue simple = (SimpleValue)v1;
+				return simple.getValue().toString();
+			}
+			throw new TeiidRuntimeException("Failed to convert value to string value"); //$NON-NLS-1$
+		}
+		return null;
+	}	
+	
+	public static <T> T getSimpleValue(ManagedCommon mc, String prop, Class<T> expectedType) {
+		 ManagedProperty mp = mc.getProperty(prop);
+		 if (mp != null) {
+			 MetaType metaType = mp.getMetaType();
+			 if (metaType.isSimple()) {
+		            SimpleValue simpleValue = (SimpleValue)mp.getValue();
+		            return expectedType.cast((simpleValue != null) ? simpleValue.getValue() : null);
+			 }
+			 else if (metaType.isEnum()) {
+				 EnumValue enumValue = (EnumValue)mp.getValue();
+				 return expectedType.cast((enumValue != null) ? enumValue.getValue() : null);
+			 }
+			 throw new IllegalArgumentException(prop+ " is not a simple type"); //$NON-NLS-1$
+		 }
+		 return null;
+	}	
+	
+	public static Properties getPropertiesValue(ManagedCommon mc, String prop) {
+		 ManagedProperty mp = mc.getProperty(prop);
+		 if (mp != null) {
+			 MetaType metaType = mp.getMetaType();
+			 if (metaType.isProperties()) {
+				 return (PropertiesMetaValue)mp.getValue();
+			 }
+			 else if (metaType.isComposite()) {
+				Properties props = new Properties();
+				MapCompositeValueSupport map = (MapCompositeValueSupport) mp.getValue();
+				MapCompositeMetaType type = map.getMetaType();
+				for (String key : type.keySet()) {
+					MetaValue value = map.get(key);
+					props.setProperty(key, stringValue(value));
+				}
+				return props;
+			 }
+			 throw new IllegalArgumentException(prop+ " is not a properties type"); //$NON-NLS-1$
+		 }
+		 return null;
+	}	
+	
+	public static <T> void getCollectionValue(ManagedCommon mc, String prop, Collection<T> list, Class<T> expectedType) {
+		 ManagedProperty mp = mc.getProperty(prop);
+		 if (mp != null) {
+			 MetaType metaType = mp.getMetaType();
+			 if (metaType.isCollection()) {
+				 CollectionValue collectionValue = (CollectionValue)mp.getValue();
+				 for(MetaValue value:collectionValue.getElements()) {
+					 if (value.getMetaType().isSimple()) {
+						 SimpleValue simpleValue = (SimpleValue)value;
+						 list.add(expectedType.cast(simpleValue.getValue()));
+					 }
+					 else {
+						 throw new IllegalArgumentException(prop+ " is not a simple type"); //$NON-NLS-1$
+					 }
+				 }
+			 }
+		 }
+	}
+	
+	public static EnumValue wrap(EnumMetaType type, String value) {
+		return new EnumValueSupport(type, value);
+	}
+	
+	public static SimpleValue wrap(MetaType type, String value) {
+		if (type instanceof SimpleMetaType) {
+			SimpleMetaType st = (SimpleMetaType)type;
+			
+			if (SimpleMetaType.BIGDECIMAL.equals(st)) {
+				return new SimpleValueSupport(st, new BigDecimal(value));
+			} else if (SimpleMetaType.BIGINTEGER.equals(st)) {
+				return new SimpleValueSupport(st, new BigInteger(value));
+			} else if (SimpleMetaType.BOOLEAN.equals(st)) {
+				return new SimpleValueSupport(st, Boolean.valueOf(value));
+			} else if (SimpleMetaType.BOOLEAN_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Boolean.valueOf(value).booleanValue());
+			} else if (SimpleMetaType.BYTE.equals(st)) {
+				return new SimpleValueSupport(st, new Byte(value.getBytes()[0]));
+			} else if (SimpleMetaType.BYTE_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, value.getBytes()[0]);
+			} else if (SimpleMetaType.CHARACTER.equals(st)) {
+				return new SimpleValueSupport(st, new Character(value.charAt(0)));
+			} else if (SimpleMetaType.CHARACTER_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st,value.charAt(0));
+			} else if (SimpleMetaType.DATE.equals(st)) {
+				try {
+					return new SimpleValueSupport(st, SimpleDateFormat.getInstance().parse(value));
+				} catch (ParseException e) {
+					throw new TeiidRuntimeException(e, IntegrationPlugin.Util.getString("failed_to_convert", type.getClassName())); //$NON-NLS-1$
+				}
+			} else if (SimpleMetaType.DOUBLE.equals(st)) {
+				return new SimpleValueSupport(st, Double.valueOf(value));
+			} else if (SimpleMetaType.DOUBLE_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Double.parseDouble(value));
+			} else if (SimpleMetaType.FLOAT.equals(st)) {
+				return new SimpleValueSupport(st, Float.parseFloat(value));
+			} else if (SimpleMetaType.FLOAT_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Float.valueOf(value));
+			} else if (SimpleMetaType.INTEGER.equals(st)) {
+				return new SimpleValueSupport(st, Integer.valueOf(value));
+			} else if (SimpleMetaType.INTEGER_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Integer.parseInt(value));
+			} else if (SimpleMetaType.LONG.equals(st)) {
+				return new SimpleValueSupport(st, Long.valueOf(value));
+			} else if (SimpleMetaType.LONG_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Long.parseLong(value));
+			} else if (SimpleMetaType.SHORT.equals(st)) {
+				return new SimpleValueSupport(st, Short.valueOf(value));
+			} else if (SimpleMetaType.SHORT_PRIMITIVE.equals(st)) {
+				return new SimpleValueSupport(st, Short.parseShort(value));
+			} else if (SimpleMetaType.STRING.equals(st)) {
+				return new SimpleValueSupport(st,value);
+			}
+		}
+		throw new TeiidRuntimeException(IntegrationPlugin.Util.getString("failed_to_convert", type.getClassName())); //$NON-NLS-1$
+	}
+	
+	public static void deployArchive(DeploymentManager deploymentManager, String fileName, final InputStream resource, boolean deployExploded) throws AdminProcessingException {
+		deployArchive(deploymentManager, fileName, getTempURL(resource), deployExploded);
+	}
+	
+	public static void deployArchive(DeploymentManager deploymentManager, String fileName, URL resourceURL, boolean deployExploded) throws AdminProcessingException {
+		List<DeploymentOption> deploymentOptions = new ArrayList<DeploymentOption>();
+		if (deployExploded) {
+			deploymentOptions.add(DeploymentOption.Explode);
+		}
+		// try to deploy
+		DeploymentProgress progress = null;
+		try {
+			progress = deploymentManager.distribute(fileName, resourceURL, deploymentOptions.toArray(new DeploymentOption[deploymentOptions.size()]));
+			execute(progress, IntegrationPlugin.Util.getString("distribute_failed", fileName)); //$NON-NLS-1$
+		} catch (Exception e) {
+			handleException(e);
+		}
+		
+		// Now that we've successfully distributed the deployment, we need to
+		// start it.
+		String[] deploymentNames = progress.getDeploymentID().getRepositoryNames();
+		try {
+			progress = deploymentManager.start(deploymentNames);
+			execute(progress, IntegrationPlugin.Util.getString("deployment_start_failed", fileName)); //$NON-NLS-1$ 
+		} catch(Exception e) {
+			try {
+				// if failed to start remove it.
+				execute(deploymentManager.remove(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$ 
+			} catch (Exception e1) {
+				handleException(e1);
+			}
+			handleException(e);
+		}
+	}
+
+	static URL getTempURL(final InputStream resource) {
+		try {
+			return new URL(null, "temp:#temp", new URLStreamHandler() { //$NON-NLS-1$
+				
+				@Override
+				protected URLConnection openConnection(URL u) throws IOException {
+					return new URLConnection(u) {
+						
+						@Override
+						public void connect() throws IOException {
+							
+						}
+						
+						@Override
+						public InputStream getInputStream() throws IOException {
+							return resource;
+						}
+					};
+				}
+			});
+		} catch (MalformedURLException e2) {
+			throw new TeiidRuntimeException(e2);
+		}
+	}
+
+	public static void handleException(Exception e) throws AdminProcessingException {
+		if (e instanceof AdminProcessingException) {
+			throw (AdminProcessingException)e;
+		}
+		throw new AdminProcessingException(e.getMessage(), e);
+	}
+
+	public static void execute(DeploymentProgress progress, String errorMessage) throws AdminProcessingException {
+	    progress.run();
+	    DeploymentStatus status =  progress.getDeploymentStatus();
+	    
+		if (status.isFailed()) {
+			if (status.getFailure() != null) {
+				throw new AdminProcessingException(status.getFailure().getMessage(), status.getFailure());
+			}
+			throw new AdminProcessingException(errorMessage);				
+		}
+	}
+
+	public static void removeArchive(DeploymentManager deploymentManager, String... deploymentNames) throws AdminProcessingException{
+		try {
+			execute(deploymentManager.stop(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$
+			execute(deploymentManager.remove(deploymentNames), IntegrationPlugin.Util.getString("failed_to_remove")); //$NON-NLS-1$ 
+		} catch (Exception e) {
+			handleException(e);
+		}
+	}
+	
+	public static MetaValue executeOperation(ManagedCommon mc, String operation, MetaValue... args) {
+		for (ManagedOperation mo:mc.getOperations()) {
+			if (mo.getName().equals(operation)) {
+				return mo.invoke(args);
+			}
+		}
+		throw new TeiidRuntimeException(IntegrationPlugin.Util.getString("no_operation", operation)); //$NON-NLS-1$ 
+	}
+}

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

Copied: tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java (from rev 2774, trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,595 @@
+/*
+ * 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;
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml
===================================================================
--- trunk/metadata/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/metadata/pom.xml (from rev 2777, trunk/metadata/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/metadata/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/pom.xml
===================================================================
--- trunk/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/pom.xml (from rev 2777, trunk/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1</connection>
+		<developerConnection>scm:svn:https://svn.jboss.org/repos/teiid/tags/teiid-parent-7.3.0.Alpha1</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.Alpha1/runtime/pom.xml
===================================================================
--- trunk/runtime/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/runtime/pom.xml (from rev 2777, trunk/runtime/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/runtime/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.deployers;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
-import org.jboss.logging.Logger;
-import org.teiid.core.util.FileUtils;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.runtime.RuntimePlugin;
-
-
-public class ObjectSerializer {
-	
-	private static final Logger log = Logger.getLogger(ObjectSerializer.class);
-
-	private static final String ATTACHMENT_SUFFIX = ".ser"; //$NON-NLS-1$
-
-	private String storagePath;
-	
-	public void setAttachmentStoreRoot(String path) {
-		this.storagePath = path;
-	}
-	
-	public <T> T loadAttachment(File attachmentsStore, Class<T> expected) throws IOException, ClassNotFoundException {
-		if (log.isTraceEnabled()) {
-			log.trace("loadAttachment, attachmentsStore=" + attachmentsStore); //$NON-NLS-1$
-		}
-
-		ObjectInputStream ois = null;
-		try {
-			ois = new ObjectInputStream(new FileInputStream(attachmentsStore));
-			return expected.cast(ois.readObject());
-		} finally {
-			if (ois != null) {
-				ois.close();
-			}
-		}
-	}
-
-	public void saveAttachment(File attachmentsStore, Object attachment) throws IOException {
-		if (log.isTraceEnabled()) {
-			log.trace("saveAttachment, attachmentsStore=" + attachmentsStore + ", attachment=" + attachment); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		
-		ObjectOutputStream oos = null;
-		try {
-			oos = new ObjectOutputStream(new FileOutputStream(attachmentsStore));
-			oos.writeObject(attachment);
-		} finally {
-			if (oos != null) {
-				oos.close();
-			}
-		}
-	}
-	
-	public void removeAttachments(VFSDeploymentUnit vf) {
-		String dirName = baseDirectory(vf);
-		FileUtils.removeDirectoryAndChildren(new File(dirName));
-	}
-
-	public File getAttachmentPath(VFSDeploymentUnit vf, String baseName) {
-		
-		String dirName = baseDirectory(vf);
-
-		final String vfsPath = baseName + ATTACHMENT_SUFFIX;
-		File f = new File(dirName, vfsPath);
-		if (!f.getParentFile().exists()) {
-			f.getParentFile().mkdirs();
-		}
-		return f;
-	}
-
-	private String baseDirectory(VFSDeploymentUnit vf) {
-		String fileName = vf.getRoot().getName();
-		String dirName = this.storagePath + File.separator + fileName + File.separator;
-		return dirName;
-	}
-	
-	public <T> T loadSafe(File cacheFile, Class<T> clazz) {
-		try {
-			if (cacheFile.exists()) {
-				return clazz.cast(loadAttachment(cacheFile, clazz));
-			}
-			return null;
-		} catch (Exception e) {
-			LogManager.logWarning(LogConstants.CTX_RUNTIME, e, RuntimePlugin.Util.getString("invalid_metadata_file", cacheFile.getAbsolutePath())); //$NON-NLS-1$
-		}
-		cacheFile.delete();
-		return null;
-	}	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java (from rev 2774, trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.deployers;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
+import org.jboss.logging.Logger;
+import org.teiid.core.util.FileUtils;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.runtime.RuntimePlugin;
+
+
+public class ObjectSerializer {
+	
+	private static final Logger log = Logger.getLogger(ObjectSerializer.class);
+
+	private static final String ATTACHMENT_SUFFIX = ".ser"; //$NON-NLS-1$
+
+	private String storagePath;
+	
+	public void setAttachmentStoreRoot(String path) {
+		this.storagePath = path;
+	}
+	
+	public <T> T loadAttachment(File attachmentsStore, Class<T> expected) throws IOException, ClassNotFoundException {
+		if (log.isTraceEnabled()) {
+			log.trace("loadAttachment, attachmentsStore=" + attachmentsStore); //$NON-NLS-1$
+		}
+
+		ObjectInputStream ois = null;
+		try {
+			ois = new ObjectInputStream(new FileInputStream(attachmentsStore));
+			return expected.cast(ois.readObject());
+		} finally {
+			if (ois != null) {
+				ois.close();
+			}
+		}
+	}
+
+	public void saveAttachment(File attachmentsStore, Object attachment) throws IOException {
+		if (log.isTraceEnabled()) {
+			log.trace("saveAttachment, attachmentsStore=" + attachmentsStore + ", attachment=" + attachment); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		
+		ObjectOutputStream oos = null;
+		try {
+			oos = new ObjectOutputStream(new FileOutputStream(attachmentsStore));
+			oos.writeObject(attachment);
+		} finally {
+			if (oos != null) {
+				oos.close();
+			}
+		}
+	}
+	
+	public boolean isStale(File cacheFile, long timeAfter) {
+		return (cacheFile.exists() && timeAfter > cacheFile.lastModified());
+	}
+	
+	public void removeAttachments(VFSDeploymentUnit vf) {
+		String dirName = baseDirectory(vf);
+		FileUtils.removeDirectoryAndChildren(new File(dirName));
+	}
+
+	public File getAttachmentPath(VFSDeploymentUnit vf, String baseName) {
+		
+		String dirName = baseDirectory(vf);
+
+		final String vfsPath = baseName + ATTACHMENT_SUFFIX;
+		File f = new File(dirName, vfsPath);
+		if (!f.getParentFile().exists()) {
+			f.getParentFile().mkdirs();
+		}
+		return f;
+	}
+
+	private String baseDirectory(VFSDeploymentUnit vf) {
+		String fileName = vf.getRoot().getName();
+		String dirName = this.storagePath + File.separator + fileName + File.separator;
+		return dirName;
+	}
+	
+	public <T> T loadSafe(File cacheFile, Class<T> clazz) {
+		try {
+			if (cacheFile.exists()) {
+				return clazz.cast(loadAttachment(cacheFile, clazz));
+			}
+			return null;
+		} catch (Exception e) {
+			LogManager.logWarning(LogConstants.CTX_RUNTIME, e, RuntimePlugin.Util.getString("invalid_metadata_file", cacheFile.getAbsolutePath())); //$NON-NLS-1$
+		}
+		cacheFile.delete();
+		return null;
+	}	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,365 +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.deployers;
-
-import java.io.File;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.IdentityHashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Set;
-
-import org.jboss.deployers.spi.DeploymentException;
-import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
-import org.jboss.deployers.structure.spi.DeploymentUnit;
-import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
-import org.jboss.util.threadpool.ThreadPool;
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.SourceMappingMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.adminapi.impl.VDBTranslatorMetaData;
-import org.teiid.adminapi.impl.ModelMetaData.ValidationError;
-import org.teiid.core.util.FileUtils;
-import org.teiid.dqp.internal.datamgr.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.dqp.internal.datamgr.TranslatorRepository;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.index.IndexMetadataFactory;
-import org.teiid.query.metadata.TransformationMetadata.Resource;
-import org.teiid.runtime.RuntimePlugin;
-import org.teiid.translator.ExecutionFactory;
-import org.teiid.translator.TranslatorException;
-
-
-public class VDBDeployer extends AbstractSimpleRealDeployer<VDBMetaData> {
-	private VDBRepository vdbRepository;
-	private TranslatorRepository translatorRepository;
-	private ObjectSerializer serializer;
-	private ContainerLifeCycleListener shutdownListener;
-	private ThreadPool threadPool;
-	
-	public VDBDeployer() {
-		super(VDBMetaData.class);
-		setInput(VDBMetaData.class);
-		setOutput(VDBMetaData.class);
-		setRelativeOrder(3001); // after the data sources
-	}
-
-	@Override
-	public void deploy(DeploymentUnit unit, VDBMetaData deployment) throws DeploymentException {
-		if (this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion())) {
-			LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("redeploying_vdb", deployment)); //$NON-NLS-1$ 
-		}
-		
-		TranslatorRepository repo = new TranslatorRepository();
-		ConnectorManagerRepository cmr = new ConnectorManagerRepository();
-		
-		boolean preview = deployment.isPreview();
-		
-		if (!preview) {
-			List<String> errors = deployment.getValidityErrors();
-			if (errors != null && !errors.isEmpty()) {
-				throw new DeploymentException(RuntimePlugin.Util.getString("validity_errors_in_vdb", deployment)); //$NON-NLS-1$
-			}
-		}
-		
-		// get the metadata store of the VDB (this is build in parse stage)
-		MetadataStoreGroup store = unit.getAttachment(MetadataStoreGroup.class);
-		
-		// add required connector managers; if they are not already there
-		for (Translator t: deployment.getOverrideTranslators()) {
-			VDBTranslatorMetaData data = (VDBTranslatorMetaData)t;
-			
-			String type = data.getType();
-			Translator parent = this.translatorRepository.getTranslatorMetaData(type);
-			if ( parent == null) {
-				throw new DeploymentException(RuntimePlugin.Util.getString("translator_type_not_found", unit.getName())); //$NON-NLS-1$
-			}
-			
-			Set<String> keys = parent.getProperties().stringPropertyNames();
-			for (String key:keys) {
-				if (data.getPropertyValue(key) == null && parent.getPropertyValue(key) != null) {
-					data.addProperty(key, parent.getPropertyValue(key));
-				}
-			}
-			repo.addTranslatorMetadata(data.getName(), data);
-		}
-		createConnectorManagers(cmr, repo, deployment);
-		
-		// if store is null and vdb dynamic vdb then try to get the metadata
-		if (store == null && deployment.isDynamic()) {
-			store = new MetadataStoreGroup();
-			buildDynamicMetadataStore((VFSDeploymentUnit)unit, deployment, store, cmr);
-		}
-		
-		// allow empty vdbs for enabling the preview functionality
-		if (preview && store == null) {
-			store = new MetadataStoreGroup();
-		}
-		
-		if (store == null) {
-			LogManager.logError(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("failed_matadata_load", deployment.getName(), deployment.getVersion())); //$NON-NLS-1$
-		}
-		
-		// check if this is a VDB with index files, if there are then build the TransformationMetadata
-		UDFMetaData udf = unit.getAttachment(UDFMetaData.class);
-		
-		LinkedHashMap<String, Resource> visibilityMap = null;
-		IndexMetadataFactory indexFactory = unit.getAttachment(IndexMetadataFactory.class);		
-		if (indexFactory != null) {
-			visibilityMap = indexFactory.getEntriesPlusVisibilities();
-		}
-				
-		// add the metadata objects as attachments
-		deployment.removeAttachment(IndexMetadataFactory.class);
-		deployment.removeAttachment(UDFMetaData.class);
-		deployment.removeAttachment(MetadataStoreGroup.class);
-		
-		// add transformation metadata to the repository.
-		this.vdbRepository.addVDB(deployment, store, visibilityMap, udf, cmr);
-		
-		try {
-			saveMetadataStore((VFSDeploymentUnit)unit, deployment, store);
-		} catch (IOException e1) {
-			LogManager.logWarning(LogConstants.CTX_RUNTIME, e1, RuntimePlugin.Util.getString("vdb_save_failed", deployment.getName()+"."+deployment.getVersion())); //$NON-NLS-1$ //$NON-NLS-2$			
-		}
-				
-		boolean valid = true;
-		if (!preview) {
-			valid = validateSources(cmr, deployment);
-			
-			// Check if the VDB is fully configured.
-			if (valid) {
-				deployment.setStatus(VDB.Status.ACTIVE);
-			} else {
-				deployment.setStatus(VDB.Status.INACTIVE);
-			}			
-		}
-		else {
-			deployment.setStatus(VDB.Status.ACTIVE);
-		}
-		LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_deployed",deployment, valid?"active":"inactive")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-
-	private void createConnectorManagers(ConnectorManagerRepository cmr, TranslatorRepository repo, final VDBMetaData deployment) throws DeploymentException {
-		IdentityHashMap<Translator, ExecutionFactory<Object, Object>> map = new IdentityHashMap<Translator, ExecutionFactory<Object, Object>>();
-		
-		for (Model model:deployment.getModels()) {
-			for (String source:model.getSourceNames()) {
-				if (cmr.getConnectorManager(source) != null) {
-					continue;
-				}
-
-				String name = model.getSourceTranslatorName(source);
-				Translator translator = repo.getTranslatorMetaData(name);
-				if (translator == null) {
-					translator = this.translatorRepository.getTranslatorMetaData(name);
-				}
-				if (translator == null) {
-					throw new DeploymentException(RuntimePlugin.Util.getString("translator_not_found", deployment.getName(), deployment.getVersion(), name)); //$NON-NLS-1$
-				}
-			
-				ExecutionFactory<Object, Object> ef = map.get(translator);
-				if ( ef == null) {
-					ef = TranslatorUtil.buildExecutionFactory(translator);
-					map.put(translator, ef);
-				}
-
-				ConnectorManager cm = new ConnectorManager(name, model.getSourceConnectionJndiName(source));
-				cm.setExecutionFactory(ef);
-				cm.setModelName(model.getName());
-				cmr.addConnectorManager(source, cm);
-			}
-		}
-	}
-
-	private boolean validateSources(ConnectorManagerRepository cmr, VDBMetaData deployment) {
-		boolean valid = true;
-		for(Model m:deployment.getModels()) {
-			ModelMetaData model = (ModelMetaData)m;
-			List<SourceMappingMetadata> mappings = model.getSourceMappings();
-			for (SourceMappingMetadata mapping:mappings) {
-				ConnectorManager cm = cmr.getConnectorManager(mapping.getName());
-				String msg = cm.getStausMessage();
-				if (msg != null && msg.length() > 0) {
-					valid = false;
-					model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), cm.getStausMessage());
-					LogManager.logInfo(LogConstants.CTX_RUNTIME, cm.getStausMessage());
-				}
-			}
-			
-			// in the dynamic case the metadata may be still loading.
-			if (!model.getErrors().isEmpty()) {
-				valid = false;
-			}
-		}
-		return valid;
-	}
-
-	public void setVDBRepository(VDBRepository repo) {
-		this.vdbRepository = repo;
-	}
-	
-	@Override
-	public void undeploy(DeploymentUnit unit, VDBMetaData deployment) {
-		super.undeploy(unit, deployment);
-		
-		if (this.vdbRepository != null) {
-			this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion());
-		}
-		
-		deployment.setRemoved(true);
-		
-		try {
-			deleteMetadataStore((VFSDeploymentUnit)unit, deployment);
-		} catch (IOException e) {
-			LogManager.logWarning(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_delete_failed", e.getMessage())); //$NON-NLS-1$
-		}
-
-		LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_undeployed", deployment)); //$NON-NLS-1$
-	}
-
-	public void setObjectSerializer(ObjectSerializer serializer) {
-		this.serializer = serializer;
-	}		
-	
-	private void saveMetadataStore(VFSDeploymentUnit unit, VDBMetaData vdb, MetadataStoreGroup store) throws IOException {
-		File cacheFileName = this.serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()); //$NON-NLS-1$
-		if (!cacheFileName.exists()) {
-			this.serializer.saveAttachment(cacheFileName,store);
-		}
-	}
-	
-	private void deleteMetadataStore(VFSDeploymentUnit unit, VDBMetaData vdb) throws IOException {
-		if (!unit.getRoot().exists() || !shutdownListener.isShutdownInProgress()) {
-			File cacheFileName = this.serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()); //$NON-NLS-1$
-			if (cacheFileName.exists()) {
-				FileUtils.removeDirectoryAndChildren(cacheFileName.getParentFile());
-			}
-		}
-	}
-	
-    private void buildDynamicMetadataStore(final VFSDeploymentUnit unit, final VDBMetaData vdb, final MetadataStoreGroup vdbStore, final ConnectorManagerRepository cmr) throws DeploymentException {
-    	
-    	// make sure we are configured correctly first
-		for (final ModelMetaData model:vdb.getModelMetaDatas().values()) {
-	    	if (model.getSourceNames().isEmpty()) {
-	    		throw new DeploymentException(RuntimePlugin.Util.getString("fail_to_deploy", vdb.getName()+"-"+vdb.getVersion(), model.getName())); //$NON-NLS-1$ //$NON-NLS-2$
-	    	}
-			    	
-	    	final boolean cache = "cached".equalsIgnoreCase(vdb.getPropertyValue("UseConnectorMetadata")); //$NON-NLS-1$ //$NON-NLS-2$
-	    	final File cacheFile = buildCachedFileName(unit, vdb, model.getName());
-	    	boolean loaded = false;
-	    	if (cache) {
-				MetadataStore store = this.serializer.loadSafe(cacheFile, MetadataStore.class);
-				if (store != null) {
-					vdbStore.addStore(store);
-					loaded = true;
-				}
-	    	}
-	    	
-	    	if (!loaded) {
-	    		String msg = RuntimePlugin.Util.getString("model_metadata_loading", vdb.getName()+"-"+vdb.getVersion(), model.getName(), SimpleDateFormat.getInstance().format(new Date())); //$NON-NLS-1$ //$NON-NLS-2$
-	    		final ValidationError addedError = model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), msg); 
-	    		LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
-	    		threadPool.run(new Runnable() {
-					@Override
-					public void run() {
-						loadMetadata(vdb, model, cache, cacheFile, vdbStore, cmr, addedError);
-					}
-	    		});
-	    	}
-		}
-	}	
-    
-    private void loadMetadata(VDBMetaData vdb, ModelMetaData model, boolean cache, File cacheFile, MetadataStoreGroup vdbStore, ConnectorManagerRepository cmr, ValidationError addedError) {
-    	Exception exception = null;
-    	
-    	boolean loaded = false;
-    	for (String sourceName: model.getSourceNames()) {
-    		ConnectorManager cm = cmr.getConnectorManager(sourceName);
-    		if (cm == null) {
-    			continue;
-    		}
-    		try {
-    			MetadataStore store = cm.getMetadata(model.getName(), this.vdbRepository.getBuiltinDatatypes(), model.getProperties());
-    			if (cache) {
-    				this.serializer.saveAttachment(cacheFile, store);
-    			}
-    			vdbStore.addStore(store);
-    			model.removeError(addedError);
-    			loaded = true;
-    			break;
-			} catch (TranslatorException e) {
-				if (exception == null) {
-					exception = e;
-				}
-			} catch (IOException e) {
-				if (exception == null) {
-					exception = e;
-				}				
-			}
-    	}
-    	
-    	synchronized (this) {
-	    	if (!loaded) {
-	    		vdb.setStatus(VDB.Status.INACTIVE);
-	    		String msg = RuntimePlugin.Util.getString("failed_to_retrive_metadata", vdb.getName()+"-"+vdb.getVersion(), model.getName()); //$NON-NLS-1$ //$NON-NLS-2$
-		    	model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), msg); 
-		    	if (exception != null) {
-		    		model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), exception.getMessage());     		
-		    	}
-		    	LogManager.logWarning(LogConstants.CTX_RUNTIME, msg);
-	    	}
-	    	else {
-	    		if (vdb.isValid()) {
-	    			this.vdbRepository.updateVDB(vdb.getName(), vdb.getVersion());
-					vdb.setStatus(VDB.Status.ACTIVE);
-					LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_activated",vdb.getName(), vdb.getVersion())); //$NON-NLS-1$    			
-	    		}
-	    	}
-    	}
-    }
-    
-	private File buildCachedFileName(VFSDeploymentUnit unit, VDBMetaData vdb, String modelName) {
-		return this.serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()+"_"+modelName); //$NON-NLS-1$ //$NON-NLS-2$
-	}    
-	
-	public void setTranslatorRepository(TranslatorRepository repo) {
-		this.translatorRepository = repo;
-	}	
-	
-	public void setContainerLifeCycleListener(ContainerLifeCycleListener listener) {
-		shutdownListener = listener;
-	}
-	
-	public void setThreadPool(ThreadPool pool) {
-		this.threadPool = pool;
-	}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java (from rev 2774, trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,367 @@
+/*
+ * 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.deployers;
+
+import java.io.File;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+
+import org.jboss.deployers.spi.DeploymentException;
+import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
+import org.jboss.deployers.structure.spi.DeploymentUnit;
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
+import org.jboss.util.threadpool.ThreadPool;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.SourceMappingMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.VDBTranslatorMetaData;
+import org.teiid.adminapi.impl.ModelMetaData.ValidationError;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.TranslatorRepository;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.index.IndexMetadataFactory;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
+import org.teiid.runtime.RuntimePlugin;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.TranslatorException;
+
+
+public class VDBDeployer extends AbstractSimpleRealDeployer<VDBMetaData> {
+	private VDBRepository vdbRepository;
+	private TranslatorRepository translatorRepository;
+	private ObjectSerializer serializer;
+	private ContainerLifeCycleListener shutdownListener;
+	private ThreadPool threadPool;
+	
+	public VDBDeployer() {
+		super(VDBMetaData.class);
+		setInput(VDBMetaData.class);
+		setOutput(VDBMetaData.class);
+		setRelativeOrder(3001); // after the data sources
+	}
+
+	@Override
+	public void deploy(DeploymentUnit unit, VDBMetaData deployment) throws DeploymentException {
+		if (this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion())) {
+			LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("redeploying_vdb", deployment)); //$NON-NLS-1$ 
+		}
+		
+		TranslatorRepository repo = new TranslatorRepository();
+		ConnectorManagerRepository cmr = new ConnectorManagerRepository();
+		
+		boolean preview = deployment.isPreview();
+		
+		if (!preview) {
+			List<String> errors = deployment.getValidityErrors();
+			if (errors != null && !errors.isEmpty()) {
+				throw new DeploymentException(RuntimePlugin.Util.getString("validity_errors_in_vdb", deployment)); //$NON-NLS-1$
+			}
+		}
+		
+		// get the metadata store of the VDB (this is build in parse stage)
+		MetadataStoreGroup store = unit.getAttachment(MetadataStoreGroup.class);
+		
+		// add required connector managers; if they are not already there
+		for (Translator t: deployment.getOverrideTranslators()) {
+			VDBTranslatorMetaData data = (VDBTranslatorMetaData)t;
+			
+			String type = data.getType();
+			Translator parent = this.translatorRepository.getTranslatorMetaData(type);
+			if ( parent == null) {
+				throw new DeploymentException(RuntimePlugin.Util.getString("translator_type_not_found", unit.getName())); //$NON-NLS-1$
+			}
+			
+			Set<String> keys = parent.getProperties().stringPropertyNames();
+			for (String key:keys) {
+				if (data.getPropertyValue(key) == null && parent.getPropertyValue(key) != null) {
+					data.addProperty(key, parent.getPropertyValue(key));
+				}
+			}
+			repo.addTranslatorMetadata(data.getName(), data);
+		}
+		createConnectorManagers(cmr, repo, deployment);
+		
+		// if store is null and vdb dynamic vdb then try to get the metadata
+		if (store == null && deployment.isDynamic()) {
+			store = new MetadataStoreGroup();
+			buildDynamicMetadataStore((VFSDeploymentUnit)unit, deployment, store, cmr);
+		}
+		
+		// allow empty vdbs for enabling the preview functionality
+		if (preview && store == null) {
+			store = new MetadataStoreGroup();
+		}
+		
+		if (store == null) {
+			LogManager.logError(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("failed_matadata_load", deployment.getName(), deployment.getVersion())); //$NON-NLS-1$
+		}
+		
+		// check if this is a VDB with index files, if there are then build the TransformationMetadata
+		UDFMetaData udf = unit.getAttachment(UDFMetaData.class);
+		
+		LinkedHashMap<String, Resource> visibilityMap = null;
+		IndexMetadataFactory indexFactory = unit.getAttachment(IndexMetadataFactory.class);		
+		if (indexFactory != null) {
+			visibilityMap = indexFactory.getEntriesPlusVisibilities();
+		}
+				
+		// add the metadata objects as attachments
+		deployment.removeAttachment(IndexMetadataFactory.class);
+		deployment.removeAttachment(UDFMetaData.class);
+		deployment.removeAttachment(MetadataStoreGroup.class);
+		
+		// add transformation metadata to the repository.
+		this.vdbRepository.addVDB(deployment, store, visibilityMap, udf, cmr);
+		
+		try {
+			saveMetadataStore((VFSDeploymentUnit)unit, deployment, store);
+		} catch (IOException e1) {
+			LogManager.logWarning(LogConstants.CTX_RUNTIME, e1, RuntimePlugin.Util.getString("vdb_save_failed", deployment.getName()+"."+deployment.getVersion())); //$NON-NLS-1$ //$NON-NLS-2$			
+		}
+				
+		boolean valid = true;
+		if (!preview) {
+			valid = validateSources(cmr, deployment);
+			
+			// Check if the VDB is fully configured.
+			if (valid) {
+				deployment.setStatus(VDB.Status.ACTIVE);
+			} else {
+				deployment.setStatus(VDB.Status.INACTIVE);
+			}			
+		}
+		else {
+			deployment.setStatus(VDB.Status.ACTIVE);
+		}
+		LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_deployed",deployment, valid?"active":"inactive")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+
+	private void createConnectorManagers(ConnectorManagerRepository cmr, TranslatorRepository repo, final VDBMetaData deployment) throws DeploymentException {
+		IdentityHashMap<Translator, ExecutionFactory<Object, Object>> map = new IdentityHashMap<Translator, ExecutionFactory<Object, Object>>();
+		
+		for (Model model:deployment.getModels()) {
+			for (String source:model.getSourceNames()) {
+				if (cmr.getConnectorManager(source) != null) {
+					continue;
+				}
+
+				String name = model.getSourceTranslatorName(source);
+				Translator translator = repo.getTranslatorMetaData(name);
+				if (translator == null) {
+					translator = this.translatorRepository.getTranslatorMetaData(name);
+				}
+				if (translator == null) {
+					throw new DeploymentException(RuntimePlugin.Util.getString("translator_not_found", deployment.getName(), deployment.getVersion(), name)); //$NON-NLS-1$
+				}
+			
+				ExecutionFactory<Object, Object> ef = map.get(translator);
+				if ( ef == null) {
+					ef = TranslatorUtil.buildExecutionFactory(translator);
+					map.put(translator, ef);
+				}
+
+				ConnectorManager cm = new ConnectorManager(name, model.getSourceConnectionJndiName(source));
+				cm.setExecutionFactory(ef);
+				cm.setModelName(model.getName());
+				cmr.addConnectorManager(source, cm);
+			}
+		}
+	}
+
+	private boolean validateSources(ConnectorManagerRepository cmr, VDBMetaData deployment) {
+		boolean valid = true;
+		for(Model m:deployment.getModels()) {
+			ModelMetaData model = (ModelMetaData)m;
+			List<SourceMappingMetadata> mappings = model.getSourceMappings();
+			for (SourceMappingMetadata mapping:mappings) {
+				ConnectorManager cm = cmr.getConnectorManager(mapping.getName());
+				String msg = cm.getStausMessage();
+				if (msg != null && msg.length() > 0) {
+					valid = false;
+					model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), cm.getStausMessage());
+					LogManager.logInfo(LogConstants.CTX_RUNTIME, cm.getStausMessage());
+				}
+			}
+			
+			// in the dynamic case the metadata may be still loading.
+			if (!model.getErrors().isEmpty()) {
+				valid = false;
+			}
+		}
+		return valid;
+	}
+
+	public void setVDBRepository(VDBRepository repo) {
+		this.vdbRepository = repo;
+	}
+	
+	@Override
+	public void undeploy(DeploymentUnit unit, VDBMetaData deployment) {
+		super.undeploy(unit, deployment);
+		
+		if (this.vdbRepository != null) {
+			this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion());
+		}
+		
+		deployment.setRemoved(true);
+		
+		try {
+			deleteMetadataStore((VFSDeploymentUnit)unit);
+		} catch (IOException e) {
+			LogManager.logWarning(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_delete_failed", e.getMessage())); //$NON-NLS-1$
+		}
+
+		LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_undeployed", deployment)); //$NON-NLS-1$
+	}
+
+	public void setObjectSerializer(ObjectSerializer serializer) {
+		this.serializer = serializer;
+	}		
+	
+	private void saveMetadataStore(VFSDeploymentUnit unit, VDBMetaData vdb, MetadataStoreGroup store) throws IOException {
+		File cacheFileName = buildCachedVDBFileName(this.serializer, unit, vdb);
+		if (!cacheFileName.exists()) {
+			this.serializer.saveAttachment(cacheFileName,store);
+			LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" metadata has been cached to "+ cacheFileName); //$NON-NLS-1$ //$NON-NLS-2$
+		}		
+	}
+	
+	private void deleteMetadataStore(VFSDeploymentUnit unit) throws IOException {
+		if (!unit.getRoot().exists() || !shutdownListener.isShutdownInProgress()) {
+			this.serializer.removeAttachments(unit);
+			LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" metadata removed"); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+	}
+	
+    private void buildDynamicMetadataStore(final VFSDeploymentUnit unit, final VDBMetaData vdb, final MetadataStoreGroup vdbStore, final ConnectorManagerRepository cmr) throws DeploymentException {
+    	
+    	// make sure we are configured correctly first
+		for (final ModelMetaData model:vdb.getModelMetaDatas().values()) {
+	    	if (model.getSourceNames().isEmpty()) {
+	    		throw new DeploymentException(RuntimePlugin.Util.getString("fail_to_deploy", vdb.getName()+"-"+vdb.getVersion(), model.getName())); //$NON-NLS-1$ //$NON-NLS-2$
+	    	}
+			    	
+	    	final boolean cache = "cached".equalsIgnoreCase(vdb.getPropertyValue("UseConnectorMetadata")); //$NON-NLS-1$ //$NON-NLS-2$
+	    	final File cacheFile = buildCachedModelFileName(unit, vdb, model.getName());
+	    	boolean loaded = false;
+	    	if (cache) {
+				MetadataStore store = this.serializer.loadSafe(cacheFile, MetadataStore.class);
+				if (store != null) {
+					vdbStore.addStore(store);
+					loaded = true;
+				}
+	    	}
+	    	
+	    	if (!loaded) {
+	    		String msg = RuntimePlugin.Util.getString("model_metadata_loading", vdb.getName()+"-"+vdb.getVersion(), model.getName(), SimpleDateFormat.getInstance().format(new Date())); //$NON-NLS-1$ //$NON-NLS-2$
+	    		final ValidationError addedError = model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), msg); 
+	    		LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
+	    		threadPool.run(new Runnable() {
+					@Override
+					public void run() {
+						loadMetadata(vdb, model, cache, cacheFile, vdbStore, cmr, addedError);
+					}
+	    		});
+	    	}
+		}
+	}	
+    
+    private void loadMetadata(VDBMetaData vdb, ModelMetaData model, boolean cache, File cacheFile, MetadataStoreGroup vdbStore, ConnectorManagerRepository cmr, ValidationError addedError) {
+    	Exception exception = null;
+    	
+    	boolean loaded = false;
+    	for (String sourceName: model.getSourceNames()) {
+    		ConnectorManager cm = cmr.getConnectorManager(sourceName);
+    		if (cm == null) {
+    			continue;
+    		}
+    		try {
+    			MetadataStore store = cm.getMetadata(model.getName(), this.vdbRepository.getBuiltinDatatypes(), model.getProperties());
+    			if (cache) {
+    				this.serializer.saveAttachment(cacheFile, store);
+    			}
+    			vdbStore.addStore(store);
+    			model.removeError(addedError);
+    			loaded = true;
+    			break;
+			} catch (TranslatorException e) {
+				if (exception == null) {
+					exception = e;
+				}
+			} catch (IOException e) {
+				if (exception == null) {
+					exception = e;
+				}				
+			}
+    	}
+    	
+    	synchronized (this) {
+	    	if (!loaded) {
+	    		vdb.setStatus(VDB.Status.INACTIVE);
+	    		String msg = RuntimePlugin.Util.getString("failed_to_retrive_metadata", vdb.getName()+"-"+vdb.getVersion(), model.getName()); //$NON-NLS-1$ //$NON-NLS-2$
+		    	model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), msg); 
+		    	if (exception != null) {
+		    		model.addError(ModelMetaData.ValidationError.Severity.ERROR.toString(), exception.getMessage());     		
+		    	}
+		    	LogManager.logWarning(LogConstants.CTX_RUNTIME, msg);
+	    	}
+	    	else {
+	    		if (vdb.isValid()) {
+	    			this.vdbRepository.updateVDB(vdb.getName(), vdb.getVersion());
+					vdb.setStatus(VDB.Status.ACTIVE);
+					LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_activated",vdb.getName(), vdb.getVersion())); //$NON-NLS-1$    			
+	    		}
+	    	}
+    	}
+    }
+    
+	private File buildCachedModelFileName(VFSDeploymentUnit unit, VDBMetaData vdb, String modelName) {
+		return this.serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()+"_"+modelName); //$NON-NLS-1$ //$NON-NLS-2$
+	}    
+	
+	static File buildCachedVDBFileName(ObjectSerializer serializer, VFSDeploymentUnit unit, VDBMetaData vdb) {
+		return serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()); //$NON-NLS-1$
+	} 	
+	
+	public void setTranslatorRepository(TranslatorRepository repo) {
+		this.translatorRepository = repo;
+	}	
+	
+	public void setContainerLifeCycleListener(ContainerLifeCycleListener listener) {
+		shutdownListener = listener;
+	}
+	
+	public void setThreadPool(ThreadPool pool) {
+		this.threadPool = pool;
+	}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.deployers;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.XMLConstants;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.validation.Schema;
-import javax.xml.validation.SchemaFactory;
-
-import org.jboss.deployers.spi.DeploymentException;
-import org.jboss.deployers.spi.deployer.managed.ManagedObjectCreator;
-import org.jboss.deployers.structure.spi.DeploymentUnit;
-import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.factory.ManagedObjectFactory;
-import org.jboss.virtual.VirtualFile;
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.adminapi.impl.VDBTranslatorMetaData;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
-import org.teiid.metadata.VdbConstants;
-import org.teiid.metadata.index.IndexConstants;
-import org.teiid.metadata.index.IndexMetadataFactory;
-import org.teiid.runtime.RuntimePlugin;
-import org.xml.sax.SAXException;
-
-
-/**
- * This file loads the "vdb.xml" file inside a ".vdb" file, along with all the metadata in the .INDEX files
- */
-public class VDBParserDeployer extends BaseMultipleVFSParsingDeployer<VDBMetaData> implements ManagedObjectCreator {
-	private ObjectSerializer serializer;
-	private VDBRepository vdbRepository;
-	 
-	public VDBParserDeployer() {
-		super(VDBMetaData.class, getCustomMappings(), IndexConstants.NAME_DELIM_CHAR+IndexConstants.INDEX_EXT, IndexMetadataFactory.class, VdbConstants.MODEL_EXT, UDFMetaData.class);
-		setAllowMultipleFiles(true);
-	}
-
-	private static Map<String, Class<?>> getCustomMappings() {
-		Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
-		mappings.put(VdbConstants.DEPLOYMENT_FILE, VDBMetaData.class);
-		// this not required but the to make the framework with extended classes 
-		// this required otherwise different version of parse is invoked.
-		mappings.put("undefined", UDFMetaData.class); //$NON-NLS-1$
-		return mappings;
-	}
-	
-	@Override
-	protected <U> U parse(VFSDeploymentUnit unit, Class<U> expectedType, VirtualFile file, Object root) throws Exception {
-		if (expectedType.equals(VDBMetaData.class)) {
-			Unmarshaller un = getUnMarsheller();
-			VDBMetaData def = (VDBMetaData)un.unmarshal(file.openStream());
-			
-			return expectedType.cast(def);
-		}
-		else if (expectedType.equals(UDFMetaData.class)) {
-			if (root == null) {
-				root = unit.getAttachment(UDFMetaData.class);
-				if (root == null) {
-					root = new UDFMetaData();
-					unit.addAttachment(UDFMetaData.class, UDFMetaData.class.cast(root));
-				}
-			}
-			UDFMetaData udf = UDFMetaData.class.cast(root);		
-			udf.addModelFile(file);
-			
-			return expectedType.cast(udf);
-		}		
-		else if (expectedType.equals(IndexMetadataFactory.class)) {
-			if (root == null) {
-				root = unit.getAttachment(IndexMetadataFactory.class);
-				if (root == null) {
-					root = new IndexMetadataFactory();
-				}
-			}
-			IndexMetadataFactory imf = IndexMetadataFactory.class.cast(root);
-			imf.addIndexFile(file);
-			unit.addAttachment(IndexMetadataFactory.class, imf);
-			return expectedType.cast(imf);
-		}
-		else {
-			throw new IllegalArgumentException("Cannot match arguments: expectedClass=" + expectedType ); //$NON-NLS-1$
-		}		
-	}
-
-	static Unmarshaller getUnMarsheller() throws JAXBException, SAXException {
-		JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {VDBMetaData.class});
-		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
-		Schema schema = schemaFactory.newSchema(VDBMetaData.class.getResource("/vdb-deployer.xsd")); //$NON-NLS-1$
-		Unmarshaller un = jc.createUnmarshaller();
-		un.setSchema(schema);
-		return un;
-	}
-	
-	@Override
-	protected VDBMetaData mergeMetaData(VFSDeploymentUnit unit, Map<Class<?>, List<Object>> metadata) throws Exception {
-		VDBMetaData vdb = getInstance(metadata, VDBMetaData.class);
-		UDFMetaData udf = getInstance(metadata, UDFMetaData.class);
-		IndexMetadataFactory imf = getInstance(metadata, IndexMetadataFactory.class);
-		
-		if (vdb == null) {
-			LogManager.logError(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("invlaid_vdb_file",unit.getRoot().getName())); //$NON-NLS-1$
-			return null;
-		}
-		
-		vdb.setUrl(unit.getRoot().toURL());		
-		
-		// build the metadata store
-		if (imf != null) {
-			imf.addEntriesPlusVisibilities(unit.getRoot(), vdb);
-			unit.addAttachment(IndexMetadataFactory.class, imf);
-							
-			// add the cached store.
-			File cacheFile = this.serializer.getAttachmentPath(unit, vdb.getName()+"_"+vdb.getVersion()); //$NON-NLS-1$
-			MetadataStoreGroup stores = this.serializer.loadSafe(cacheFile, MetadataStoreGroup.class);
-			if (stores == null) {
-				stores = new MetadataStoreGroup();
-				stores.addStore(imf.getMetadataStore(vdbRepository.getSystemStore().getDatatypes()));
-			}
-			unit.addAttachment(MetadataStoreGroup.class, stores);				
-		}
-		
-		if (udf != null) {
-			// load the UDF
-			for(Model model:vdb.getModels()) {
-				if (model.getModelType().equals(Model.Type.FUNCTION)) {
-					String path = ((ModelMetaData)model).getPath();
-					if (path == null) {
-						throw new DeploymentException(RuntimePlugin.Util.getString("invalid_udf_file", model.getName())); //$NON-NLS-1$
-					}
-					udf.buildFunctionModelFile(path);
-				}
-			}		
-			
-			// If the UDF file is enclosed then attach it to the deployment artifact
-			unit.addAttachment(UDFMetaData.class, udf);
-		}
-				
-		LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" has been parsed."); //$NON-NLS-1$ //$NON-NLS-2$
-		return vdb;
-	}
-	
-	public void setVdbRepository(VDBRepository vdbRepository) {
-		this.vdbRepository = vdbRepository;
-	}
-	
-	public void setObjectSerializer(ObjectSerializer serializer) {
-		this.serializer = serializer;
-	}		
-	
-	private ManagedObjectFactory mof;
-	
-	@Override
-	public void build(DeploymentUnit unit, Set<String> attachmentNames, Map<String, ManagedObject> managedObjects)
-		throws DeploymentException {
-	          
-		ManagedObject vdbMO = managedObjects.get(VDBMetaData.class.getName());
-		if (vdbMO != null) {
-			VDBMetaData vdb = (VDBMetaData) vdbMO.getAttachment();
-			for (Model m : vdb.getModels()) {
-				ManagedObject mo = this.mof.initManagedObject(m, ModelMetaData.class, m.getName(),m.getName());
-				if (mo == null) {
-					throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
-				}
-				managedObjects.put(mo.getName(), mo);
-			}
-			
-			for (Translator t: vdb.getOverrideTranslators()) {
-				ManagedObject mo = this.mof.initManagedObject(t, VDBTranslatorMetaData.class, t.getName(), t.getName());
-				if (mo == null) {
-					throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
-				}
-				managedObjects.put(mo.getName(), mo);				
-			}
-		}
-	}	
-	
-	public void setManagedObjectFactory(ManagedObjectFactory mof) {
-		this.mof = mof;
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java (from rev 2774, trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,222 @@
+/*
+ * 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.deployers;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.XMLConstants;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.validation.Schema;
+import javax.xml.validation.SchemaFactory;
+
+import org.jboss.deployers.spi.DeploymentException;
+import org.jboss.deployers.spi.deployer.managed.ManagedObjectCreator;
+import org.jboss.deployers.structure.spi.DeploymentUnit;
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
+import org.jboss.managed.api.ManagedObject;
+import org.jboss.managed.api.factory.ManagedObjectFactory;
+import org.jboss.virtual.VirtualFile;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.VDBTranslatorMetaData;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.VdbConstants;
+import org.teiid.metadata.index.IndexConstants;
+import org.teiid.metadata.index.IndexMetadataFactory;
+import org.teiid.runtime.RuntimePlugin;
+import org.xml.sax.SAXException;
+
+
+/**
+ * This file loads the "vdb.xml" file inside a ".vdb" file, along with all the metadata in the .INDEX files
+ */
+public class VDBParserDeployer extends BaseMultipleVFSParsingDeployer<VDBMetaData> implements ManagedObjectCreator {
+	private ObjectSerializer serializer;
+	private VDBRepository vdbRepository;
+	 
+	public VDBParserDeployer() {
+		super(VDBMetaData.class, getCustomMappings(), IndexConstants.NAME_DELIM_CHAR+IndexConstants.INDEX_EXT, IndexMetadataFactory.class, VdbConstants.MODEL_EXT, UDFMetaData.class);
+		setAllowMultipleFiles(true);
+	}
+
+	private static Map<String, Class<?>> getCustomMappings() {
+		Map<String, Class<?>> mappings = new HashMap<String, Class<?>>();
+		mappings.put(VdbConstants.DEPLOYMENT_FILE, VDBMetaData.class);
+		// this not required but the to make the framework with extended classes 
+		// this required otherwise different version of parse is invoked.
+		mappings.put("undefined", UDFMetaData.class); //$NON-NLS-1$
+		return mappings;
+	}
+	
+	@Override
+	protected <U> U parse(VFSDeploymentUnit unit, Class<U> expectedType, VirtualFile file, Object root) throws Exception {
+		if (expectedType.equals(VDBMetaData.class)) {
+			Unmarshaller un = getUnMarsheller();
+			VDBMetaData def = (VDBMetaData)un.unmarshal(file.openStream());
+			
+			return expectedType.cast(def);
+		}
+		else if (expectedType.equals(UDFMetaData.class)) {
+			if (root == null) {
+				root = unit.getAttachment(UDFMetaData.class);
+				if (root == null) {
+					root = new UDFMetaData();
+					unit.addAttachment(UDFMetaData.class, UDFMetaData.class.cast(root));
+				}
+			}
+			UDFMetaData udf = UDFMetaData.class.cast(root);		
+			udf.addModelFile(file);
+			
+			return expectedType.cast(udf);
+		}		
+		else if (expectedType.equals(IndexMetadataFactory.class)) {
+			if (root == null) {
+				root = unit.getAttachment(IndexMetadataFactory.class);
+				if (root == null) {
+					root = new IndexMetadataFactory();
+				}
+			}
+			IndexMetadataFactory imf = IndexMetadataFactory.class.cast(root);
+			imf.addIndexFile(file);
+			unit.addAttachment(IndexMetadataFactory.class, imf);
+			return expectedType.cast(imf);
+		}
+		else {
+			throw new IllegalArgumentException("Cannot match arguments: expectedClass=" + expectedType ); //$NON-NLS-1$
+		}		
+	}
+
+	static Unmarshaller getUnMarsheller() throws JAXBException, SAXException {
+		JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {VDBMetaData.class});
+		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
+		Schema schema = schemaFactory.newSchema(VDBMetaData.class.getResource("/vdb-deployer.xsd")); //$NON-NLS-1$
+		Unmarshaller un = jc.createUnmarshaller();
+		un.setSchema(schema);
+		return un;
+	}
+	
+	@Override
+	protected VDBMetaData mergeMetaData(VFSDeploymentUnit unit, Map<Class<?>, List<Object>> metadata) throws Exception {
+		VDBMetaData vdb = getInstance(metadata, VDBMetaData.class);
+		UDFMetaData udf = getInstance(metadata, UDFMetaData.class);
+		IndexMetadataFactory imf = getInstance(metadata, IndexMetadataFactory.class);
+		
+		if (vdb == null) {
+			LogManager.logError(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("invlaid_vdb_file",unit.getRoot().getName())); //$NON-NLS-1$
+			return null;
+		}
+		
+		vdb.setUrl(unit.getRoot().toURL());		
+		
+		// build the metadata store
+		if (imf != null) {
+			imf.addEntriesPlusVisibilities(unit.getRoot(), vdb);
+			unit.addAttachment(IndexMetadataFactory.class, imf);
+							
+			// add the cached store.
+			File cacheFile = VDBDeployer.buildCachedVDBFileName(this.serializer, unit, vdb);
+			// check to see if the vdb has been modified when server is down; if it is then clear the old files
+			if (this.serializer.isStale(cacheFile, unit.getRoot().getLastModified())) {
+				this.serializer.removeAttachments(unit);
+				LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" old cached metadata has been removed"); //$NON-NLS-1$ //$NON-NLS-2$				
+			}
+			MetadataStoreGroup stores = this.serializer.loadSafe(cacheFile, MetadataStoreGroup.class);
+			if (stores == null) {				
+				// start to build the new metadata 
+				stores = new MetadataStoreGroup();
+				stores.addStore(imf.getMetadataStore(vdbRepository.getSystemStore().getDatatypes()));
+			}
+			else {
+				LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" has being loaded from cached metadata"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+			unit.addAttachment(MetadataStoreGroup.class, stores);				
+		}
+		
+		if (udf != null) {
+			// load the UDF
+			for(Model model:vdb.getModels()) {
+				if (model.getModelType().equals(Model.Type.FUNCTION)) {
+					String path = ((ModelMetaData)model).getPath();
+					if (path == null) {
+						throw new DeploymentException(RuntimePlugin.Util.getString("invalid_udf_file", model.getName())); //$NON-NLS-1$
+					}
+					udf.buildFunctionModelFile(path);
+				}
+			}		
+			
+			// If the UDF file is enclosed then attach it to the deployment artifact
+			unit.addAttachment(UDFMetaData.class, udf);
+		}
+				
+		LogManager.logTrace(LogConstants.CTX_RUNTIME, "VDB "+unit.getRoot().getName()+" has been parsed."); //$NON-NLS-1$ //$NON-NLS-2$
+		return vdb;
+	}
+	
+	public void setVdbRepository(VDBRepository vdbRepository) {
+		this.vdbRepository = vdbRepository;
+	}
+	
+	public void setObjectSerializer(ObjectSerializer serializer) {
+		this.serializer = serializer;
+	}		
+	
+	private ManagedObjectFactory mof;
+	
+	@Override
+	public void build(DeploymentUnit unit, Set<String> attachmentNames, Map<String, ManagedObject> managedObjects)
+		throws DeploymentException {
+	          
+		ManagedObject vdbMO = managedObjects.get(VDBMetaData.class.getName());
+		if (vdbMO != null) {
+			VDBMetaData vdb = (VDBMetaData) vdbMO.getAttachment();
+			for (Model m : vdb.getModels()) {
+				ManagedObject mo = this.mof.initManagedObject(m, ModelMetaData.class, m.getName(),m.getName());
+				if (mo == null) {
+					throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
+				}
+				managedObjects.put(mo.getName(), mo);
+			}
+			
+			for (Translator t: vdb.getOverrideTranslators()) {
+				ManagedObject mo = this.mof.initManagedObject(t, VDBTranslatorMetaData.class, t.getName(), t.getName());
+				if (mo == null) {
+					throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
+				}
+				managedObjects.put(mo.getName(), mo);				
+			}
+		}
+	}	
+	
+	public void setManagedObjectFactory(ManagedObjectFactory mof) {
+		this.mof = mof;
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java
===================================================================
--- trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,239 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright (C) 2008 Red Hat, Inc.
- * Licensed to Red Hat, Inc. under one or more contributor 
- * license agreements.  See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.transport;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import java.io.ByteArrayInputStream;
-import java.io.Serializable;
-import java.io.StringReader;
-import java.net.InetSocketAddress;
-import java.util.Properties;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-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.SessionToken;
-import org.teiid.client.util.ResultsFuture;
-import org.teiid.common.buffer.BufferManagerFactory;
-import org.teiid.core.ComponentNotFoundException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.crypto.NullCryptor;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.dqp.service.SessionService;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.ConnectionException;
-import org.teiid.net.TeiidURL;
-import org.teiid.net.socket.SocketServerConnection;
-import org.teiid.net.socket.SocketServerConnectionFactory;
-import org.teiid.net.socket.SocketUtil;
-import org.teiid.net.socket.UrlServerDiscovery;
-import org.teiid.transport.TestSocketRemoting.FakeService;
-
-
- at SuppressWarnings("nls")
-public class TestCommSockets {
-
-	SocketListener listener;
-	private SocketServerConnectionFactory sscf;
-	private InetSocketAddress addr;
-
-	@Before public void setUp() {
-		addr = new InetSocketAddress(0);
-	}
-	
-	@After public void tearDown() throws Exception {
-		if (listener != null) {
-			listener.stop();
-		}
-	}
-
-	@Test(expected=CommunicationException.class) public void testFailedConnect() throws Exception {
-		SSLConfiguration config = new SSLConfiguration();
-		listener = new SocketListener(addr.getPort(), addr.getAddress().getHostAddress(),1024, 1024, 1, config, null, BufferManagerFactory.getStandaloneBufferManager());
-
-		Properties p = new Properties();
-		String url = new TeiidURL(addr.getHostName(), listener.getPort() - 1, false).getAppServerURL();
-		p.setProperty(TeiidURL.CONNECTION.SERVER_URL, url); //wrong port
-		SocketServerConnectionFactory.getInstance().getConnection(p);
-	}
-
-	@Test public void testConnectWithoutPooling() throws Exception {
-		Properties p = new Properties();
-		p.setProperty("org.teiid.sockets.maxCachedInstances", String.valueOf(0)); //$NON-NLS-1$
-		SocketServerConnection conn = helpEstablishConnection(false, new SSLConfiguration(), p);
-		SocketListenerStats stats = listener.getStats();
-		assertEquals(2, stats.objectsRead); // handshake response, logon,
-		assertEquals(1, stats.sockets);
-		conn.close();
-		stats = listener.getStats();
-		assertEquals(1, stats.maxSockets);
-		assertEquals(3, stats.objectsRead); // handshake response, logon, logoff
-		if (stats.sockets > 0) {
-			// there is a timing issue here, since the effect of shutdown on the
-			// server side can be delayed
-			Thread.sleep(500);
-		}
-		stats = listener.getStats();
-		assertEquals(0, stats.sockets);
-	}
-	
-	@Test public void testConnectWithPooling() throws Exception {
-		SocketServerConnection conn = helpEstablishConnection(false);
-		SocketListenerStats stats = listener.getStats();
-		assertEquals(2, stats.objectsRead); // handshake response, logon,
-		assertEquals(1, stats.sockets);
-		conn.close();
-		stats = listener.getStats();
-		assertEquals(1, stats.maxSockets);
-		assertEquals(3, stats.objectsRead); // handshake response, logon, logoff
-		stats = listener.getStats();
-		assertEquals(1, stats.sockets);
-		conn = helpEstablishConnection(false);
-		conn.close();
-		stats = listener.getStats();
-		assertEquals(1, stats.sockets);
-		assertEquals(1, stats.maxSockets);
-	}
-
-	@Test public void testLobs() throws Exception {
-		SocketServerConnection conn = helpEstablishConnection(false);
-		FakeService fs = conn.getService(FakeService.class);
-		assertEquals(150, fs.lobMethod(new ByteArrayInputStream(new byte[100]), new StringReader(new String(new char[50]))));
-		assertEquals(0, fs.lobMethod(new ByteArrayInputStream(new byte[0]), new StringReader(new String(new char[0]))));
-		assertEquals((1 << 17) + 50, fs.lobMethod(new ByteArrayInputStream(new byte[1 << 17]), new StringReader(new String(new char[50]))));
-	}
-	
-	@Test public void testServerRemoteStreaming() throws Exception {
-		SocketServerConnection conn = helpEstablishConnection(false);
-		FakeService fs = conn.getService(FakeService.class);
-		assertEquals("hello world", ObjectConverterUtil.convertToString(fs.getReader()));
-		assertTrue(Serializable.class.isAssignableFrom(fs.getReader().getClass()));
-	}
-
-	@Test public void testConnectWithoutClientEncryption() throws Exception {
-		SSLConfiguration config = new SSLConfiguration();
-		config.setMode(SSLConfiguration.DISABLED);
-		SocketServerConnection conn = helpEstablishConnection(false, config, new Properties());
-		assertTrue(conn.selectServerInstance().getCryptor() instanceof NullCryptor);
-		conn.close();
-	}
-
-	private SocketServerConnection helpEstablishConnection(boolean secure) throws CommunicationException, ConnectionException {
-		return helpEstablishConnection(secure, new SSLConfiguration(), new Properties());
-	}
-
-	private SocketServerConnection helpEstablishConnection(boolean clientSecure, SSLConfiguration config, Properties socketConfig) throws CommunicationException,
-			ConnectionException {
-		if (listener == null) {
-			ClientServiceRegistryImpl server = new ClientServiceRegistryImpl();
-			server.registerClientService(ILogon.class, new LogonImpl(mock(SessionService.class), "fakeCluster") { //$NON-NLS-1$
-				@Override
-				public LogonResult logon(Properties connProps)
-						throws LogonException, ComponentNotFoundException {
-					return new LogonResult(new SessionToken("dummy"), "x", 1, "z");
-				}
-				
-				@Override
-				public ResultsFuture<?> ping() throws InvalidSessionException,
-						TeiidComponentException {
-					return ResultsFuture.NULL_FUTURE;
-				}
-				
-				@Override
-				public void assertIdentity(SessionToken checkSession)
-						throws InvalidSessionException, TeiidComponentException {
-					return;
-				}
-
-			}, null); 
-			server.registerClientService(FakeService.class, new TestSocketRemoting.FakeServiceImpl(), null);
-			listener = new SocketListener(addr.getPort(), addr.getAddress().getHostAddress(), 1024, 1024, 1, config, server, BufferManagerFactory.getStandaloneBufferManager());
-			
-			SocketListenerStats stats = listener.getStats();
-			assertEquals(0, stats.maxSockets);
-			assertEquals(0, stats.objectsRead);
-			assertEquals(0, stats.objectsWritten);
-			assertEquals(0, stats.sockets);
-		}
-
-		Properties p = new Properties();
-		String url = new TeiidURL(addr.getHostName(), listener.getPort(), clientSecure).getAppServerURL();
-		p.setProperty(TeiidURL.CONNECTION.SERVER_URL, url); 
-		p.setProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, UrlServerDiscovery.class.getName());
-		if (sscf == null) {
-			sscf = new SocketServerConnectionFactory();
-			sscf.initialize(socketConfig);
-		}
-		return sscf.getConnection(p);
-	}
-
-	@Test public void testSSLConnectWithNonSSLServer() throws Exception {
-		try {
-			helpEstablishConnection(true);
-			fail("exception expected"); //$NON-NLS-1$
-		} catch (CommunicationException e) {
-			
-		}
-	}
-
-	@Test public void testAnonSSLConnect() throws Exception {
-		SSLConfiguration config = new SSLConfiguration();
-		config.setMode(SSLConfiguration.ENABLED);
-		config.setAuthenticationMode(SSLConfiguration.ANONYMOUS);
-		Properties p = new Properties();
-		helpEstablishConnection(true, config, p);
-		SocketServerConnection conn = helpEstablishConnection(true, config, p);
-		conn.close();
-	}
-	
-	@Test(expected=CommunicationException.class) public void testNonSSLConnectWithSSLServer() throws Exception {
-		SSLConfiguration config = new SSLConfiguration();
-		config.setMode(SSLConfiguration.ENABLED);
-		config.setAuthenticationMode(SSLConfiguration.ANONYMOUS);
-		Properties p = new Properties();
-		p.setProperty(SocketUtil.ALLOW_ANON, Boolean.FALSE.toString());
-		helpEstablishConnection(true, config, p);
-	}
-	
-	@Test public void testSelectNewInstance() throws Exception {
-		SSLConfiguration config = new SSLConfiguration();
-		Properties p = new Properties();
-		SocketServerConnection conn = helpEstablishConnection(false, config, p);
-		SocketListenerStats stats = listener.getStats();
-		assertEquals(2, stats.objectsRead); // handshake response, logon,
-		assertEquals(1, stats.sockets);
-		conn.cleanUp();
-		assertTrue(conn.isOpen(1000));
-		stats = listener.getStats();
-		assertEquals(5, stats.objectsRead); // ping (pool test), assert identity, ping (isOpen)
-		assertEquals(1, stats.sockets);
-		conn.close();
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java (from rev 2774, trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/runtime/src/test/java/org/teiid/transport/TestCommSockets.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,249 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright (C) 2008 Red Hat, Inc.
+ * Licensed to Red Hat, Inc. under one or more contributor 
+ * license agreements.  See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.transport;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.Serializable;
+import java.io.StringReader;
+import java.net.InetSocketAddress;
+import java.util.Properties;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+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.SessionToken;
+import org.teiid.client.util.ResultsFuture;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.core.ComponentNotFoundException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.crypto.NullCryptor;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.dqp.service.SessionService;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.ConnectionException;
+import org.teiid.net.TeiidURL;
+import org.teiid.net.socket.SocketServerConnection;
+import org.teiid.net.socket.SocketServerConnectionFactory;
+import org.teiid.net.socket.SocketUtil;
+import org.teiid.net.socket.UrlServerDiscovery;
+import org.teiid.transport.TestSocketRemoting.FakeService;
+
+
+ at SuppressWarnings("nls")
+public class TestCommSockets {
+
+	SocketListener listener;
+	private SocketServerConnectionFactory sscf;
+	private InetSocketAddress addr;
+
+	@Before public void setUp() {
+		addr = new InetSocketAddress(0);
+	}
+	
+	@After public void tearDown() throws Exception {
+		if (listener != null) {
+			listener.stop();
+		}
+	}
+
+	@Test(expected=CommunicationException.class) public void testFailedConnect() throws Exception {
+		SSLConfiguration config = new SSLConfiguration();
+		listener = new SocketListener(addr.getPort(), addr.getAddress().getHostAddress(),1024, 1024, 1, config, null, BufferManagerFactory.getStandaloneBufferManager());
+
+		Properties p = new Properties();
+		String url = new TeiidURL(addr.getHostName(), listener.getPort() - 1, false).getAppServerURL();
+		p.setProperty(TeiidURL.CONNECTION.SERVER_URL, url); //wrong port
+		SocketServerConnectionFactory.getInstance().getConnection(p);
+	}
+
+	@Test public void testConnectWithoutPooling() throws Exception {
+		Properties p = new Properties();
+		p.setProperty("org.teiid.sockets.maxCachedInstances", String.valueOf(0)); //$NON-NLS-1$
+		SocketServerConnection conn = helpEstablishConnection(false, new SSLConfiguration(), p);
+		SocketListenerStats stats = listener.getStats();
+		assertEquals(2, stats.objectsRead); // handshake response, logon,
+		assertEquals(1, stats.sockets);
+		conn.close();
+		stats = listener.getStats();
+		assertEquals(1, stats.maxSockets);
+		assertEquals(3, stats.objectsRead); // handshake response, logon, logoff
+		if (stats.sockets > 0) {
+			// there is a timing issue here, since the effect of shutdown on the
+			// server side can be delayed
+			Thread.sleep(500);
+		}
+		stats = listener.getStats();
+		assertEquals(0, stats.sockets);
+	}
+	
+	@Test public void testConnectWithPooling() throws Exception {
+		SocketServerConnection conn = helpEstablishConnection(false);
+		SocketListenerStats stats = listener.getStats();
+		assertEquals(2, stats.objectsRead); // handshake response, logon,
+		assertEquals(1, stats.sockets);
+		conn.close();
+		stats = listener.getStats();
+		assertEquals(1, stats.maxSockets);
+		assertEquals(3, stats.objectsRead); // handshake response, logon, logoff
+		stats = listener.getStats();
+		assertEquals(1, stats.sockets);
+		conn = helpEstablishConnection(false);
+		conn.close();
+		stats = listener.getStats();
+		assertEquals(1, stats.sockets);
+		assertEquals(1, stats.maxSockets);
+	}
+
+	@Test public void testLobs() throws Exception {
+		SocketServerConnection conn = helpEstablishConnection(false);
+		FakeService fs = conn.getService(FakeService.class);
+		assertEquals(150, fs.lobMethod(new ByteArrayInputStream(new byte[100]), new StringReader(new String(new char[50]))));
+		assertEquals(0, fs.lobMethod(new ByteArrayInputStream(new byte[0]), new StringReader(new String(new char[0]))));
+		assertEquals((1 << 17) + 50, fs.lobMethod(new ByteArrayInputStream(new byte[1 << 17]), new StringReader(new String(new char[50]))));
+	}
+	
+	@Test public void testServerRemoteStreaming() throws Exception {
+		SocketServerConnection conn = helpEstablishConnection(false);
+		FakeService fs = conn.getService(FakeService.class);
+		assertEquals("hello world", ObjectConverterUtil.convertToString(fs.getReader()));
+		assertTrue(Serializable.class.isAssignableFrom(fs.getReader().getClass()));
+	}
+
+	@Test public void testConnectWithoutClientEncryption() throws Exception {
+		SSLConfiguration config = new SSLConfiguration();
+		config.setMode(SSLConfiguration.DISABLED);
+		SocketServerConnection conn = helpEstablishConnection(false, config, new Properties());
+		assertTrue(conn.selectServerInstance().getCryptor() instanceof NullCryptor);
+		conn.close();
+	}
+
+	private SocketServerConnection helpEstablishConnection(boolean secure) throws CommunicationException, ConnectionException {
+		return helpEstablishConnection(secure, new SSLConfiguration(), new Properties());
+	}
+
+	private SocketServerConnection helpEstablishConnection(boolean clientSecure, SSLConfiguration config, Properties socketConfig) throws CommunicationException,
+			ConnectionException {
+		if (listener == null) {
+			ClientServiceRegistryImpl server = new ClientServiceRegistryImpl();
+			server.registerClientService(ILogon.class, new LogonImpl(mock(SessionService.class), "fakeCluster") { //$NON-NLS-1$
+				@Override
+				public LogonResult logon(Properties connProps)
+						throws LogonException, ComponentNotFoundException {
+					return new LogonResult(new SessionToken("dummy"), "x", 1, "z");
+				}
+				
+				@Override
+				public ResultsFuture<?> ping() throws InvalidSessionException,
+						TeiidComponentException {
+					return ResultsFuture.NULL_FUTURE;
+				}
+				
+				@Override
+				public void assertIdentity(SessionToken checkSession)
+						throws InvalidSessionException, TeiidComponentException {
+					return;
+				}
+
+			}, null); 
+			server.registerClientService(FakeService.class, new TestSocketRemoting.FakeServiceImpl(), null);
+			listener = new SocketListener(addr.getPort(), addr.getAddress().getHostAddress(), 1024, 1024, 1, config, server, BufferManagerFactory.getStandaloneBufferManager());
+			
+			SocketListenerStats stats = listener.getStats();
+			assertEquals(0, stats.maxSockets);
+			assertEquals(0, stats.objectsRead);
+			assertEquals(0, stats.objectsWritten);
+			assertEquals(0, stats.sockets);
+		}
+
+		Properties p = new Properties();
+		String url = new TeiidURL(addr.getHostName(), listener.getPort(), clientSecure).getAppServerURL();
+		p.setProperty(TeiidURL.CONNECTION.SERVER_URL, url); 
+		p.setProperty(TeiidURL.CONNECTION.DISCOVERY_STRATEGY, UrlServerDiscovery.class.getName());
+		if (sscf == null) {
+			sscf = new SocketServerConnectionFactory();
+			sscf.initialize(socketConfig);
+		}
+		return sscf.getConnection(p);
+	}
+
+	@Test public void testSSLConnectWithNonSSLServer() throws Exception {
+		//first make a non-ssl connection to ensure that it's not reused
+		SocketServerConnection conn = helpEstablishConnection(false);
+		conn.close();
+		try {
+			helpEstablishConnection(true);
+			fail("exception expected"); //$NON-NLS-1$
+		} catch (CommunicationException e) {
+			
+		}
+	}
+
+	@Test public void testAnonSSLConnect() throws Exception {
+		SSLConfiguration config = new SSLConfiguration();
+		config.setMode(SSLConfiguration.ENABLED);
+		config.setAuthenticationMode(SSLConfiguration.ANONYMOUS);
+		Properties p = new Properties();
+		p.setProperty("org.teiid.sockets.soTimeout", "100");
+		helpEstablishConnection(true, config, p);
+		SocketServerConnection conn = helpEstablishConnection(true, config, p);
+		conn.close();
+		
+		try {
+			helpEstablishConnection(false, config, p);
+		} catch (CommunicationException e) {
+			
+		}
+	}
+	
+	@Test(expected=CommunicationException.class) public void testNonAnonSSLConnectWithSSLServer() throws Exception {
+		SSLConfiguration config = new SSLConfiguration();
+		config.setMode(SSLConfiguration.ENABLED);
+		config.setAuthenticationMode(SSLConfiguration.ANONYMOUS);
+		Properties p = new Properties();
+		p.setProperty(SocketUtil.ALLOW_ANON, Boolean.FALSE.toString());
+		helpEstablishConnection(true, config, p);
+	}
+	
+	@Test public void testSelectNewInstance() throws Exception {
+		SSLConfiguration config = new SSLConfiguration();
+		Properties p = new Properties();
+		SocketServerConnection conn = helpEstablishConnection(false, config, p);
+		SocketListenerStats stats = listener.getStats();
+		assertEquals(2, stats.objectsRead); // handshake response, logon,
+		assertEquals(1, stats.sockets);
+		conn.cleanUp();
+		assertTrue(conn.isOpen(1000));
+		stats = listener.getStats();
+		assertEquals(5, stats.objectsRead); // ping (pool test), assert identity, ping (isOpen)
+		assertEquals(1, stats.sockets);
+		conn.close();
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml
===================================================================
--- trunk/test-integration/common/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/test-integration/common/pom.xml (from rev 2777, trunk/test-integration/common/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/common/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,138 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.connector.language;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.cdk.unittest.FakeTranslationFactory;
-import org.teiid.language.Condition;
-import org.teiid.language.LanguageFactory;
-import org.teiid.language.LanguageUtil;
-import org.teiid.language.Select;
-
-import junit.framework.TestCase;
-
-
-
-/**
- */
-public class TestLanguageUtil extends TestCase {
-
-    /**
-     * Constructor for TestLanguageUtil.
-     * @param name
-     */
-    public TestLanguageUtil(String name) {
-        super(name);
-    }
-
-    private Condition convertCriteria(String criteriaStr) {
-        // Create ICriteria from criteriaStr
-        TranslationUtility util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
-        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE " + criteriaStr; //$NON-NLS-1$
-        Select query = (Select) util.parseCommand(sql);
-        Condition criteria = query.getWhere();
-        return criteria;
-    }
-    
-    public void helpTestSeparateByAnd(String criteriaStr, String[] expected) throws Exception {
-        Condition criteria = convertCriteria(criteriaStr);
-
-        // Execute        
-        List<Condition> crits = LanguageUtil.separateCriteriaByAnd(criteria);
-        
-        // Build expected and actual sets
-        Set<String> expectedSet = new HashSet<String>(Arrays.asList(expected));
-        Set<String> actualSet = new HashSet<String>();
-        for(int i=0; i<crits.size(); i++) {
-            actualSet.add(crits.get(i).toString());
-        }
-        
-        // Compare
-        assertEquals("Did not get expected criteria pieces", expectedSet, actualSet); //$NON-NLS-1$
-    }
-
-    public void testSeparateCrit_predicate() throws Exception {
-        helpTestSeparateByAnd("intkey = 1", new String[] { "SmallA.IntKey = 1" }); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    public void testSeparateCrit_ORisConjunct() throws Exception {
-        helpTestSeparateByAnd("intkey = 1 OR intkey = 2", new String[] { "SmallA.IntKey = 1 OR SmallA.IntKey = 2" }); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    public void testSeparateCrit_nestedAND() throws Exception {
-        helpTestSeparateByAnd("((intkey = 1 AND intkey = 2) AND (intkey = 3) AND (intkey = 4))",  //$NON-NLS-1$
-            new String[] { "SmallA.IntKey = 1", //$NON-NLS-1$
-                "SmallA.IntKey = 2",  //$NON-NLS-1$
-                "SmallA.IntKey = 3", //$NON-NLS-1$
-                "SmallA.IntKey = 4" }); //$NON-NLS-1$ 
-    }
-
-    public void testSeparateCrit_NOT() throws Exception {
-        helpTestSeparateByAnd("((NOT (intkey = 1 AND intkey = 2)) AND (intkey = 3) AND (intkey = 4))",  //$NON-NLS-1$
-            new String[] { "SmallA.IntKey <> 1 OR SmallA.IntKey <> 2", //$NON-NLS-1$
-                "SmallA.IntKey = 3", //$NON-NLS-1$
-                "SmallA.IntKey = 4" }); //$NON-NLS-1$        
-    }
-
-    public void helpTestCombineCriteria(String primaryStr, String additionalStr, String expected) throws Exception {
-        Condition primaryCrit = (primaryStr == null ? null : convertCriteria(primaryStr));
-        Condition additionalCrit = (additionalStr == null ? null : convertCriteria(additionalStr));
-
-        // Execute        
-        Condition crit = LanguageUtil.combineCriteria(primaryCrit, additionalCrit, LanguageFactory.INSTANCE);
-        
-        // Compare
-        String critStr = (crit == null ? null : crit.toString());
-        assertEquals("Did not get expected criteria", expected, critStr); //$NON-NLS-1$
-    }
-    
-    public void testCombineCrit_bothNull() throws Exception {
-        helpTestCombineCriteria(null, null, null);
-    }
-
-    public void testCombineCrit_primaryNull() throws Exception {
-        helpTestCombineCriteria(null, "intkey = 1", "SmallA.IntKey = 1");  //$NON-NLS-1$//$NON-NLS-2$
-    }
-
-    public void testCombineCrit_additionalNull() throws Exception {
-        helpTestCombineCriteria("intkey = 1", null, "SmallA.IntKey = 1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-
-    public void testCombineCrit_bothPredicates() throws Exception {
-        helpTestCombineCriteria("intkey = 1", "intkey = 2", "SmallA.IntKey = 1 AND SmallA.IntKey = 2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    public void testCombineCrit_primaryPredicate() throws Exception {
-        helpTestCombineCriteria("intkey = 1", "intkey = 2 AND intkey = 3", "SmallA.IntKey = 1 AND SmallA.IntKey = 2 AND SmallA.IntKey = 3"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    public void testCombineCrit_additionalPredicate() throws Exception {
-        helpTestCombineCriteria("intkey = 1 AND intkey = 2", "intkey = 3", "SmallA.IntKey = 1 AND SmallA.IntKey = 2 AND SmallA.IntKey = 3"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java (from rev 2775, trunk/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/common/src/test/java/org/teiid/connector/language/TestLanguageUtil.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,138 @@
+/*
+ * 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.connector.language;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.cdk.unittest.FakeTranslationFactory;
+import org.teiid.language.Condition;
+import org.teiid.language.LanguageFactory;
+import org.teiid.language.LanguageUtil;
+import org.teiid.language.Select;
+
+import junit.framework.TestCase;
+
+
+
+/**
+ */
+public class TestLanguageUtil extends TestCase {
+
+    /**
+     * Constructor for TestLanguageUtil.
+     * @param name
+     */
+    public TestLanguageUtil(String name) {
+        super(name);
+    }
+
+    private Condition convertCriteria(String criteriaStr) {
+        // Create ICriteria from criteriaStr
+        TranslationUtility util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
+        String sql = "SELECT IntKey FROM BQT1.SmallA WHERE " + criteriaStr; //$NON-NLS-1$
+        Select query = (Select) util.parseCommand(sql);
+        Condition criteria = query.getWhere();
+        return criteria;
+    }
+    
+    public void helpTestSeparateByAnd(String criteriaStr, String[] expected) throws Exception {
+        Condition criteria = convertCriteria(criteriaStr);
+
+        // Execute        
+        List<Condition> crits = LanguageUtil.separateCriteriaByAnd(criteria);
+        
+        // Build expected and actual sets
+        Set<String> expectedSet = new HashSet<String>(Arrays.asList(expected));
+        Set<String> actualSet = new HashSet<String>();
+        for(int i=0; i<crits.size(); i++) {
+            actualSet.add(crits.get(i).toString());
+        }
+        
+        // Compare
+        assertEquals("Did not get expected criteria pieces", expectedSet, actualSet); //$NON-NLS-1$
+    }
+
+    public void testSeparateCrit_predicate() throws Exception {
+        helpTestSeparateByAnd("intkey = 1", new String[] { "SmallA.IntKey = 1" }); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    public void testSeparateCrit_ORisConjunct() throws Exception {
+        helpTestSeparateByAnd("intkey = 1 OR intkey = 2", new String[] { "SmallA.IntKey = 1 OR SmallA.IntKey = 2" }); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    public void testSeparateCrit_nestedAND() throws Exception {
+        helpTestSeparateByAnd("((intkey = 1 AND intnum = 2) AND (stringnum = '3') AND (stringkey = '4'))",  //$NON-NLS-1$
+            new String[] { "SmallA.IntKey = 1", //$NON-NLS-1$
+                "SmallA.IntNum = 2",  //$NON-NLS-1$
+                "SmallA.StringNum = '3'", //$NON-NLS-1$
+                "SmallA.StringKey = '4'" }); //$NON-NLS-1$ 
+    }
+
+    public void testSeparateCrit_NOT() throws Exception {
+        helpTestSeparateByAnd("(NOT (intkey = 1 AND intnum = 2) AND (stringnum = '3') AND (stringkey = '4'))",  //$NON-NLS-1$
+            new String[] { "SmallA.IntKey <> 1 OR SmallA.IntNum <> 2", //$NON-NLS-1$
+                "SmallA.StringNum = '3'", //$NON-NLS-1$
+                "SmallA.StringKey = '4'" }); //$NON-NLS-1$        
+    }
+
+    public void helpTestCombineCriteria(String primaryStr, String additionalStr, String expected) throws Exception {
+        Condition primaryCrit = (primaryStr == null ? null : convertCriteria(primaryStr));
+        Condition additionalCrit = (additionalStr == null ? null : convertCriteria(additionalStr));
+
+        // Execute        
+        Condition crit = LanguageUtil.combineCriteria(primaryCrit, additionalCrit, LanguageFactory.INSTANCE);
+        
+        // Compare
+        String critStr = (crit == null ? null : crit.toString());
+        assertEquals("Did not get expected criteria", expected, critStr); //$NON-NLS-1$
+    }
+    
+    public void testCombineCrit_bothNull() throws Exception {
+        helpTestCombineCriteria(null, null, null);
+    }
+
+    public void testCombineCrit_primaryNull() throws Exception {
+        helpTestCombineCriteria(null, "intkey = 1", "SmallA.IntKey = 1");  //$NON-NLS-1$//$NON-NLS-2$
+    }
+
+    public void testCombineCrit_additionalNull() throws Exception {
+        helpTestCombineCriteria("intkey = 1", null, "SmallA.IntKey = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    public void testCombineCrit_bothPredicates() throws Exception {
+        helpTestCombineCriteria("intkey = 1", "intkey = 2", "SmallA.IntKey = 1 AND SmallA.IntKey = 2"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    public void testCombineCrit_primaryPredicate() throws Exception {
+        helpTestCombineCriteria("intkey = 1", "intnum = 2 AND stringkey = '3'", "SmallA.IntKey = 1 AND SmallA.IntNum = 2 AND SmallA.StringKey = '3'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    public void testCombineCrit_additionalPredicate() throws Exception {
+        helpTestCombineCriteria("intkey = 1 AND intnum = 2", "stringkey = '3'", "SmallA.IntKey = 1 AND SmallA.IntNum = 2 AND SmallA.StringKey = '3'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml
===================================================================
--- trunk/test-integration/db/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/test-integration/db/pom.xml (from rev 2777, trunk/test-integration/db/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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.Alpha1/test-integration/db/src/assembly/binaries.xml
===================================================================
--- trunk/test-integration/db/src/assembly/binaries.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,110 +0,0 @@
-<!--This script builds a kit for the ctc-client -->
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
-  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
-
-  
-  <id>kit</id>
-  
-  <formats>
-	<format>zip</format>
-  </formats>
-
-  <includeBaseDirectory>false</includeBaseDirectory>
-  <baseDirectory>server</baseDirectory>
-    
-  <dependencySets>
-
-    <dependencySet>
-	  <outputDirectory>/ant</outputDirectory>
-
-      <useProjectArtifact>false</useProjectArtifact>      
-      <useTransitiveDependencies>true</useTransitiveDependencies>
-      <useTransitiveFiltering>false</useTransitiveFiltering>
-      <useDefaultExcludes>true</useDefaultExcludes>
-      <unpack>false</unpack>
-
-       <includes>
-		<include>org.apache.ant:ant</include>
-		<include>org.apache.ant:ant-launcher</include>
-      	<include>ant-contrib:cpptasks</include>
-		<include>ant-contrib:ant-contrib</include>
-      </includes>
-
-    </dependencySet>
-
-
-    <dependencySet>
-	  <outputDirectory>/lib</outputDirectory>
-
-      <useProjectArtifact>false</useProjectArtifact>      
-      <useTransitiveDependencies>true</useTransitiveDependencies>
-      <useTransitiveFiltering>false</useTransitiveFiltering>
-      <useDefaultExcludes>true</useDefaultExcludes>
-      <unpack>false</unpack>
-
-       <includes>
-      	<include>commons-collections:commons-collections</include>
-		<include>org.slf4j:slf4j-api</include>
-		<include>org.jboss.teiid:test-integration-common</include>
-		<include>org.jboss.teiid:teiid-common-core</include>
-		<include>org.jboss.teiid:teiid-adminshell</include>
-		<include>org.jboss.teiid:teiid-engine</include>
-		<include>log4j:log4j</include>
-		<include>junit:junit</include>
-		<include>jdom:jdom</include>
-      </includes>
-
-    </dependencySet>
-  </dependencySets>
-
-  <fileSets>
-
-    <fileSet>
-        <directory>install_scripts</directory>
-        <outputDirectory>.</outputDirectory>      
-        <includes>
-          <include>**/*.sh</include>
-        </includes>   
-        <fileMode>755</fileMode>      
-    </fileSet> 
-          
-    <fileSet>
-        <directory>install_scripts</directory>
-        <outputDirectory>.</outputDirectory>      
-        <excludes>
-          <exclude>**/*.sh</exclude>
-        </excludes>      
-    </fileSet> 
-
-
-
-    <fileSet>
-      <directory>src/main/resources/ctc_tests</directory>
-      <outputDirectory>.</outputDirectory>  
-      <includes>
-        <include>runclienttest.sh</include>
-      </includes>
-  
-	  <fileMode>755</fileMode>     
-    </fileSet>
-
-    <fileSet>
-      <directory>src/main/resources</directory>
- 		<outputDirectory>resources</outputDirectory>
-
-    </fileSet>
-
-    <fileSet>
-      <directory>${project.build.directory}</directory>
- 		<outputDirectory>lib</outputDirectory>
-      <includes>
-        <include>*.jar</include>
-      </includes>
-    </fileSet>
-
-  </fileSets>
-
-
-
-</assembly>
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml (from rev 2774, trunk/test-integration/db/src/assembly/binaries.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/assembly/binaries.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,112 @@
+<!--This script builds a kit for the ctc-client -->
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+  
+  <id>kit</id>
+  
+  <formats>
+	<format>zip</format>
+  </formats>
+
+  <includeBaseDirectory>false</includeBaseDirectory>
+  <baseDirectory>server</baseDirectory>
+    
+  <dependencySets>
+
+    <dependencySet>
+	  <outputDirectory>/ant</outputDirectory>
+
+      <useProjectArtifact>false</useProjectArtifact>      
+      <useTransitiveDependencies>true</useTransitiveDependencies>
+      <useTransitiveFiltering>false</useTransitiveFiltering>
+      <useDefaultExcludes>true</useDefaultExcludes>
+      <unpack>false</unpack>
+
+       <includes>
+		<include>org.apache.ant:ant</include>
+		<include>org.apache.ant:ant-launcher</include>
+      	<include>ant-contrib:cpptasks</include>
+		<include>ant-contrib:ant-contrib</include>
+		<include>xerces:xercesImpl</include>
+      </includes>
+
+    </dependencySet>
+
+
+    <dependencySet>
+	  <outputDirectory>/lib</outputDirectory>
+
+      <useProjectArtifact>false</useProjectArtifact>      
+      <useTransitiveDependencies>true</useTransitiveDependencies>
+      <useTransitiveFiltering>false</useTransitiveFiltering>
+      <useDefaultExcludes>true</useDefaultExcludes>
+      <unpack>false</unpack>
+
+       <includes>
+      	<include>commons-collections:commons-collections</include>
+		<include>org.slf4j:slf4j-api</include>
+		<include>org.jboss.teiid:test-integration-common</include>
+		<include>org.jboss.teiid:teiid-common-core</include>
+		<include>org.jboss.teiid:teiid-adminshell</include>
+		<include>org.jboss.teiid:teiid-engine</include>
+		<include>org.jboss.teiid:teiid-client</include>
+		<include>log4j:log4j</include>
+		<include>junit:junit</include>
+		<include>jdom:jdom</include>
+      </includes>
+
+    </dependencySet>
+  </dependencySets>
+
+  <fileSets>
+
+    <fileSet>
+        <directory>install_scripts</directory>
+        <outputDirectory>.</outputDirectory>      
+        <includes>
+          <include>**/*.sh</include>
+        </includes>   
+        <fileMode>755</fileMode>      
+    </fileSet> 
+          
+    <fileSet>
+        <directory>install_scripts</directory>
+        <outputDirectory>.</outputDirectory>      
+        <excludes>
+          <exclude>**/*.sh</exclude>
+        </excludes>      
+    </fileSet> 
+
+
+
+    <fileSet>
+      <directory>src/main/resources/ctc_tests</directory>
+      <outputDirectory>.</outputDirectory>  
+      <includes>
+        <include>runclienttest.sh</include>
+      </includes>
+  
+	  <fileMode>755</fileMode>     
+    </fileSet>
+
+    <fileSet>
+      <directory>src/main/resources</directory>
+ 		<outputDirectory>resources</outputDirectory>
+
+    </fileSet>
+
+    <fileSet>
+      <directory>${project.build.directory}</directory>
+ 		<outputDirectory>lib</outputDirectory>
+      <includes>
+        <include>*.jar</include>
+      </includes>
+    </fileSet>
+
+  </fileSets>
+
+
+
+</assembly>
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,112 +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.test.client;
-
-import java.io.File;
-import java.sql.ResultSet;
-
-import org.teiid.test.framework.exception.QueryTestFailedException;
-
-/**
- * An ExpectedResults represents one set of expected results (referred to as the queryset) identified by the {@link  #getQuerySetID}.   
- * The <code>queryidentifier</code> identify a unique query and corresponds to the expected results file.   
- * 
- * 
- * @author vanhalbert
- *
- */
-public interface ExpectedResults {
-	
-    /**
-     * The results location is where expected result files can be found
-     */
-    public static final String PROP_EXPECTED_RESULTS_DIR_LOC = "results.loc";
-    
-    /**
-     * {@link #PROP_EXPECTED_RESULTS_ROOT_DIR}, if specified, indicates the root directory 
-     * to be prepended to the {@link #PROP_EXPECTED_RESULTS_DIR_LOC} to create the full
-     * directory to find the expected results files.  
-     * 
-     * This property is normally used during the nightly builds so that the query files
-     * will coming from other projects.
-     */
-
-    public static final String PROP_EXPECTED_RESULTS_ROOT_DIR = "results.root.dir";
-
-
-    
-    /**
-     * Return the unique identifier for this query set.
-     * @return
-     */
-    String getQuerySetID();
-
-
-	/**
-	 * Returns the <code>File</code> location for the actual results for the specified
-	 * query identifier. 
-	 * @param queryidentifier
-	 * @return File location for actual results for the specified query
-	 * @throws QueryTestFailedException
-	 *
-	 * @since
-	 */
-	File getResultsFile(String queryidentifier) throws QueryTestFailedException;
-	
-	
-	/**
-	 * Indicates if a query expects to have an <code>Exception</code> to be thrown when the
-	 * query is executed.
-	 * @param queryidentifier
-	 * @return boolean true if the query expects an exception to be thrown
-	 * @throws QueryTestFailedException
-	 */
-	boolean isExceptionExpected(String queryidentifier) throws QueryTestFailedException;
-	
-	
-	Object getMetaData(String queryidentifier);
-	
-	
-	/**
-	 * Called to compare the <code>ResultSet</code> from the executed query to the expected results
-	 * and return the errors.
-	 * @param queryIdentifier
-	 * @param sql
-	 * @param resultSet
-	 * @param actualException
-	 * @param testStatus
-	 * @param isOrdered
-	 * @param updateCnt
-	 * @return Object identifying the errors in the comparison
-	 * @throws QueryTestFailedException
-	 */
-	Object compareResults(final String queryIdentifier,
-			   final String sql,
-               final ResultSet resultSet,
-               final Throwable actualException,
-               final int testStatus,
-               final boolean isOrdered,
-               final int updateCnt,
-               final boolean resultFromQuery) throws QueryTestFailedException;
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ExpectedResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,123 @@
+/*
+ * 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.test.client;
+
+import java.io.File;
+import java.sql.ResultSet;
+
+import org.teiid.test.framework.exception.QueryTestFailedException;
+
+/**
+ * An ExpectedResults represents one set of expected results (referred to as the queryset) identified by the {@link  #getQuerySetID}.   
+ * The <code>queryidentifier</code> identify a unique query and corresponds to the expected results file.   
+ * 
+ * 
+ * @author vanhalbert
+ *
+ */
+public interface ExpectedResults {
+	
+    /**
+     * The results location is where expected result files can be found
+     */
+    public static final String PROP_EXPECTED_RESULTS_DIR_LOC = "results.loc";
+    
+    /**
+     * {@link #PROP_EXPECTED_RESULTS_ROOT_DIR}, if specified, indicates the root directory 
+     * to be prepended to the {@link #PROP_EXPECTED_RESULTS_DIR_LOC} to create the full
+     * directory to find the expected results files.  
+     * 
+     * This property is normally used during the nightly builds so that the query files
+     * will coming from other projects.
+     */
+
+    public static final String PROP_EXPECTED_RESULTS_ROOT_DIR = "results.root.dir";
+
+
+    
+    /**
+     * Return the unique identifier for this query set.
+     * @return
+     */
+    String getQuerySetID();
+
+
+	/**
+	 * Returns the <code>File</code> location for the actual results for the specified
+	 * query identifier. 
+	 * @param queryidentifier
+	 * @return File location for actual results for the specified query
+	 * @throws QueryTestFailedException
+	 *
+	 * @since
+	 */
+	File getResultsFile(String queryidentifier) throws QueryTestFailedException;
+	
+	
+	/**
+	 * @see TestProperties#RESULT_MODES
+	 * 
+	 * Return true if the expected results file is needed in the test.  Either
+	 * for comparison or generation.   It will return false when
+	 * the option <code>TestProperties.RESULT_MODES.NONE</code>
+	 * @return
+	 */
+	boolean isExpectedResultsNeeded();
+	
+	
+	/**
+	 * Indicates if a query expects to have an <code>Exception</code> to be thrown when the
+	 * query is executed.
+	 * @param queryidentifier
+	 * @return boolean true if the query expects an exception to be thrown
+	 * @throws QueryTestFailedException
+	 */
+	boolean isExceptionExpected(String queryidentifier) throws QueryTestFailedException;
+	
+	
+	Object getMetaData(String queryidentifier);
+	
+	
+	/**
+	 * Called to compare the <code>ResultSet</code> from the executed query to the expected results
+	 * and return the errors.
+	 * @param queryIdentifier
+	 * @param sql
+	 * @param resultSet
+	 * @param actualException
+	 * @param testStatus
+	 * @param isOrdered
+	 * @param updateCnt
+	 * @return Object identifying the errors in the comparison
+	 * @throws QueryTestFailedException
+	 */
+	Object compareResults(final String queryIdentifier,
+			   final String sql,
+               final ResultSet resultSet,
+               final Throwable actualException,
+               final int testStatus,
+               final boolean isOrdered,
+               final int updateCnt,
+               final boolean resultFromQuery) throws QueryTestFailedException;
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,306 +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.test.client;
-
-import java.text.SimpleDateFormat;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.junit.Assert;
-import org.teiid.core.util.FileUtils;
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.core.util.StringUtil;
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.ConfigPropertyNames;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.TransactionContainer;
-import org.teiid.test.framework.connection.DataSourceConnection;
-import org.teiid.test.framework.connection.DriverConnection;
-import org.teiid.test.framework.datasource.DataSourceMgr;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-
-
-
-/**
- * TestClient is the starter class for running bulk sql testing against a Teiid server.
- * The bulk testing is about testing a lot of queries against a predefined set of 
- * expected results and providing error files when comparisons don't match.  
- * The process 
- * The bulk testing, in its simplicity, will do the following:
- * <li>use a {@link QueryReader} to read the queries that it will execute</li>
- * <li>based on the results of each query executed, the process will compare the results
- * to the {@link ExpectedResults }.</li>
- * <li>If the {@link TestProperties#PROP_RESULT_MODE} option is set to {@link TestProperties.RESULT_MODES#GENERATE}
- * 	then the process will not perform a comparison, but generate a new set of expected result files that
- * 	can in turn be used as the
- * @author vanhalbert
- *
- */
-public class TestClient  {
-
-    public static final SimpleDateFormat TSFORMAT = new SimpleDateFormat(
-	    "HH:mm:ss.SSS"); //$NON-NLS-1$
-    
-    
-    private Properties overrides = new Properties();
-    
-    static {
-	if (System.getProperty(ConfigPropertyNames.CONFIG_FILE ) == null) {
-		System.setProperty(ConfigPropertyNames.CONFIG_FILE,"./ctc_tests/ctc-test.properties");
-	} else {
-	    System.out.println("Config File Set: " + System.getProperty(ConfigPropertyNames.CONFIG_FILE ));
-	}
-	
-	// the project.loc is used 
-	if (System.getProperty("project.loc" ) == null) {
-		System.setProperty("project.loc",".");
-	}
-
-    }
-
-    public TestClient() {
-
-
-    }
-    
-    public static void main(String[] args) {
-
-	TestClient tc = new TestClient();
-	tc.runTest();
-	
-	
-    }
-    
-    public void runTest() {
-	
-	try {
-    
-	    runScenario();
-	    
-	} catch (Throwable t) {
-	    t.printStackTrace();
-	}
-	
-    }
- 
-    
-    private void runScenario() throws Exception {
-	
-	
-	String scenario_file = ConfigPropertyLoader.getInstance().getProperty(TestProperties.PROP_SCENARIO_FILE);
-	if (scenario_file == null) {
-	    throw new TransactionRuntimeException(TestProperties.PROP_SCENARIO_FILE + " property was not defined");
-	}
-
-	String scenario_name = FileUtils.getBaseFileNameWithoutExtension(scenario_file);
-	
-	TestLogger.log("Starting scenario " + scenario_name);
-	
-	Properties sc_props = PropertiesUtils.load(scenario_file);
-	
-	// 1st perform substitution on the scenario file based on the config and system properties file 
-	// because the next substitution is based on the scenario file
-	Properties sc_updates = getSubstitutedProperties(sc_props);
-	if (!sc_updates.isEmpty()) {
-	    sc_props.putAll(sc_updates);
-	    this.overrides.putAll(sc_props);
-	    
-	}
-	ConfigPropertyLoader.getInstance().setProperties(sc_props);
-	
-	// 2nd perform substitution on current configuration - which will be based on the config properties file
-	Properties config_updates = getSubstitutedProperties(ConfigPropertyLoader.getInstance().getProperties());
-	if (!config_updates.isEmpty()) {
-	    this.overrides.putAll(config_updates);
-	    ConfigPropertyLoader.getInstance().setProperties(config_updates);
-	}
-
-
-	
-	// update the URL with the vdb that is to be used
-	String url = ConfigPropertyLoader.getInstance().getProperty(DriverConnection.DS_URL);
-	String vdb_name = ConfigPropertyLoader.getInstance().getProperty(DataSourceConnection.DS_DATABASENAME);
-	
-	Assert.assertNotNull(DataSourceConnection.DS_DATABASENAME + " property not set, need it for the vdb name", vdb_name);
-	url = StringUtil.replace(url, "${vdb}", vdb_name);
-	
-	ConfigPropertyLoader.getInstance().setProperty(DriverConnection.DS_URL, url);
-	
-	
-	QueryScenario set = ClassFactory.createQueryScenario(scenario_name);
-	
-	TransactionContainer tc = getTransactionContainter();
-
-	runTestCase(set,  tc);
-
-	TestLogger.log("Completed scenario " + scenario_name);
-    }
-    
-    private void runTestCase(QueryScenario queryset,  TransactionContainer tc) throws Exception {
-	String querySetID = null;
-	List<QueryTest> queryTests = null;
-	
-	TestClientTransaction userTxn = new TestClientTransaction(queryset);
-	
-	Iterator<String> qsetIt = queryset.getQuerySetIDs().iterator();
-	TestResultsSummary summary = new TestResultsSummary(queryset.getResultsMode());
-	
-	try {
-        
-        	// iterate over the query set ID's, which there
-        	// should be 1 for each file to be processed
-        	while (qsetIt.hasNext()) {
-        	    querySetID = qsetIt.next();
-        
-        	    TestLogger.logInfo("Start Test Query ID [" + querySetID + "]");
-        
-        	    queryTests = queryset.getQueries(querySetID);
-        
-        		 // the iterator to process the query tests
-        	    Iterator<QueryTest> queryTestIt = null;
-        	    queryTestIt = queryTests.iterator();
-        	    
-        	    ExpectedResults expectedResults = queryset.getExpectedResults(querySetID);
-              	    
-        	    
-        	    long beginTS = System.currentTimeMillis();
-        	    long endTS = 0;
-        	    
-                	while (queryTestIt.hasNext()) {
-                	    QueryTest q = queryTestIt.next();
-                             	    
-                    	    userTxn.init(summary, expectedResults, q);
-                     	    
-                	    // run test
-                    	    try {
-                    		tc.runTransaction(userTxn);
-                    	    } catch (Throwable t) {
-                    		TestLogger.logInfo("Testcase run error: " + t.getLocalizedMessage());
-                    	    }
-        	             
-                	}
-                	
-                	endTS = System.currentTimeMillis();
-                	
-                	TestLogger.logInfo("End Test Query ID [" + querySetID + "]");
-                	
-                	summary.printResults(queryset, querySetID,beginTS, endTS);        	
-          
-        	}
-        	
-   
-	} finally {	
-	    try {
-    		summary.printTotals(queryset);
-    		summary.cleanup();
-	    } catch (Throwable t) {
-		t.printStackTrace();
-	    }
-	    
-		// cleanup all connections created for this test.
-	    
-	    	DataSourceMgr.getInstance().shutdown();
-//		userTxn.getConnectionStrategy().shutdown();
-		ConfigPropertyLoader.reset();
-	}
-
-	
-    }
-
-    
-    protected TransactionContainer getTransactionContainter() {
-	try {
-	    return TransactionFactory.create(ConfigPropertyLoader.getInstance());
-	} catch (QueryTestFailedException e) {
-	    // TODO Auto-generated catch block
-	    e.printStackTrace();
-	    throw new TransactionRuntimeException(e);
-	}
-
-    }
-
-    
-    private Properties getSubstitutedProperties(Properties props) {
-	Properties or = new Properties();
-	
-	Properties configprops = ConfigPropertyLoader.getInstance().getProperties();
-	
-	configprops.putAll(props);
-	
-	or = PropertiesUtils.resolveNestedProperties(configprops);
-	
-	return or;
-
-    }
-
-    
-
-
-    /**
-     * One-time synchronization barrier that allows dynamically reducing the
-     * number of threads expected at the barrier. Captures the timestamp when
-     * all the expected threads arrive at the barrier.
-     * 
-     * @since 4.3
-     */
-//    private static final class TimestampedSynchronizationBarrier {
-//	private int expectedThreads;
-//	private int currentThreads = 0;
-//	private long leaveBarrierTimestamp = -1;
-//
-//	private TimestampedSynchronizationBarrier(int expectedThreads) {
-//	    this.expectedThreads = expectedThreads;
-//	}
-//
-//	private synchronized void barrier(final long waitTime) {
-//	    if ((++currentThreads) == expectedThreads) {
-//		// If all the expected threads have arrived at the barrier, then
-//		// wake them all.
-//		leaveBarrierTimestamp = System.currentTimeMillis();
-//		this.notifyAll();
-//	    } else {
-//		// Otherwise, wait for other threads to arrive.
-//		try {
-//		    wait(waitTime);
-//		} catch (InterruptedException e) {
-//		    System.err
-//			    .println("A thread was unexpectedly interrupted while waiting for other threads to enter the barrier. The measurements for this test will not be accurate.");
-//		    e.printStackTrace(System.err);
-//		    // Let the thread continue on its merry way
-//		}
-//	    }
-//	}
-//
-//	private synchronized void decrementExpectedThreads() {
-//	    if ((--expectedThreads) == currentThreads) {
-//		// If all the remaining threads are already waiting, then wake
-//		// them all.
-//		leaveBarrierTimestamp = System.currentTimeMillis();
-//		this.notifyAll();
-//	    }
-//	}
-//    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClient.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,306 @@
+/*
+ * 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.test.client;
+
+import java.text.SimpleDateFormat;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.junit.Assert;
+import org.teiid.core.util.FileUtils;
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.core.util.StringUtil;
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.TransactionContainer;
+import org.teiid.test.framework.connection.DataSourceConnection;
+import org.teiid.test.framework.connection.DriverConnection;
+import org.teiid.test.framework.datasource.DataSourceMgr;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+
+
+
+/**
+ * TestClient is the starter class for running bulk sql testing against a Teiid server.
+ * The bulk testing is about testing a lot of queries against a predefined set of 
+ * expected results and providing error files when comparisons don't match.  
+ * The process 
+ * The bulk testing, in its simplicity, will do the following:
+ * <li>use a {@link QueryReader} to read the queries that it will execute</li>
+ * <li>based on the results of each query executed, the process will compare the results
+ * to the {@link ExpectedResults }.</li>
+ * <li>If the {@link TestProperties#PROP_RESULT_MODE} option is set to {@link TestProperties.RESULT_MODES#GENERATE}
+ * 	then the process will not perform a comparison, but generate a new set of expected result files that
+ * 	can in turn be used as the
+ * @author vanhalbert
+ *
+ */
+public class TestClient  {
+
+    public static final SimpleDateFormat TSFORMAT = new SimpleDateFormat(
+	    "HH:mm:ss.SSS"); //$NON-NLS-1$
+    
+    
+    private Properties overrides = new Properties();
+    
+    static {
+	if (System.getProperty(ConfigPropertyNames.CONFIG_FILE ) == null) {
+		System.setProperty(ConfigPropertyNames.CONFIG_FILE,"./ctc_tests/ctc-test.properties");
+	} else {
+	    System.out.println("Config File Set: " + System.getProperty(ConfigPropertyNames.CONFIG_FILE ));
+	}
+	
+	// the project.loc is used 
+	if (System.getProperty("project.loc" ) == null) {
+		System.setProperty("project.loc",".");
+	}
+
+    }
+
+    public TestClient() {
+
+
+    }
+    
+    public static void main(String[] args) {
+
+	TestClient tc = new TestClient();
+	tc.runTest();
+	
+	
+    }
+    
+    public void runTest() {
+	
+	try {
+    
+	    runScenario();
+	    
+	} catch (Throwable t) {
+	    t.printStackTrace();
+	}
+	
+    }
+ 
+    
+    private void runScenario() throws Exception {
+	
+	
+	String scenario_file = ConfigPropertyLoader.getInstance().getProperty(TestProperties.PROP_SCENARIO_FILE);
+	if (scenario_file == null) {
+	    throw new TransactionRuntimeException(TestProperties.PROP_SCENARIO_FILE + " property was not defined");
+	}
+
+	String scenario_name = FileUtils.getBaseFileNameWithoutExtension(scenario_file);
+	
+	TestLogger.log("Starting scenario " + scenario_name);
+	
+	Properties sc_props = PropertiesUtils.load(scenario_file);
+	
+	// 1st perform substitution on the scenario file based on the config and system properties file 
+	// because the next substitution is based on the scenario file
+	Properties sc_updates = getSubstitutedProperties(sc_props);
+	if (!sc_updates.isEmpty()) {
+	    sc_props.putAll(sc_updates);
+	    this.overrides.putAll(sc_props);
+	    
+	}
+	ConfigPropertyLoader.getInstance().setProperties(sc_props);
+	
+	// 2nd perform substitution on current configuration - which will be based on the config properties file
+	Properties config_updates = getSubstitutedProperties(ConfigPropertyLoader.getInstance().getProperties());
+	if (!config_updates.isEmpty()) {
+	    this.overrides.putAll(config_updates);
+	    ConfigPropertyLoader.getInstance().setProperties(config_updates);
+	}
+
+
+	
+	// update the URL with the vdb that is to be used
+	String url = ConfigPropertyLoader.getInstance().getProperty(DriverConnection.DS_URL);
+	String vdb_name = ConfigPropertyLoader.getInstance().getProperty(DataSourceConnection.DS_DATABASENAME);
+	
+	Assert.assertNotNull(DataSourceConnection.DS_DATABASENAME + " property not set, need it for the vdb name", vdb_name);
+	url = StringUtil.replace(url, "${vdb}", vdb_name);
+	
+	ConfigPropertyLoader.getInstance().setProperty(DriverConnection.DS_URL, url);
+	
+	
+	QueryScenario set = ClassFactory.createQueryScenario(scenario_name);
+	
+	TransactionContainer tc = getTransactionContainter();
+
+	runTestCase(set,  tc);
+
+	TestLogger.log("Completed scenario " + scenario_name);
+    }
+    
+    private void runTestCase(QueryScenario queryset,  TransactionContainer tc) throws Exception {
+	String querySetID = null;
+	List<QueryTest> queryTests = null;
+	
+	TestClientTransaction userTxn = new TestClientTransaction(queryset);
+	
+	Iterator<String> qsetIt = queryset.getQuerySetIDs().iterator();
+	TestResultsSummary summary = new TestResultsSummary(queryset.getResultsMode());
+	
+	try {
+        
+        	// iterate over the query set ID's, which there
+        	// should be 1 for each file to be processed
+        	while (qsetIt.hasNext()) {
+        	    querySetID = qsetIt.next();
+        
+        	    TestLogger.logInfo("Start Test Query ID [" + querySetID + "]");
+        
+        	    queryTests = queryset.getQueries(querySetID);
+        
+        		 // the iterator to process the query tests
+        	    Iterator<QueryTest> queryTestIt = null;
+        	    queryTestIt = queryTests.iterator();
+        	    
+        	    ExpectedResults expectedResults = queryset.getExpectedResults(querySetID);
+              	    
+        	    
+        	    long beginTS = System.currentTimeMillis();
+        	    long endTS = 0;
+        	    
+                	while (queryTestIt.hasNext()) {
+                	    QueryTest q = queryTestIt.next();
+                             	    
+                    	    userTxn.init(summary, expectedResults, q);
+                     	    
+                	    // run test
+                    	    try {
+                    	    	tc.runTransaction(userTxn);
+                    	    } catch (Throwable t) {
+                    	    	t.printStackTrace();
+                    	    }
+        	             
+                	}
+                	
+                	endTS = System.currentTimeMillis();
+                	
+                	TestLogger.logInfo("End Test Query ID [" + querySetID + "]");
+                	
+                	summary.printResults(queryset, querySetID,beginTS, endTS);        	
+          
+        	}
+        	
+   
+	} finally {	
+	    try {
+    		summary.printTotals(queryset);
+    		summary.cleanup();
+	    } catch (Throwable t) {
+		t.printStackTrace();
+	    }
+	    
+		// cleanup all connections created for this test.
+	    
+	    	DataSourceMgr.getInstance().shutdown();
+//		userTxn.getConnectionStrategy().shutdown();
+		ConfigPropertyLoader.reset();
+	}
+
+	
+    }
+
+    
+    protected TransactionContainer getTransactionContainter() {
+	try {
+	    return TransactionFactory.create(ConfigPropertyLoader.getInstance());
+	} catch (QueryTestFailedException e) {
+	    // TODO Auto-generated catch block
+	    e.printStackTrace();
+	    throw new TransactionRuntimeException(e);
+	}
+
+    }
+
+    
+    private Properties getSubstitutedProperties(Properties props) {
+	Properties or = new Properties();
+	
+	Properties configprops = ConfigPropertyLoader.getInstance().getProperties();
+	
+	configprops.putAll(props);
+	
+	or = PropertiesUtils.resolveNestedProperties(configprops);
+	
+	return or;
+
+    }
+
+    
+
+
+    /**
+     * One-time synchronization barrier that allows dynamically reducing the
+     * number of threads expected at the barrier. Captures the timestamp when
+     * all the expected threads arrive at the barrier.
+     * 
+     * @since 4.3
+     */
+//    private static final class TimestampedSynchronizationBarrier {
+//	private int expectedThreads;
+//	private int currentThreads = 0;
+//	private long leaveBarrierTimestamp = -1;
+//
+//	private TimestampedSynchronizationBarrier(int expectedThreads) {
+//	    this.expectedThreads = expectedThreads;
+//	}
+//
+//	private synchronized void barrier(final long waitTime) {
+//	    if ((++currentThreads) == expectedThreads) {
+//		// If all the expected threads have arrived at the barrier, then
+//		// wake them all.
+//		leaveBarrierTimestamp = System.currentTimeMillis();
+//		this.notifyAll();
+//	    } else {
+//		// Otherwise, wait for other threads to arrive.
+//		try {
+//		    wait(waitTime);
+//		} catch (InterruptedException e) {
+//		    System.err
+//			    .println("A thread was unexpectedly interrupted while waiting for other threads to enter the barrier. The measurements for this test will not be accurate.");
+//		    e.printStackTrace(System.err);
+//		    // Let the thread continue on its merry way
+//		}
+//	    }
+//	}
+//
+//	private synchronized void decrementExpectedThreads() {
+//	    if ((--expectedThreads) == currentThreads) {
+//		// If all the remaining threads are already waiting, then wake
+//		// them all.
+//		leaveBarrierTimestamp = System.currentTimeMillis();
+//		this.notifyAll();
+//	    }
+//	}
+//    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,221 +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.test.client;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import org.teiid.test.client.results.TestResultStat;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.framework.query.AbstractQueryTransactionTest;
-
-/**
- * TestClientTransaction
- * 
- * @author vanhalbert
- * 
- */
-public class TestClientTransaction extends AbstractQueryTransactionTest {
-
-    private QueryScenario querySet = null;
-    private ExpectedResults expectedResults = null;
-    private QueryTest query = null;
-
-    private long endTS = 0;
-    private long beginTS = 0;
-
-    private int testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
-
-    private boolean errorExpected = false;
-    
-    private String sql = null;
-    private boolean resultFromQuery = false;
-    
-    private TestResultsSummary testResultsSummary;
-
-    public TestClientTransaction(QueryScenario querySet) {
-	super(querySet.getQueryScenarioIdentifier());
-	this.querySet = querySet;
-
-    }
-    
-    
-    
-
-    public void init(TestResultsSummary testResultsSummary, ExpectedResults expectedResults, QueryTest query) {
-	this.query = query;
-	this.testResultsSummary = testResultsSummary;
-	this.expectedResults = expectedResults;
-	
-	endTS = 0;
-	beginTS = 0;
-
-	testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
-
-	errorExpected = false;
-	resultFromQuery = false;
-
-    }
-    
-    public String getTestName() {
-	return query.getQueryScenarioID() + ":" + (query.getQueryID()!=null?query.getQueryID():"NA");
-	
-    }
-
-    @Override
-    public void before() {
-	// TODO Auto-generated method stub
-	super.before();
-
-
-	try {
-	    this.errorExpected = expectedResults
-		    .isExceptionExpected(query.getQueryID());
-	} catch (QueryTestFailedException e) {
-	    // TODO Auto-generated catch block
-	    throw new TransactionRuntimeException("ProgramError: "
-		    + e.getMessage());
-	}
-
-    }
-
-
-    @Override
-    public void testCase() throws Exception {
-	TestLogger.logDebug("expected error: " + this.errorExpected);
-	TestLogger.logDebug("ID: " + query.geQuerySetID() + "-" + query.getQueryID());
-        
-	QuerySQL[] queries = query.getQueries();
-	int l = queries.length;
-
-	try {
-	    // need to set this so the underlying query execution handles an
-	    // error properly.
-
-	    beginTS = System.currentTimeMillis();
-	    
-	    for (int i= 0; i < l; i++) {
-		QuerySQL qsql = queries[i];
-		this.sql = qsql.getSql();
-		resultFromQuery = execute(sql, qsql.getParms());
-		if (qsql.getUpdateCnt() >= 0) {	    
-		    this.assertUpdateCount(qsql.getUpdateCnt());
-
-		} else if (qsql.getRowCnt() >= 0) {
-		    this.assertRowCount(qsql.getRowCnt());
-
-		}
-		
-	    }
-
-	} catch (Throwable t) {
-	    this.setApplicationException(t);
-
-	} finally {
-	    // Capture resp time
-	    endTS = System.currentTimeMillis();
-	}
-
-    }
-
-    @Override
-    public void after() {
-	// TODO Auto-generated method stub
-	super.after();
-	TestResult rs = null;
-	
-	Throwable resultException = null;
-
-	resultException = (this.getLastException() != null ? this
-		    .getLastException() : this.getApplicationException());
-
-	
-	if (resultException != null) {
-	    if (this.exceptionExpected()) {
-		testStatus = TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION;
-	    } else {
-		testStatus = TestResult.RESULT_STATE.TEST_EXCEPTION;
-	    }
-
-	}
-
-	rs = new TestResultStat(query.geQuerySetID(), query.getQueryID(), sql,
-		testStatus, beginTS, endTS, resultException, null);
-	
-	
-
-	System.out.println("ADD THE TEST RESULT");
-
-	this.testResultsSummary.addTestResult(query.geQuerySetID(), rs);
-
-//	
-//	try {
-//		System.out.println("HANDLE RESULT " + this.internalResultSet.isClosed());
-//	} catch (SQLException e) {
-//		// TODO Auto-generated catch block
-//		e.printStackTrace();
-//	}
-	
-	this.querySet.handleTestResult(rs, this.internalResultSet, this.updateCount, resultFromQuery, sql);
-
-    }
-
-
-    @Override
-    protected Statement createStatement() throws SQLException {
-	return this.internalConnection.createStatement(
-		ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-    }
-
-    // need to override this method because the abstract logic for throwing
-    // exceptions depends on this
-    @Override
-    public boolean exceptionExpected() {
-	return this.errorExpected;
-    }
-
-
-    /**
-     * Override the super cleanup() so that the connection to Teiid is not
-     * cleaned up at this time.
-     * 
-     * This will be handled after all queries in the set have been executed.
-     * 
-     * @see TestClient#runTest();
-     * 
-     */
-    @Override
-    public void cleanup() {
-	//	
-	// NOTE: do not cleanup TestResults because {@link #getTestResult} is called
-	// after cleanup
-
-    }
-
-
-    
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TestClientTransaction.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,209 @@
+/*
+ * 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.test.client;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import org.teiid.test.client.results.TestResultStat;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+import org.teiid.test.framework.query.AbstractQueryTransactionTest;
+
+/**
+ * TestClientTransaction
+ * 
+ * @author vanhalbert
+ * 
+ */
+public class TestClientTransaction extends AbstractQueryTransactionTest {
+
+    private QueryScenario querySet = null;
+    private ExpectedResults expectedResults = null;
+    private QueryTest query = null;
+
+    private long endTS = 0;
+    private long beginTS = 0;
+
+    private int testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
+
+    private boolean errorExpected = false;
+    
+    private String sql = null;
+    private boolean resultFromQuery = false;
+    
+    private TestResultsSummary testResultsSummary;
+
+    public TestClientTransaction(QueryScenario querySet) {
+	super(querySet.getQueryScenarioIdentifier());
+	this.querySet = querySet;
+
+    }
+    
+    
+    
+
+    public void init(TestResultsSummary testResultsSummary, ExpectedResults expectedResults, QueryTest query) {
+	this.query = query;
+	this.testResultsSummary = testResultsSummary;
+	this.expectedResults = expectedResults;
+	
+	endTS = 0;
+	beginTS = 0;
+
+	testStatus = TestResult.RESULT_STATE.TEST_SUCCESS;
+
+	errorExpected = false;
+	resultFromQuery = false;
+
+    }
+    
+    public String getTestName() {
+	return query.getQueryScenarioID() + ":" + (query.getQueryID()!=null?query.getQueryID():"NA");
+	
+    }
+
+    @Override
+    public void before() {
+	// TODO Auto-generated method stub
+	super.before();
+
+
+	try {
+	    this.errorExpected = expectedResults
+		    .isExceptionExpected(query.getQueryID());
+	} catch (QueryTestFailedException e) {
+	    // TODO Auto-generated catch block
+	    throw new TransactionRuntimeException("ProgramError: "
+		    + e.getMessage());
+	}
+
+    }
+
+
+    @Override
+    public void testCase() throws Exception {
+	TestLogger.logDebug("expected error: " + this.errorExpected);
+	TestLogger.logInfo("ID: " + query.geQuerySetID() + "  -  " + query.getQueryID());
+        
+	QuerySQL[] queries = query.getQueries();
+	int l = queries.length;
+
+	try {
+	    // need to set this so the underlying query execution handles an
+	    // error properly.
+
+	    beginTS = System.currentTimeMillis();
+	    
+	    for (int i= 0; i < l; i++) {
+		QuerySQL qsql = queries[i];
+		this.sql = qsql.getSql();
+		resultFromQuery = execute(sql, qsql.getParms());
+		if (qsql.getUpdateCnt() >= 0) {	    
+		    this.assertUpdateCount(qsql.getUpdateCnt());
+
+		} else if (qsql.getRowCnt() >= 0) {
+		    this.assertRowCount(qsql.getRowCnt());
+
+		}
+		
+	    }
+
+	} catch (Throwable t) {
+	    this.setApplicationException(t);
+
+	} finally {
+	    // Capture resp time
+	    endTS = System.currentTimeMillis();
+	}
+
+    }
+
+    @Override
+    public void after() {
+	// TODO Auto-generated method stub
+	super.after();
+	TestResult rs = null;
+	
+	Throwable resultException = null;
+
+	resultException = (this.getLastException() != null ? this
+		    .getLastException() : this.getApplicationException());
+
+	
+	if (resultException != null) {
+	    if (this.exceptionExpected()) {
+		testStatus = TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION;
+	    } else {
+		testStatus = TestResult.RESULT_STATE.TEST_EXCEPTION;
+	    }
+
+	}
+
+	rs = new TestResultStat(query.geQuerySetID(), query.getQueryID(), sql,
+		testStatus, beginTS, endTS, resultException, null);
+	
+	this.testResultsSummary.addTestResult(query.geQuerySetID(), rs);
+
+	this.querySet.handleTestResult(rs, this.internalResultSet, this.updateCount, resultFromQuery, sql);
+
+    }
+
+
+    @Override
+    protected Statement createStatement() throws SQLException {
+	return this.internalConnection.createStatement(
+		ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+    }
+
+    // need to override this method because the abstract logic for throwing
+    // exceptions depends on this
+    @Override
+    public boolean exceptionExpected() {
+	return this.errorExpected;
+    }
+
+
+    /**
+     * Override the super cleanup() so that the connection to Teiid is not
+     * cleaned up at this time.
+     * 
+     * This will be handled after all queries in the set have been executed.
+     * 
+     * @see TestClient#runTest();
+     * 
+     */
+    @Override
+    public void cleanup() {
+	//	
+	// NOTE: do not cleanup TestResults because {@link #getTestResult} is called
+	// after cleanup
+
+    }
+
+
+    
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,105 +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.test.client;
-
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.TransactionContainer;
-import org.teiid.test.framework.ConfigPropertyNames.TXN_AUTO_WRAP_OPTIONS;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.framework.transaction.JNDITransaction;
-import org.teiid.test.framework.transaction.LocalTransaction;
-import org.teiid.test.framework.transaction.TxnAutoTransaction;
-import org.teiid.test.framework.transaction.XATransaction;
-
-
-/**
- * TransactionFactory is used so that the type of {@link TransactionContainer } can be dynamically loaded
- * based on a property.
- * 
- * Specify the property {@link #TRANSACTION_TYPE} in order to set the transaction type to use.
- * 
- * @author vanhalbert
- *
- */
-public class TransactionFactory {
-    
-
-	/**
-	 * Transaction Type indicates the type of transaction container to use
-	 * @see TransactionFactory
-	 */
-    public static final String TRANSACTION_TYPE = "transaction-option"; //$NON-NLS-1$
-
-    public interface TRANSACTION_TYPES {
-		public static final String LOCAL_TRANSACTION = "local";     //$NON-NLS-1$
-		public static final String XATRANSACTION = "xa"; //$NON-NLS-1$
-		public static final String JNDI_TRANSACTION = "jndi"; //$NON-NLS-1$
-		public static final String OFFWRAP_TRANSACTION = "off"; //$NON-NLS-1$
-		public static final String ONWRAP_TRANSACTION = "on"; //$NON-NLS-1$
-		public static final String AUTOWRAP_TRANSACTION = "auto"; //$NON-NLS-1$
-   }
-	
-
-        
-    private TransactionFactory(){}
-        
-    
-    public static TransactionContainer create(ConfigPropertyLoader config) throws QueryTestFailedException {
-    	TransactionContainer transacton = null;
-    	    	
-        String type = config.getProperty(TRANSACTION_TYPE);
-        if (type == null) {
-            throw new TransactionRuntimeException(TRANSACTION_TYPE + " property was not specified" );
-        } 
-        
-       
-        TestLogger.log("====  Create Transaction-Option: " + type);
-        
-        if (type.equalsIgnoreCase(TRANSACTION_TYPES.LOCAL_TRANSACTION)) {
-        	transacton = new LocalTransaction();
-        }
-        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.XATRANSACTION)) {
-        	transacton = new XATransaction();
-        }
-        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.JNDI_TRANSACTION)) {
-        	transacton = new JNDITransaction();
-        }
-     	else if (type.equalsIgnoreCase(TRANSACTION_TYPES.OFFWRAP_TRANSACTION)) {
-            	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_OFF);
-        }
-        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.ONWRAP_TRANSACTION)) {
-        	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_ON);
-        }
-            else if (type.equalsIgnoreCase(TRANSACTION_TYPES.AUTOWRAP_TRANSACTION)) {
-        	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_AUTO);
-
-        } else {
-        	throw new TransactionRuntimeException("Invalid property value of " + type + " for " + TRANSACTION_TYPE );
-        }
-
-        TestLogger.log("====  TransactionContainer: " + transacton.getClass().getName() + " option:" + type);
-        return transacton;
-    }
-    
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/TransactionFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,105 @@
+/*
+ * 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.test.client;
+
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.TransactionContainer;
+import org.teiid.test.framework.ConfigPropertyNames.TXN_AUTO_WRAP_OPTIONS;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+import org.teiid.test.framework.transaction.JNDITransaction;
+import org.teiid.test.framework.transaction.LocalTransaction;
+import org.teiid.test.framework.transaction.TxnAutoTransaction;
+import org.teiid.test.framework.transaction.XATransaction;
+
+
+/**
+ * TransactionFactory is used so that the type of {@link TransactionContainer } can be dynamically loaded
+ * based on a property.
+ * 
+ * Specify the property {@link #TRANSACTION_TYPE} in order to set the transaction type to use.
+ * 
+ * @author vanhalbert
+ *
+ */
+public class TransactionFactory {
+    
+
+	/**
+	 * Transaction Type indicates the type of transaction container to use
+	 * @see TransactionFactory
+	 */
+    public static final String TRANSACTION_TYPE = "transaction-option"; //$NON-NLS-1$
+
+    public interface TRANSACTION_TYPES {
+		public static final String LOCAL_TRANSACTION = "local";     //$NON-NLS-1$
+		public static final String XATRANSACTION = "xa"; //$NON-NLS-1$
+		public static final String JNDI_TRANSACTION = "jndi"; //$NON-NLS-1$
+		public static final String OFFWRAP_TRANSACTION = "off"; //$NON-NLS-1$
+		public static final String ONWRAP_TRANSACTION = "on"; //$NON-NLS-1$
+		public static final String AUTOWRAP_TRANSACTION = "auto"; //$NON-NLS-1$
+   }
+	
+
+        
+    private TransactionFactory(){}
+        
+    
+    public static TransactionContainer create(ConfigPropertyLoader config) throws QueryTestFailedException {
+    	TransactionContainer transacton = null;
+    	    	
+        String type = config.getProperty(TRANSACTION_TYPE);
+        if (type == null) {
+            throw new TransactionRuntimeException(TRANSACTION_TYPE + " property was not specified" );
+        } 
+        
+       
+        TestLogger.logDebug("====  Create Transaction-Option: " + type);
+        
+        if (type.equalsIgnoreCase(TRANSACTION_TYPES.LOCAL_TRANSACTION)) {
+        	transacton = new LocalTransaction();
+        }
+        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.XATRANSACTION)) {
+        	transacton = new XATransaction();
+        }
+        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.JNDI_TRANSACTION)) {
+        	transacton = new JNDITransaction();
+        }
+     	else if (type.equalsIgnoreCase(TRANSACTION_TYPES.OFFWRAP_TRANSACTION)) {
+            	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_OFF);
+        }
+        else if (type.equalsIgnoreCase(TRANSACTION_TYPES.ONWRAP_TRANSACTION)) {
+        	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_ON);
+        }
+            else if (type.equalsIgnoreCase(TRANSACTION_TYPES.AUTOWRAP_TRANSACTION)) {
+        	transacton = new TxnAutoTransaction(TXN_AUTO_WRAP_OPTIONS.AUTO_WRAP_AUTO);
+
+        } else {
+        	throw new TransactionRuntimeException("Invalid property value of " + type + " for " + TRANSACTION_TYPE );
+        }
+
+        TestLogger.log("====  TransactionContainer: " + transacton.getClass().getName() + " option:" + type);
+        return transacton;
+    }
+    
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,154 +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.test.client.ctc;
-
-import java.io.IOException;
-import java.sql.ResultSet;
-import java.util.Properties;
-
-import org.teiid.test.client.ExpectedResults;
-import org.teiid.test.client.QueryScenario;
-import org.teiid.test.client.TestProperties;
-import org.teiid.test.client.TestResult;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-
-/**
- * The CTCQueryScenario represents the tests that were created using the old xml file formats.
- *  
- * @author vanhalbert
- *
- */
-public class CTCQueryScenario extends QueryScenario {
-    
-     
-    public CTCQueryScenario(String scenarioName, Properties querySetProperties) {
-	super(scenarioName, querySetProperties);
-    }
-    
-    protected void setUp() {
-
-	try {
-	    reader = new XMLQueryReader(this.getQueryScenarioIdentifier(), this.getProperties());
-	} catch (QueryTestFailedException e1) {
-    		throw new TransactionRuntimeException(e1);
-	}
-
-	resultsGen = new XMLGenerateResults(this.getQueryScenarioIdentifier(), this.getProperties());
-
-	if (reader.getQuerySetIDs() == null
-		|| reader.getQuerySetIDs().isEmpty()) {
-	    throw new TransactionRuntimeException(
-		    "The queryreader did not return any queryset ID's to process");
-	}
-
-	validateResultsMode(this.getProperties());
-
-    }
-
- 
-    @Override 
-    public ExpectedResults getExpectedResults(String querySetID) {    
-	return new XMLExpectedResults( querySetID, this.getProperties());
-    }    
-
-
-
-    /* (non-Javadoc)
-     * @see org.teiid.test.client.QueryScenario#handleTestResult(org.teiid.test.client.TestResult, java.lang.String)
-     */
-    @Override
-    public void handleTestResult(TestResult tr, ResultSet resultSet, int updatecnt, boolean resultFromQuery, String sql) {
-
-	Throwable resultException = tr.getException();
-	if (getResultsMode().equalsIgnoreCase(TestProperties.RESULT_MODES.COMPARE)) {
-	    if (tr.getStatus() != TestResult.RESULT_STATE.TEST_EXCEPTION) {
-			try {
-			    this.getExpectedResults(tr.getQuerySetID()).compareResults(tr.getQueryID(), 
-				    sql, 
-				    resultSet, 
-				    resultException, 
-				    tr.getStatus(), isOrdered(sql), -1,  resultFromQuery);
-	
-			} catch (QueryTestFailedException qtf) {
-			    resultException = (resultException != null ? resultException
-				    : qtf);
-			    tr.setException(resultException);
-			    tr.setStatus(TestResult.RESULT_STATE.TEST_EXCEPTION);
-	
-			}
-	    }
-
-	    if (tr.getStatus() == TestResult.RESULT_STATE.TEST_EXCEPTION) {
-			try {
-			    
-			    this.getResultsGenerator().generateErrorFile(tr.getQuerySetID(),
-				    tr.getQueryID(), sql, resultSet, resultException,
-				    this.getExpectedResults(tr.getQuerySetID()).getResultsFile(tr.getQueryID()) );
-			    
-	
-			} catch (QueryTestFailedException qtfe) {
-			    throw new TransactionRuntimeException(qtfe.getMessage());
-			}
-	    }
-
-	} else if (getResultsMode().equalsIgnoreCase(TestProperties.RESULT_MODES.GENERATE)) { //$NON-NLS-1$
-
-	    try {
-		
-			this.getResultsGenerator().generateQueryResultFile(tr.getQuerySetID(),
-				tr.getQueryID(), sql, resultSet, resultException, tr.getStatus());
-		
-	    } catch (QueryTestFailedException qtfe) {
-		throw new TransactionRuntimeException(qtfe.getMessage());
-	    }
-
-	} else {
-	    // just create the error file for any failures
-	    if (tr.getStatus() == TestResult.RESULT_STATE.TEST_EXCEPTION) {
-		try {
-		    this.getResultsGenerator().generateErrorFile(tr.getQuerySetID(),
-			    tr.getQueryID(), sql, resultSet, resultException,
-			    this.getExpectedResults(tr.getQuerySetID()).getResultsFile(tr.getQueryID()) );
-
-		} catch (QueryTestFailedException qtfe) {
-		    throw new TransactionRuntimeException(qtfe.getMessage());
-		}
-	    }
-	}
-
-
-	
-    }
-    
-
-    private boolean isOrdered(String sql) {
-
-	if (sql.toLowerCase().indexOf(" order by ") > 0) {
-	    return true;
-	}
-	return false;
-
-    }
-
-
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/CTCQueryScenario.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,153 @@
+/* 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.test.client.ctc;
+
+import java.sql.ResultSet;
+import java.util.Properties;
+
+import org.teiid.test.client.ExpectedResults;
+import org.teiid.test.client.QueryScenario;
+import org.teiid.test.client.TestProperties;
+import org.teiid.test.client.TestResult;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+
+/**
+ * The CTCQueryScenario represents the tests that were created using the old xml file formats.
+ *  
+ * @author vanhalbert
+ *
+ */
+public class CTCQueryScenario extends QueryScenario {
+    
+     
+    public CTCQueryScenario(String scenarioName, Properties querySetProperties) {
+	super(scenarioName, querySetProperties);
+    }
+    
+    protected void setUp() {
+
+	try {
+	    reader = new XMLQueryReader(this.getQueryScenarioIdentifier(), this.getProperties());
+	} catch (QueryTestFailedException e1) {
+    		throw new TransactionRuntimeException(e1);
+	}
+
+	resultsGen = new XMLGenerateResults(this.getQueryScenarioIdentifier(), this.getProperties());
+
+	if (reader.getQuerySetIDs() == null
+		|| reader.getQuerySetIDs().isEmpty()) {
+	    throw new TransactionRuntimeException(
+		    "The queryreader did not return any queryset ID's to process");
+	}
+
+	validateResultsMode(this.getProperties());
+
+    }
+
+ 
+    @Override 
+    public ExpectedResults getExpectedResults(String querySetID) {    
+	return new XMLExpectedResults( querySetID, this.getProperties());
+    }    
+
+
+
+    /* (non-Javadoc)
+     * @see org.teiid.test.client.QueryScenario#handleTestResult(org.teiid.test.client.TestResult, java.lang.String)
+     */
+    @Override
+    public void handleTestResult(TestResult tr, ResultSet resultSet, int updatecnt, boolean resultFromQuery, String sql) {
+
+	Throwable resultException = tr.getException();
+	if (getResultsMode().equalsIgnoreCase(TestProperties.RESULT_MODES.COMPARE)) {
+	    if (tr.getStatus() != TestResult.RESULT_STATE.TEST_EXCEPTION) {
+			try {
+			    this.getExpectedResults(tr.getQuerySetID()).compareResults(tr.getQueryID(), 
+				    sql, 
+				    resultSet, 
+				    resultException, 
+				    tr.getStatus(), isOrdered(sql), -1,  resultFromQuery);
+	
+			} catch (QueryTestFailedException qtf) {
+			    resultException = (resultException != null ? resultException
+				    : qtf);
+			    tr.setException(resultException);
+			    tr.setStatus(TestResult.RESULT_STATE.TEST_EXCEPTION);
+	
+			}
+	    }
+
+	    if (tr.getStatus() == TestResult.RESULT_STATE.TEST_EXCEPTION) {
+			try {
+			    
+			    this.getResultsGenerator().generateErrorFile(tr.getQuerySetID(),
+				    tr.getQueryID(), sql, resultSet, resultException,
+				    this.getExpectedResults(tr.getQuerySetID()).getResultsFile(tr.getQueryID()) );
+			    
+	
+			} catch (QueryTestFailedException qtfe) {
+			    throw new TransactionRuntimeException(qtfe.getMessage());
+			}
+	    }
+
+	} else if (getResultsMode().equalsIgnoreCase(TestProperties.RESULT_MODES.GENERATE)) { //$NON-NLS-1$
+
+	    try {
+		
+			this.getResultsGenerator().generateQueryResultFile(tr.getQuerySetID(),
+				tr.getQueryID(), sql, resultSet, resultException, tr.getStatus());
+		
+	    } catch (QueryTestFailedException qtfe) {
+		throw new TransactionRuntimeException(qtfe.getMessage());
+	    }
+
+	} else {
+	    // just create the error file for any failures
+	    if (tr.getStatus() == TestResult.RESULT_STATE.TEST_EXCEPTION && !getResultsMode().equalsIgnoreCase(TestProperties.RESULT_MODES.NONE)) {
+		try {
+		    this.getResultsGenerator().generateErrorFile(tr.getQuerySetID(),
+			    tr.getQueryID(), sql, resultSet, resultException,
+			    this.getExpectedResults(tr.getQuerySetID()).getResultsFile(tr.getQueryID()) );
+
+		} catch (QueryTestFailedException qtfe) {
+		    throw new TransactionRuntimeException(qtfe.getMessage());
+		}
+	    }
+	}
+
+
+	
+    }
+    
+
+    private boolean isOrdered(String sql) {
+
+	if (sql.toLowerCase().indexOf(" order by ") > 0) {
+	    return true;
+	}
+	return false;
+
+    }
+
+
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,138 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership.  Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.test.client.ctc;
-
-import java.util.Map;
-import java.util.HashMap;
-
-/**
- * Constants used in XML messaging.
- */
-public final class TagNames {
-
-  private static final String DATA_ELE_TYPE_INT = "integer"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_STRING = "string"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_FLOAT = "float"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_LONG = "long"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_DOUBLE = "double"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_BYTE = "byte"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_DATE = "date"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_TIME = "time"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_TIMESTAMP = "timestamp"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_BOOLEAN = "boolean"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_CHAR = "char"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_SHORT = "short"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_BIG_INT = "biginteger"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_BIG_DEC = "bigdecimal"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_OBJECT = "object"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_XML = "xml"; //$NON-NLS-1$
-  private static final String DATA_ELE_TYPE_CLOB = "clob"; //$NON-NLS-1$
-
-    public static Map TYPE_MAP;
-
-    static {
-        TYPE_MAP = new HashMap();
-
-        TYPE_MAP.put(DATA_ELE_TYPE_OBJECT,      java.lang.Object.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_INT,         java.lang.Integer.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_STRING,      java.lang.String.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_FLOAT,       java.lang.Float.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_LONG,        java.lang.Long.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_DOUBLE,      java.lang.Double.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_BYTE,        java.lang.Byte.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_BOOLEAN,     java.lang.Boolean.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_CHAR,        java.lang.Character.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_SHORT,       java.lang.Short.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_BIG_INT,     java.math.BigInteger.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_BIG_DEC,     java.math.BigDecimal.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_DATE,        java.sql.Date.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_TIME,        java.sql.Time.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_TIMESTAMP,   java.sql.Timestamp.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_XML,         java.lang.String.class);
-        TYPE_MAP.put(DATA_ELE_TYPE_CLOB,        java.lang.String.class);
-    }
-
-
-    /**
-     * Enumeration of XML element tag constants.
-     */
-    public static final class Elements {
-        public static final String STRING = "string"; //$NON-NLS-1$
-        public static final String BOOLEAN = "boolean"; //$NON-NLS-1$
-        public static final String BYTE = "byte"; //$NON-NLS-1$
-        public static final String SHORT = "short"; //$NON-NLS-1$
-        public static final String CHAR = "char"; //$NON-NLS-1$
-        public static final String INTEGER = "integer"; //$NON-NLS-1$
-        public static final String LONG = "long"; //$NON-NLS-1$
-        public static final String BIGINTEGER = "biginteger"; //$NON-NLS-1$
-        public static final String FLOAT = "float"; //$NON-NLS-1$
-        public static final String DOUBLE = "double"; //$NON-NLS-1$
-        public static final String BIGDECIMAL = "bigdecimal"; //$NON-NLS-1$
-        public static final String DATE = "date"; //$NON-NLS-1$
-        public static final String TIME = "time"; //$NON-NLS-1$
-        public static final String TIMESTAMP = "timestamp"; //$NON-NLS-1$
-        public static final String OBJECT = "object"; //$NON-NLS-1$
-
-        public static final String CLASS = "class"; //$NON-NLS-1$
-        public static final String TABLE = "table"; //$NON-NLS-1$
-        public static final String TABLE_ROW = "tableRow"; //$NON-NLS-1$
-        public static final String TABLE_CELL = "tableCell"; //$NON-NLS-1$
-        public static final String NULL = "null"; //$NON-NLS-1$
-        public static final String EXCEPTION = "exception"; //$NON-NLS-1$
-        public static final String ACTUAL_EXCEPTION = "actual_exception"; //$NON-NLS-1$
-        public static final String EXPECTED_EXCEPTION = "expected_exception"; //$NON-NLS-1$
-        public static final String EXCEPTION_TYPE = "exceptionType"; //$NON-NLS-1$
-        public static final String MESSAGE = "message"; //$NON-NLS-1$
-        public static final String DATA_ELEMENT = "dataElement"; //$NON-NLS-1$
-        public static final String QUERY_RESULTS = "queryResults"; //$NON-NLS-1$
-        public static final String ACTUAL_QUERY_RESULTS = "actual_queryResults"; //$NON-NLS-1$
-        public static final String EXPECTED_QUERY_RESULTS = "expected_queryResults"; //$NON-NLS-1$
-        public static final String QUERY = "query"; //$NON-NLS-1$
-        public static final String SELECT = "select"; //$NON-NLS-1$
-        public static final String ROOT_ELEMENT = "root"; //$NON-NLS-1$
-        public static final String SQL = "sql"; //$NON-NLS-1$
-        public static final String PARM = "parm"; //$NON-NLS-1$
-    }
-
-    /**
-     * Enumeration of XML element attribute names.
-     */
-    public static final class Attributes {
-        public static final String TYPE = "type"; //$NON-NLS-1$
-        public static final String SIZE = "size"; //$NON-NLS-1$
-        public static final String TABLE_ROW_COUNT = "rowCount"; //$NON-NLS-1$
-        public static final String TABLE_COLUMN_COUNT = "columnCount"; //$NON-NLS-1$
-        public static final String NAME = "name"; //$NON-NLS-1$
-        public static final String VALUE = "value"; //$NON-NLS-1$
-        public static final String DISTINCT = "distinct"; //$NON-NLS-1$
-        public static final String STAR = "star"; //$NON-NLS-1$
-        public static final String UPDATE_CNT = "updatecnt"; //$NON-NLS-1$
-    }
-
-    /**
-     * Enumeration of XML element attribute values.
-     */
-    public static final class Values {
-        public static final String TRUE = "true"; //$NON-NLS-1$
-        public static final String FALSE = "false"; //$NON-NLS-1$
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/TagNames.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,140 @@
+/*
+ * 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.test.client.ctc;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Constants used in XML messaging.
+ */
+public final class TagNames {
+
+  private static final String DATA_ELE_TYPE_INT = "integer"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_STRING = "string"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_FLOAT = "float"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_LONG = "long"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_DOUBLE = "double"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_BYTE = "byte"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_DATE = "date"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_TIME = "time"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_TIMESTAMP = "timestamp"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_BOOLEAN = "boolean"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_CHAR = "char"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_SHORT = "short"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_BIG_INT = "biginteger"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_BIG_DEC = "bigdecimal"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_OBJECT = "object"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_XML = "xml"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_CLOB = "clob"; //$NON-NLS-1$
+  private static final String DATA_ELE_TYPE_BLOB = "blob"; //$NON-NLS-1$
+
+    public static Map TYPE_MAP;
+
+    static {
+        TYPE_MAP = new HashMap();
+
+        TYPE_MAP.put(DATA_ELE_TYPE_OBJECT,      java.lang.Object.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_INT,         java.lang.Integer.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_STRING,      java.lang.String.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_FLOAT,       java.lang.Float.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_LONG,        java.lang.Long.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_DOUBLE,      java.lang.Double.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_BYTE,        java.lang.Byte.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_BOOLEAN,     java.lang.Boolean.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_CHAR,        java.lang.Character.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_SHORT,       java.lang.Short.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_BIG_INT,     java.math.BigInteger.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_BIG_DEC,     java.math.BigDecimal.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_DATE,        java.sql.Date.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_TIME,        java.sql.Time.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_TIMESTAMP,   java.sql.Timestamp.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_XML,         java.lang.String.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_CLOB,        java.lang.String.class);
+        TYPE_MAP.put(DATA_ELE_TYPE_BLOB,        java.lang.String.class);
+    }
+
+
+    /**
+     * Enumeration of XML element tag constants.
+     */
+    public static final class Elements {
+        public static final String STRING = "string"; //$NON-NLS-1$
+        public static final String BOOLEAN = "boolean"; //$NON-NLS-1$
+        public static final String BYTE = "byte"; //$NON-NLS-1$
+        public static final String SHORT = "short"; //$NON-NLS-1$
+        public static final String CHAR = "char"; //$NON-NLS-1$
+        public static final String INTEGER = "integer"; //$NON-NLS-1$
+        public static final String LONG = "long"; //$NON-NLS-1$
+        public static final String BIGINTEGER = "biginteger"; //$NON-NLS-1$
+        public static final String FLOAT = "float"; //$NON-NLS-1$
+        public static final String DOUBLE = "double"; //$NON-NLS-1$
+        public static final String BIGDECIMAL = "bigdecimal"; //$NON-NLS-1$
+        public static final String DATE = "date"; //$NON-NLS-1$
+        public static final String TIME = "time"; //$NON-NLS-1$
+        public static final String TIMESTAMP = "timestamp"; //$NON-NLS-1$
+        public static final String OBJECT = "object"; //$NON-NLS-1$
+
+        public static final String CLASS = "class"; //$NON-NLS-1$
+        public static final String TABLE = "table"; //$NON-NLS-1$
+        public static final String TABLE_ROW = "tableRow"; //$NON-NLS-1$
+        public static final String TABLE_CELL = "tableCell"; //$NON-NLS-1$
+        public static final String NULL = "null"; //$NON-NLS-1$
+        public static final String EXCEPTION = "exception"; //$NON-NLS-1$
+        public static final String ACTUAL_EXCEPTION = "actual_exception"; //$NON-NLS-1$
+        public static final String EXPECTED_EXCEPTION = "expected_exception"; //$NON-NLS-1$
+        public static final String EXCEPTION_TYPE = "exceptionType"; //$NON-NLS-1$
+        public static final String MESSAGE = "message"; //$NON-NLS-1$
+        public static final String DATA_ELEMENT = "dataElement"; //$NON-NLS-1$
+        public static final String QUERY_RESULTS = "queryResults"; //$NON-NLS-1$
+        public static final String ACTUAL_QUERY_RESULTS = "actual_queryResults"; //$NON-NLS-1$
+        public static final String EXPECTED_QUERY_RESULTS = "expected_queryResults"; //$NON-NLS-1$
+        public static final String QUERY = "query"; //$NON-NLS-1$
+        public static final String SELECT = "select"; //$NON-NLS-1$
+        public static final String ROOT_ELEMENT = "root"; //$NON-NLS-1$
+        public static final String SQL = "sql"; //$NON-NLS-1$
+        public static final String PARM = "parm"; //$NON-NLS-1$
+    }
+
+    /**
+     * Enumeration of XML element attribute names.
+     */
+    public static final class Attributes {
+        public static final String TYPE = "type"; //$NON-NLS-1$
+        public static final String SIZE = "size"; //$NON-NLS-1$
+        public static final String TABLE_ROW_COUNT = "rowCount"; //$NON-NLS-1$
+        public static final String TABLE_COLUMN_COUNT = "columnCount"; //$NON-NLS-1$
+        public static final String NAME = "name"; //$NON-NLS-1$
+        public static final String VALUE = "value"; //$NON-NLS-1$
+        public static final String DISTINCT = "distinct"; //$NON-NLS-1$
+        public static final String STAR = "star"; //$NON-NLS-1$
+        public static final String UPDATE_CNT = "updatecnt"; //$NON-NLS-1$
+    }
+
+    /**
+     * Enumeration of XML element attribute values.
+     */
+    public static final class Values {
+        public static final String TRUE = "true"; //$NON-NLS-1$
+        public static final String FALSE = "false"; //$NON-NLS-1$
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,951 +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.test.client.ctc;
-
-import java.io.File;
-import java.io.IOException;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.jdom.JDOMException;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.core.util.StringUtil;
-import org.teiid.test.client.ClassFactory;
-import org.teiid.test.client.ExpectedResults;
-import org.teiid.test.client.QueryScenario;
-import org.teiid.test.client.QueryTest;
-import org.teiid.test.client.ResultsGenerator;
-import org.teiid.test.client.TestProperties;
-import org.teiid.test.client.TestResult;
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.ConfigPropertyNames;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-
-
-
-
-public class XMLExpectedResults implements ExpectedResults {
-     
-    protected Properties props;
-    protected String resultMode = TestProperties.RESULT_MODES.NONE;
-    protected String generateDir = null;
-    protected String querySetIdentifier = null;
-    protected String results_dir_loc = null;
-     
-    protected Map<String, ResultsHolder> loadedResults = new HashMap<String, ResultsHolder>();
-    
-    
-    public XMLExpectedResults(String querySetIdentifier, Properties properties) {
-    	this.props = properties;
-    	this.querySetIdentifier = querySetIdentifier;
-     	
-    	this.results_dir_loc = props.getProperty(
-				PROP_EXPECTED_RESULTS_DIR_LOC, ""); 
-    	
-	String expected_root_loc = this.props
-		.getProperty(PROP_EXPECTED_RESULTS_ROOT_DIR);
-
-	if (expected_root_loc != null) {
-	    File dir = new File(expected_root_loc, results_dir_loc);
-	    this.results_dir_loc = dir.getAbsolutePath();
-	}
-	
-	validateResultsMode(this.props);
-
-    	
-    	TestLogger.logInfo("Expected results loc: " + this.results_dir_loc);
-    }
-    
-    protected void validateResultsMode(Properties props) {
-	// Determine from property what to do with query results
-	String resultModeStr = props.getProperty(
-		TestProperties.PROP_RESULT_MODE, "");
-	// No need to check for null prop here since we've just checked for this
-	// required property
-
-	if (resultModeStr.equalsIgnoreCase(TestProperties.RESULT_MODES.NONE)
-		|| resultModeStr
-			.equalsIgnoreCase(TestProperties.RESULT_MODES.COMPARE)
-		|| resultModeStr
-			.equalsIgnoreCase(TestProperties.RESULT_MODES.GENERATE)) { //$NON-NLS-1$
-	    resultMode = resultModeStr;
-	}
-	// otherwise use default of NONE
-
-	TestLogger.log("\nResults mode: " + resultMode); //$NON-NLS-1$
-
-    }
-
-
-	@Override
-	public boolean isExceptionExpected(String queryidentifier) throws QueryTestFailedException {
-		if (resultMode.equalsIgnoreCase(
-			TestProperties.RESULT_MODES.COMPARE)) {
-
-       			ResultsHolder expectedResults = (ResultsHolder) getResults(queryidentifier);
-
-       			return (expectedResults.getExceptionMsg() == null ? false : true);
-		} 
-		return false;
-	}
-
-
-
-	@Override
-	public String getQuerySetID() {
-	    return this.querySetIdentifier;
-	}
-
-
-
-	@Override
-	public synchronized File getResultsFile(String queryidentifier) throws QueryTestFailedException {
-		return findExpectedResultsFile(queryidentifier, this.querySetIdentifier);
-		
-	}
-	
-	private ResultsHolder getResults(String queryidentifier) throws QueryTestFailedException {
-		ResultsHolder rh = null;
-		
-		if (!loadedResults.containsKey(queryidentifier)) {
-			rh = loadExpectedResults( findExpectedResultsFile(queryidentifier, this.querySetIdentifier));
-		} else {
-			rh = loadedResults.get(queryidentifier);
-		}
-				
-		return rh;
-	}
-	
-	   /**
-     * Compare the results of a query with those that were expected.
-     * 
-     * @param expectedResults
-     *            The expected results.
-     * @param results
-     *            The actual results - may be null if <code>actualException</code>.
-     * @param actualException
-     *            The actual exception recieved durring query execution - may be null if <code>results</code>.
-     * @param isOrdered
-     *            Are the actual results ordered?
-     * @param batchSize
-     *            Size of the batch(es) used in determining when the first batch of results were read.
-     * @return The response time for comparing the first batch (sizes) of resutls.
-     * @throws QueryTestFailedException
-     *             If comparison fails.
-     */
-    public Object compareResults(  final String queryIdentifier,
-    								  final String sql,
-                                      final ResultSet resultSet,
-                                      final Throwable actualException,
-                                      final int testStatus,
-                                      final boolean isOrdered,
-                                      final int batchSize,
-                                      final boolean resultFromQuery) throws QueryTestFailedException {
-
-        final String eMsg = "CompareResults Error: "; //$NON-NLS-1$
-   	
-	ResultsHolder expectedResults = (ResultsHolder) getResults(queryIdentifier);
-
-	ResultsHolder actualResults;
-
-	switch (testStatus) {
-		case TestResult.RESULT_STATE.TEST_EXCEPTION:
-			throw new QueryTestFailedException(
-				eMsg
-					+ "Test resulted in unexpected exception " + actualException.getMessage()); //$NON-NLS-1$
-
-			
-		case TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION:
-
-		            if (!expectedResults.isException()) {
-		                // The actual exception was expected, but the expected results was not
-		                throw new QueryTestFailedException(eMsg + "The actual result was an exception, but the Expected results wasn't an exception.  Actual exception: '" //$NON-NLS-1$
-		                                                   + actualException.getMessage() + "'"); //$NON-NLS-1$
-		            }
-		            // We got an exception that we expected - convert actual exception to ResultsHolder
-		            actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
-		            actualResults.setQueryID(expectedResults.getQueryID());
-
-		            actualResults = convertException(actualException, actualResults);
-		            
-		            compareExceptions(actualResults, expectedResults, eMsg);
-
-		            break;
-		            
-		  default: 
-			    // DEBUG:
-			    // debugOut.println("*** Expected Results (holder): " +
-			    // expectedResults);
-			    // DEBUG:
-			    // debugOut.println("*** Actual Results (ResultSet): " +
-			    // printResultSet(results));
-
-			    // Convert results to ResultsHolder
- 			    actualResults = new ResultsHolder(TagNames.Elements.QUERY_RESULTS);
-		    		actualResults.setQueryID(expectedResults.getQueryID());
-
-		      		if (expectedResults.getRows().size() > 0) {
-         			    convertResults(resultSet, batchSize,   actualResults);
-        			    compareResults(actualResults, expectedResults, eMsg, isOrdered);
-		      		} else if (actualResults.getRows() != null &&  actualResults.getRows().size() > 0) {
-			                throw new QueryTestFailedException(eMsg + "Expected results indicated no results, but actual shows " + actualResults.getRows().size() + " rows."); //$NON-NLS-1$
-	      		    
-		      		    
-		      		}
-
-			    // DEBUG:
-			    // debugOut.println("*** Actual Results (holder): " +
-			    // actualResults);
-
-			// Compare expected results with actual results, record by record
-			
-
-			break;
-		    
-	       }
-	
-	return null;
-
-    	
-    }
-    
-    private ResultsHolder convertException(final Throwable actualException,
-			final ResultsHolder actualResults) {
-		actualResults.setExceptionClassName(actualException.getClass()
-				.getName());
-		actualResults.setExceptionMsg(actualException.getMessage());
-		return actualResults;
-	}
-    
-    /**
-     * Helper to convert results into records and record first batch response time.
-     * 
-     * @param results
-     * @param batchSize
-     * @param resultsHolder
-     *            Modified - results added by this method.
-     * @return List of sorted results.
-     * @throws QueryTestFailedException
-     *             replaced SQLException.
-     */
-    private final long convertResults(final ResultSet results,
-                                             final int batchSize,
-                                             ResultsHolder resultsHolder) throws QueryTestFailedException {
-
-        long firstBatchResponseTime = 0;
-        final List records = new ArrayList();
-        final List columnTypeNames = new ArrayList();
-        final List columnTypes = new ArrayList();
-
-        final ResultSetMetaData rsMetadata;
-        final int colCount;
-
-        // Get column info
-        try {
-            rsMetadata = results.getMetaData();
-            colCount = rsMetadata.getColumnCount();
-            // Read types of all columns
-            for (int col = 1; col <= colCount; col++) {
-                columnTypeNames.add(rsMetadata.getColumnName(col));
-                columnTypes.add(rsMetadata.getColumnTypeName(col));
-            }
-        } catch (SQLException qre) {
-            throw new QueryTestFailedException("Can't get results metadata: " + qre.getMessage()); //$NON-NLS-1$
-        }
-
-        // Get rows
-        try {
-            // Read all the rows
-            for (int row = 0; results.next(); row++) {
-                final List currentRecord = new ArrayList(colCount);
-                // Read values for this row
-                for (int col = 1; col <= colCount; col++) {
-                    currentRecord.add(results.getObject(col));
-                }
-                records.add(currentRecord);
-                // If this row is the (fetch size - 1)th row, record first batch response time
-                if (row == batchSize) {
-                    firstBatchResponseTime = System.currentTimeMillis();
-                }
-            }
-        } catch (SQLException qre) {
-            throw new QueryTestFailedException("Can't get results: " + qre.getMessage()); //$NON-NLS-1$
-        }
-
-        // Set info on resultsHolder
-        resultsHolder.setRows(records);
-        resultsHolder.setIdentifiers(columnTypeNames);
-        resultsHolder.setTypes(columnTypes);
-
-        return firstBatchResponseTime;
-    }
-    
-    /**
-     * Added primarily for public access to the compare code for testing.
-     * 
-     * @param actualResults
-     * @param expectedResults
-     * @param eMsg
-     * @param isOrdered
-     * @throws QueryTestFailedException
-     */
-     protected void compareResults(final ResultsHolder actualResults,
-                                      final ResultsHolder expectedResults,
-                                      final String eMsg,
-                                      boolean isOrdered) throws QueryTestFailedException {
-//        if (actualResults.isException() && expectedResults.isException()) {
-//            // Compare exceptions
-//            compareExceptions(actualResults, expectedResults, eMsg);
-//        } else 
-            
- //           if (actualResults.isResult() && expectedResults.isResult()) {
-            // Compare results
-            if (isOrdered == false && actualResults.hasRows() && expectedResults.hasRows()) {
-                // If the results are not ordered, we can sort both
-                // results and expected results to compare record for record
-                // Otherwise, actual and expected results are already assumed
-                // to be in same order
-
-                //sort the sortedResults in ascending order
-                final List actualRows = actualResults.getRows();
-                sortRecords(actualRows, true);
-                actualResults.setRows(actualRows);
-
-                //sort the expectedResults with ascending order
-                final List expectedRows = expectedResults.getRows();
-                sortRecords(expectedRows, true);
-                expectedResults.setRows(expectedRows);
-            }
-            
-            compareResultSets(actualResults.getRows(),
-                              actualResults.getTypes(),
-                              actualResults.getIdentifiers(),
-                              expectedResults.getRows(),
-                              expectedResults.getTypes(),
-                              expectedResults.getIdentifiers(),
-                              eMsg);
-//        } else if (actualResults.isResult() && expectedResults.isException()) {
-//            // Error - expected exception but got result
-//        } else if (actualResults.isException() && expectedResults.isResult()) {
-//            // Error - expected result but got exception
-//        }
-    }
-     
-     /**
-      * sort one result that is composed of records of all columns
-      */
-     private static void sortRecords(List records,
-                                     boolean ascending) {
-         //if record's size == 0, don't need to sort
-         if (records.size() != 0) {
-             int nFields = ((List)records.get(0)).size();
-             for (int k = 0; k < nFields; k++) {
-                 for (int m = k; m < nFields; m++) {
-                     int[] params = new int[m - k + 1];
-
-                     for (int n = k, j = 0; n <= m; n++, j++) {
-                         params[j] = n;
-                     }
-
-                     Collections.sort(records, new ListNestedSortComparator(params, ascending));
-                 }
-             }
-         }
-     }
-    
-    private void compareExceptions(final ResultsHolder actualResults,
-			final ResultsHolder expectedResults, String eMsg)
-			throws QueryTestFailedException {
-
-		final String expectedExceptionClass = expectedResults
-				.getExceptionClassName();
-		final String expectedExceptionMsg = expectedResults.getExceptionMsg().toLowerCase();
-		final String actualExceptionClass = actualResults
-				.getExceptionClassName();
-		final String actualExceptionMsg = actualResults.getExceptionMsg().toLowerCase();
-
-		if (actualExceptionClass == null) {
-			// We didn't get an actual exception, we should have
-			throw new QueryTestFailedException(eMsg + "Expected exception: " //$NON-NLS-1$
-					+ expectedExceptionClass + " but got none."); //$NON-NLS-1$
-		}
-		// Compare exception classes
-		if (!expectedExceptionClass.equals(actualExceptionClass)) {
-			throw new QueryTestFailedException(eMsg
-					+ "Got wrong exception, expected \"" //$NON-NLS-1$
-					+ expectedExceptionClass + "\" but got \"" + //$NON-NLS-1$
-					actualExceptionClass + "\""); //$NON-NLS-1$
-		}
-		// Compare exception messages
-		if (!expectedExceptionMsg.equals(actualExceptionMsg)) {
-			// Give it another chance by comparing w/o line separators
-			if (!compareStrTokens(expectedExceptionMsg, actualExceptionMsg)) {
-				throw new QueryTestFailedException(
-						eMsg
-								+ "Got expected exception but with wrong message. Got " + actualExceptionMsg); //$NON-NLS-1$
-			}
-		}
-	}
-
-    private boolean compareStrTokens(String expectedStr, String gotStr) {
-		String newline = System.getProperty("line.separator"); //$NON-NLS-1$
-		List expectedTokens = StringUtil.split(expectedStr, newline);
-		List gotTokens = StringUtil.split(gotStr, newline);
-		for (int i = 0; i < expectedTokens.size(); i++) {
-			String expected = (String) expectedTokens.get(i);
-			String got = (String) gotTokens.get(i);
-			if (!expected.equals(got)) {
-				return false;
-			}
-		}
-		return true;
-	}
-    
-    /**
-     * Compare actual results, identifiers and types with expected. <br>
-     * <strong>Note </strong>: result list are expected to match element for element.</br>
-     * 
-     * @param actualResults
-     * @param actualDatatypes
-     * @param actualIdentifiers
-     * @param expectedResults
-     * @param expectedDatatypes
-     * @param expectedIdentifiers
-     * @param eMsg
-     * @throws QueryTestFailedException
-     *             If comparison fails.
-     */
-    protected void compareResultSets(final List actualResults,
-                                          final List actualDatatypes,
-                                          final List actualIdentifiers,
-                                          final List expectedResults,
-                                          final List expectedDatatypes,
-                                          final List expectedIdentifiers,
-                                          final String eMsg) throws QueryTestFailedException {
-        // Compare column names and types
-        compareIdentifiers(actualIdentifiers, expectedIdentifiers, actualDatatypes, expectedDatatypes);
-
-        // Walk through records and compare actual against expected
-        final int actualRowCount = actualResults.size();
-        final int expectedRowCount = expectedResults.size();
-        final int actualColumnCount = actualIdentifiers.size();
-
-        // Check for less records than in expected results
-        if (actualRowCount < expectedRowCount) {
-            throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
-                                               " records but received only " + actualRowCount); //$NON-NLS-1$
-        } else if (actualRowCount > expectedRowCount) {
-            // Check also for more records than expected
-            throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
-                                               " records but received " + actualRowCount); //$NON-NLS-1$
-        }
-
-        //      DEBUG:
-        //       debugOut.println("================== Compariing Rows ===================");
- 
-        // Loop through rows
-        for (int row = 0; row < actualRowCount; row++) {
-
-            // Get actual record
-            final List actualRecord = (List)actualResults.get(row);
-
-            // Get expected record
-            final List expectedRecord = (List)expectedResults.get(row);
-
-            //          DEBUG:
-            //            debugOut.println("Row: " + (row + 1));
-            //            debugOut.println(" expectedRecord: " + expectedRecord);
-            //            debugOut.println(" actualRecord: " + actualRecord);
-            // Loop through columns
-            // Compare actual elements with expected elements column by column in this row
-            for (int col = 0; col < actualColumnCount; col++) {
-                // Get actual value
-                Object actualValue = actualRecord.get(col);
-                // Get expected value
-                Object expectedValue = expectedRecord.get(col);
- 
-                //              DEBUG:
-                //                debugOut.println(" Col: " +(col +1) + ": expectedValue:[" + expectedValue + "] actualValue:[" + actualValue +
-                // "]");
-
-                // Compare these values
-                if ( ( expectedValue == null && actualValue != null) ||
-                		(actualValue == null && expectedValue != null) ){
-                    // Compare nulls
-                        throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
-                                                           + " and column " + (col + 1) //$NON-NLS-1$
-                                                           + ": expected = [" //$NON-NLS-1$
-                                                           + (expectedValue!=null?expectedValue:"null") + "], actual = [" //$NON-NLS-1$
-                                                           + (actualValue!=null?actualValue:"null")  + "]"); //$NON-NLS-1$
-
-                } 
-                	
-                if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) {
-                    	 
-                	if (actualValue instanceof Clob){
-                		Clob c = (Clob)actualValue;
-                		try {
-							actualValue = ObjectConverterUtil.convertToString(c.getAsciiStream());
-							
-						} catch (Throwable e) {
-							// TODO Auto-generated catch block
-							throw new QueryTestFailedException(e);
-						}
-                	} else if (actualValue instanceof Blob){
-                    		Blob b = (Blob)actualValue;
-                    		try {
-    							actualValue = ObjectConverterUtil.convertToString(b.getBinaryStream());
-    							
-    						} catch (Throwable e) {
-    							// TODO Auto-generated catch block
-    							throw new QueryTestFailedException(e);
-    						}
-                    } else if (actualValue instanceof SQLXML){
-                    	SQLXML s = (SQLXML)actualValue;
-                		try {
-							actualValue = ObjectConverterUtil.convertToString(s.getBinaryStream());
-							
-						} catch (Throwable e) {
-							// TODO Auto-generated catch block
-							throw new QueryTestFailedException(e);
-						}
-                    } 
-
-                	
-                	if (!(expectedValue instanceof String)) {
-                		expectedValue = expectedValue.toString();
-                	}
-                } 
-                	
-                    // Compare values with equals
-                    if (!expectedValue.equals(actualValue)) {
-                        // DEBUG:
-                        //                        debugOut.println(" ExpectedType: " + expectedValue.getClass() + " ActualType: " +
-                        // actualValue.getClass());
-                	
-                         if (expectedValue instanceof String) {
-                            final String expectedString = (String)expectedValue;
-//                            if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) {
-//                            	
-//                            	Clob c = (Clob)actualValue;
-//                                // LOB types are special case - metadata says they're Object types so
-//                                // expected results are of type String. Actual object type is MMBlob, MMClob.
-//                                // Must compare w/ String verion of actual!
-//                                if (!expectedValue.equals(actualValue.toString())) {
-//                                    throw new QueryTestFailedException(eMsg + "LOB Value mismatch at row " + (row + 1) //$NON-NLS-1$
-//                                                                       + " and column " + (col + 1) //$NON-NLS-1$
-//                                                                       + ": expected = [" //$NON-NLS-1$
-//                                                                       + expectedValue + "], actual = [" //$NON-NLS-1$
-//                                                                       + actualValue + "]"); //$NON-NLS-1$
-//                                }
-//                            } else 
-                            if (!(actualValue instanceof String)) {
-                                throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
-                                                                   + " and column " + (col + 1) //$NON-NLS-1$
-                                                                   + ": expected = [" //$NON-NLS-1$
-                                                                   + expectedValue + "], actual = [" //$NON-NLS-1$
-                                                                   + actualValue + "]"); //$NON-NLS-1$
-                            } else if (expectedString.length() > 0) {
-                                // Check for String difference
-                                assertStringsMatch(expectedString, (String)actualValue, (row + 1), (col + 1), eMsg);
-                            }
-                        } else {
-                            
-                            throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
-                                    + " and column " + (col + 1) //$NON-NLS-1$
-                                    + ": expected = [" //$NON-NLS-1$
-                                    + expectedValue + "], actual = [" //$NON-NLS-1$
-                                    + actualValue + "]"); //$NON-NLS-1$
-              
-                        }
-                    }
-
-            } // end loop through columns
-        } // end loop through rows
-    }
-    
- 
-    
-    protected void compareIdentifiers(List actualIdentifiers,
-			List expectedIdentifiers, List actualDataTypes,
-			List expectedDatatypes) throws QueryTestFailedException {
-
-		// Check sizes
-		if (expectedIdentifiers.size() != actualIdentifiers.size()) {
-			throw new QueryTestFailedException(
-					"Got incorrect number of columns, expected = " + expectedIdentifiers.size() + ", actual = " //$NON-NLS-1$ //$NON-NLS-2$
-							+ actualIdentifiers.size());
-		}
-
-		// Compare identifier lists only by short name
-		for (int i = 0; i < actualIdentifiers.size(); i++) {
-			String actualIdent = (String) actualIdentifiers.get(i);
-			String expectedIdent = (String) expectedIdentifiers.get(i);
-			String actualType = (String) actualDataTypes.get(i);
-			String expectedType = (String) expectedDatatypes.get(i);
-
-			// Get short name for each identifier
-			String actualShort = getShortName(actualIdent);
-			String expectedShort = getShortName(expectedIdent);
-
-			if (!expectedShort.equalsIgnoreCase(actualShort)) {
-				throw new QueryTestFailedException(
-						"Got incorrect column name at column " + i + ", expected = " + expectedShort + " but got = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-								+ actualShort);
-			}
-			if (actualType.equalsIgnoreCase("xml")) {//$NON-NLS-1$
-				actualType = "string";//$NON-NLS-1$
-			}
-			if (actualType.equalsIgnoreCase("clob")) {//$NON-NLS-1$
-				actualType = "string";//$NON-NLS-1$
-			}
-			if (!expectedType.equalsIgnoreCase(actualType)) {
-				throw new QueryTestFailedException(
-						"Got incorrect column type at column " + i + ", expected = " + expectedType + " but got = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-								+ actualType);
-			}
-		}
-	}
-
-
-   protected  String getShortName(String ident) {
-        int index = ident.lastIndexOf("."); //$NON-NLS-1$
-        if (index >= 0) {
-            return ident.substring(index + 1);
-        }
-        return ident;
-    }
-    
-    private static final int MISMATCH_OFFSET = 20;
-    private static final int MAX_MESSAGE_SIZE = 50;
-
- 
-    
-   protected void assertStringsMatch(final String expectedStr, final String actualStr,
-			final int row, final int col, final String eMsg)
-			throws QueryTestFailedException {
-		// TODO: Replace stripCR() with XMLUnit comparison for XML results.
-		// stripCR() is a workaround for comparing XML Queries
-		// that have '\r'.
-		String expected = stripCR(expectedStr).trim();
-		String actual = stripCR(actualStr).trim();
-
-		String locationText = ""; //$NON-NLS-1$
-		int mismatchIndex = -1;
-		
-		
-		boolean isequal = Arrays.equals(expected.toCharArray(), actual.toCharArray());
-		
-		//if (!expected.equals(actual)) {
-		if (!isequal) {
-			if (expected != null && actual != null) {
-				int shortestStringLength = expected.length();
-				if (actual.length() < expected.length()) {
-					shortestStringLength = actual.length();
-				} 
-				for (int i = 0; i < shortestStringLength; i++) {
-					if (expected.charAt(i) != actual.charAt(i)) {
-						locationText = "  Strings do not match at character: " + (i + 1) + //$NON-NLS-1$
-								". Expected [" + expected.charAt(i)
-								+ "] but got [" + actual.charAt(i) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-						mismatchIndex = i;
-						break;
-					}
-				}
-			}
-
-			String expectedPartOfMessage = expected;
-			String actualPartOfMessage = actual;
-			if (expected.length() + actual.length() > MAX_MESSAGE_SIZE) {
-				expectedPartOfMessage = safeSubString(expected, mismatchIndex
-						- MISMATCH_OFFSET, mismatchIndex + MISMATCH_OFFSET);
-				actualPartOfMessage = safeSubString(actual, mismatchIndex
-						- MISMATCH_OFFSET, mismatchIndex + MISMATCH_OFFSET);
-			}
-
-			String message = eMsg + "Value mismatch at row " + row + //$NON-NLS-1$
-					" and column " + col + //$NON-NLS-1$
-					". Expected: {0} but was: {1}" + locationText; //$NON-NLS-1$
-			message = MessageFormat.format(message, new Object[] {
-					expectedPartOfMessage, actualPartOfMessage });
-			throw new QueryTestFailedException(message);
-		}
-	}
-    
-    private String safeSubString(String text, int startIndex,
-			int endIndex) {
-		String prefix = "...'"; //$NON-NLS-1$
-		String suffix = "'..."; //$NON-NLS-1$
-
-		int actualStartIndex = startIndex;
-		if (actualStartIndex < 0) {
-			actualStartIndex = 0;
-			prefix = "'"; //$NON-NLS-1$
-		}
-		int actualEndIndex = endIndex;
-		if (actualEndIndex > text.length() - 1) {
-			actualEndIndex = text.length() - 1;
-			if (actualEndIndex < 0) {
-				actualEndIndex = 0;
-			}
-		}
-		if (actualEndIndex == text.length() - 1 || text.length() == 0) {
-			suffix = "'"; //$NON-NLS-1$
-		}
-
-		return prefix + text.substring(actualStartIndex, actualEndIndex)
-				+ suffix;
-	}
-
-
-    
-    private String stripCR(final String text) {
-        if (text.indexOf('\r') >= 0) {
-            StringBuffer stripped = new StringBuffer(text.length());
-            int len = text.length();
-            for (int i = 0; i < len; i++) {
-                char current = text.charAt(i);
-                if (current != '\r') {
-                    stripped.append(current);
-                }
-            }
-            return stripped.toString();
-        }
-        return text;
-    }
-
-
-	@Override
-	public Object getMetaData(String queryidentifier) {
-		// TODO Auto-generated method stub
-		return null;
-	}
-
-
-	private ResultsHolder loadExpectedResults(File resultsFile) throws QueryTestFailedException {
-        XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
-        final ResultsHolder expectedResult;
-        try {
-            expectedResult = jstrat.parseXMLResultsFile(resultsFile);
-        } catch (IOException e) {
-            throw new QueryTestFailedException("Unable to load expected results: " + e.getMessage()); //$NON-NLS-1$
-        } catch (JDOMException e) {
-            throw new QueryTestFailedException("Unable to load expected results: " + e.getMessage()); //$NON-NLS-1$
-        }
-        return expectedResult;
-    }
-	
-    private File findExpectedResultsFile(String queryIdentifier,
-			String querySetIdentifier) throws QueryTestFailedException {
-		String resultFileName = queryIdentifier + ".xml"; //$NON-NLS-1$
-		File file = new File(results_dir_loc + "/" + querySetIdentifier, resultFileName);
-		if (!file.exists()) {
-			throw new QueryTestFailedException("Query results file " + file.getAbsolutePath() + " cannot be found");
-		}
-		
-		return file;
-
-	}
-    
-	public static void main(String[] args) {
-		System.setProperty(ConfigPropertyNames.CONFIG_FILE, "ctc-bqt-test.properties");
-
-		ConfigPropertyLoader _instance = ConfigPropertyLoader.getInstance();
-		Properties p = _instance.getProperties();
-		if (p == null || p.isEmpty()) {
-			throw new RuntimeException("Failed to load config properties file");
-
-		}
-		
-		QueryScenario set = ClassFactory.createQueryScenario("testscenario");
-
-		
-		_instance.setProperty(XMLQueryReader.PROP_QUERY_FILES_ROOT_DIR, new File("src/main/resources/").getAbsolutePath() );
-		
-
-		
-
-		try {
-
-		    Iterator<String> it = set.getQuerySetIDs().iterator();
-		    while (it.hasNext()) {
-			String querySetID = it.next();
-
-			List<QueryTest> queries = set.getQueries(querySetID);
-			if (queries.size() == 0l) {
-				System.out.println("Failed, didn't load any queries " );
-			}
-			
-				
-				ExpectedResults er = set.getExpectedResults(querySetID);
-				    //new XMLExpectedResults(_instance.getProperties(), querySetID);
-								
-				ResultsGenerator gr = set.getResultsGenerator();
-				    //new XMLGenerateResults(_instance.getProperties(), "testname", set.getOutputDirectory());
-
-				Iterator<QueryTest> qIt = queries.iterator();
-				while(qIt.hasNext()) {
-				    QueryTest q = qIt.next();
-				//	String qId = (String) qIt.next();
-				//	String sql = (String) queries.get(qId);
-					
-//					System.out.println("SetID #: " + cnt + "  Qid: " + qId + "   sql: " + sql);
-					
-					File resultsFile = er.getResultsFile(q.getQueryID());
-					if (resultsFile == null) {
-						System.out.println("Failed to get results file for queryID " + q.getQueryID());
-					}
-					
-	
-					
-					
-				}
-
-		    }
-			
-			System.out.println("Completed Test");
-
-		} catch (QueryTestFailedException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-
-	}
-    
-	private  long compareResults(final ResultsHolder expectedResults,
-	    final ResultSet results, final int testStatus, final Throwable actualException,
-	    final boolean isOrdered, final int batchSize)
-	    throws QueryTestFailedException {
-
-	ResultsHolder actualResults;
-	long firstBatchResponseTime = 0;
-	final String eMsg = "CompareResults Error: "; //$NON-NLS-1$
-	
-	       switch (testStatus) {
-		case TestResult.RESULT_STATE.TEST_EXCEPTION:
-	                throw new QueryTestFailedException(eMsg + "TestResult indicates test exception occured, the process should not have passed it in for comparison."); //$NON-NLS-1$
-			
-			
-//			break;
-			
-		case TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION:
-		//    String actualExceptionClass = actualException.getClass().getName();
-
-		            if (!expectedResults.isException()) {
-		                // The actual exception was expected, but the expected results was not
-		                throw new QueryTestFailedException(eMsg + "The actual result was an exception, but the Expected results wasn't an exception.  Actual exception: '" //$NON-NLS-1$
-		                                                   + actualException.getMessage() + "'"); //$NON-NLS-1$
-		            }
-		            // We got an exception that we expected - convert actual exception to ResultsHolder
-		            actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
-		            actualResults.setQueryID(expectedResults.getQueryID());
-
-		            actualResults = convertException(actualException, actualResults);
-		            
-		            compareExceptions(actualResults, expectedResults, eMsg);
-
-		            return firstBatchResponseTime;
-		    
-//		    	break;
-		    
-	       }
-	       
-
-
-//	if (results == null) {
-//	    // The result is an exception - compare exceptions
-//
-//	    String actualExceptionClass = null;
-//	    if (actualException != null) {
-//		actualExceptionClass = actualException.getClass().getName();
-//	    } else {
-//		// We didn't get results but there was no exception either
-//		throw new QueryTestFailedException(eMsg
-//			+ "Didn't get results or exception '"); //$NON-NLS-1$
-//	    }
-//
-//	    if (!expectedResults.isException()) {
-//		// We didn't get results but there was no expected exception
-//		// either
-//		throw new QueryTestFailedException(
-//			eMsg
-//				+ "Expected results but didn't get results or exception '" //$NON-NLS-1$
-//				+ actualExceptionClass + "'"); //$NON-NLS-1$
-//	    }
-//	    // We got an exception that we expected - convert actual exception
-//	    // to ResultsHolder
-//	    actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
-//	    actualResults.setQueryID(expectedResults.getQueryID());
-//
-//	    actualResults = convertException(actualException, actualResults);
-//
-//	} else {
-	    // The result is a ResultSet - compare actual results with expected
-
-	    if (expectedResults.isException()) {
-		throw new QueryTestFailedException(
-			eMsg
-				+ "Expected exception " + expectedResults.getExceptionMsg() //$NON-NLS-1$
-				+ " but got results"); //$NON-NLS-1$
-	    }
-	    // DEBUG:
-	    // debugOut.println("*** Expected Results (holder): " +
-	    // expectedResults);
-	    // DEBUG:
-	    // debugOut.println("*** Actual Results (ResultSet): " +
-	    // printResultSet(results));
-
-	    // Convert results to ResultsHolder
-	    actualResults = new ResultsHolder(TagNames.Elements.QUERY_RESULTS);
-	    actualResults.setQueryID(expectedResults.getQueryID());
-	    firstBatchResponseTime = convertResults(results, batchSize,
-		    actualResults);
-
-	    // DEBUG:
-	    // debugOut.println("*** Actual Results (holder): " +
-	    // actualResults);
-//	} // end is resultSet
-
-	// Compare expected results with actual results, record by record
-	compareResults(actualResults, expectedResults, eMsg, isOrdered);
-
-	return firstBatchResponseTime;
-    }
-
-
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLExpectedResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,957 @@
+/*
+ * 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.test.client.ctc;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.jdom.JDOMException;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.StringUtil;
+import org.teiid.test.client.ClassFactory;
+import org.teiid.test.client.ExpectedResults;
+import org.teiid.test.client.QueryScenario;
+import org.teiid.test.client.QueryTest;
+import org.teiid.test.client.ResultsGenerator;
+import org.teiid.test.client.TestProperties;
+import org.teiid.test.client.TestResult;
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+
+
+
+
+public class XMLExpectedResults implements ExpectedResults {
+     
+    protected Properties props;
+    protected String resultMode = TestProperties.RESULT_MODES.NONE;
+    protected String generateDir = null;
+    protected String querySetIdentifier = null;
+    protected String results_dir_loc = null;
+     
+    protected Map<String, ResultsHolder> loadedResults = new HashMap<String, ResultsHolder>();
+    
+    
+    public XMLExpectedResults(String querySetIdentifier, Properties properties) {
+    	this.props = properties;
+    	this.querySetIdentifier = querySetIdentifier;
+     	
+    	this.results_dir_loc = props.getProperty(
+				PROP_EXPECTED_RESULTS_DIR_LOC, ""); 
+    	
+	String expected_root_loc = this.props
+		.getProperty(PROP_EXPECTED_RESULTS_ROOT_DIR);
+
+	if (expected_root_loc != null) {
+	    File dir = new File(expected_root_loc, results_dir_loc);
+	    this.results_dir_loc = dir.getAbsolutePath();
+	}
+	
+	validateResultsMode(this.props);
+
+    	
+    	TestLogger.logDebug("Expected results loc: " + this.results_dir_loc);
+    }
+    
+    protected void validateResultsMode(Properties props) {
+	// Determine from property what to do with query results
+	String resultModeStr = props.getProperty(
+		TestProperties.PROP_RESULT_MODE, "");
+	// No need to check for null prop here since we've just checked for this
+	// required property
+
+	if (resultModeStr.equalsIgnoreCase(TestProperties.RESULT_MODES.NONE)
+		|| resultModeStr
+			.equalsIgnoreCase(TestProperties.RESULT_MODES.COMPARE)
+		|| resultModeStr
+			.equalsIgnoreCase(TestProperties.RESULT_MODES.GENERATE)) { //$NON-NLS-1$
+	    resultMode = resultModeStr;
+	}
+	// otherwise use default of NONE
+
+	TestLogger.logDebug("\nResults mode: " + resultMode); //$NON-NLS-1$
+
+    }
+    
+    public boolean isExpectedResultsNeeded() {
+    	return (resultMode.equalsIgnoreCase(TestProperties.RESULT_MODES.COMPARE));
+    }
+
+
+	@Override
+	public boolean isExceptionExpected(String queryidentifier) throws QueryTestFailedException {
+		if (resultMode.equalsIgnoreCase(
+			TestProperties.RESULT_MODES.COMPARE)) {
+
+       			ResultsHolder expectedResults = (ResultsHolder) getResults(queryidentifier);
+
+       			return (expectedResults.getExceptionMsg() == null ? false : true);
+		} 
+		return false;
+	}
+
+
+
+	@Override
+	public String getQuerySetID() {
+	    return this.querySetIdentifier;
+	}
+
+
+
+	@Override
+	public synchronized File getResultsFile(String queryidentifier) throws QueryTestFailedException {
+		return findExpectedResultsFile(queryidentifier, this.querySetIdentifier);
+		
+	}
+	
+	private ResultsHolder getResults(String queryidentifier) throws QueryTestFailedException {
+		ResultsHolder rh = null;
+		
+		if (!loadedResults.containsKey(queryidentifier)) {
+			rh = loadExpectedResults( findExpectedResultsFile(queryidentifier, this.querySetIdentifier));
+		} else {
+			rh = loadedResults.get(queryidentifier);
+		}
+				
+		return rh;
+	}
+	
+	   /**
+     * Compare the results of a query with those that were expected.
+     * 
+     * @param expectedResults
+     *            The expected results.
+     * @param results
+     *            The actual results - may be null if <code>actualException</code>.
+     * @param actualException
+     *            The actual exception recieved durring query execution - may be null if <code>results</code>.
+     * @param isOrdered
+     *            Are the actual results ordered?
+     * @param batchSize
+     *            Size of the batch(es) used in determining when the first batch of results were read.
+     * @return The response time for comparing the first batch (sizes) of resutls.
+     * @throws QueryTestFailedException
+     *             If comparison fails.
+     */
+    public Object compareResults(  final String queryIdentifier,
+    								  final String sql,
+                                      final ResultSet resultSet,
+                                      final Throwable actualException,
+                                      final int testStatus,
+                                      final boolean isOrdered,
+                                      final int batchSize,
+                                      final boolean resultFromQuery) throws QueryTestFailedException {
+
+        final String eMsg = "CompareResults Error: "; //$NON-NLS-1$
+   	
+	ResultsHolder expectedResults = (ResultsHolder) getResults(queryIdentifier);
+
+	ResultsHolder actualResults;
+
+	switch (testStatus) {
+		case TestResult.RESULT_STATE.TEST_EXCEPTION:
+			throw new QueryTestFailedException(
+				eMsg
+					+ "Test resulted in unexpected exception " + actualException.getMessage()); //$NON-NLS-1$
+
+			
+		case TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION:
+
+		            if (!expectedResults.isException()) {
+		                // The actual exception was expected, but the expected results was not
+		                throw new QueryTestFailedException(eMsg + "The actual result was an exception, but the Expected results wasn't an exception.  Actual exception: '" //$NON-NLS-1$
+		                                                   + actualException.getMessage() + "'"); //$NON-NLS-1$
+		            }
+		            // We got an exception that we expected - convert actual exception to ResultsHolder
+		            actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
+		            actualResults.setQueryID(expectedResults.getQueryID());
+
+		            actualResults = convertException(actualException, actualResults);
+		            
+		            compareExceptions(actualResults, expectedResults, eMsg);
+
+		            break;
+		            
+		  default: 
+			    // DEBUG:
+			    // debugOut.println("*** Expected Results (holder): " +
+			    // expectedResults);
+			    // DEBUG:
+			    // debugOut.println("*** Actual Results (ResultSet): " +
+			    // printResultSet(results));
+
+			    // Convert results to ResultsHolder
+ 			    actualResults = new ResultsHolder(TagNames.Elements.QUERY_RESULTS);
+		    		actualResults.setQueryID(expectedResults.getQueryID());
+		    		convertResults(resultSet, batchSize,   actualResults);
+
+		      		if (expectedResults.getRows().size() > 0) {
+        			    compareResults(actualResults, expectedResults, eMsg, isOrdered);
+		      		} else if (actualResults.getRows() != null &&  actualResults.getRows().size() > 0) {
+			                throw new QueryTestFailedException(eMsg + "Expected results indicated no results, but actual shows " + actualResults.getRows().size() + " rows."); //$NON-NLS-1$	      		    		      		    
+		      		}
+
+			    // DEBUG:
+			    // debugOut.println("*** Actual Results (holder): " +
+			    // actualResults);
+
+			// Compare expected results with actual results, record by record
+			
+
+			break;
+		    
+	       }
+	
+	return null;
+
+    	
+    }
+    
+    private ResultsHolder convertException(final Throwable actualException,
+			final ResultsHolder actualResults) {
+		actualResults.setExceptionClassName(actualException.getClass()
+				.getName());
+		actualResults.setExceptionMsg(actualException.getMessage());
+		return actualResults;
+	}
+    
+    /**
+     * Helper to convert results into records and record first batch response time.
+     * 
+     * @param results
+     * @param batchSize
+     * @param resultsHolder
+     *            Modified - results added by this method.
+     * @return List of sorted results.
+     * @throws QueryTestFailedException
+     *             replaced SQLException.
+     */
+    private final long convertResults(final ResultSet results,
+                                             final int batchSize,
+                                             ResultsHolder resultsHolder) throws QueryTestFailedException {
+
+        long firstBatchResponseTime = 0;
+        final List records = new ArrayList();
+        final List columnTypeNames = new ArrayList();
+        final List columnTypes = new ArrayList();
+
+        final ResultSetMetaData rsMetadata;
+        final int colCount;
+
+        // Get column info
+        try {
+            rsMetadata = results.getMetaData();
+            colCount = rsMetadata.getColumnCount();
+            // Read types of all columns
+            for (int col = 1; col <= colCount; col++) {
+                columnTypeNames.add(rsMetadata.getColumnName(col));
+                columnTypes.add(rsMetadata.getColumnTypeName(col));
+            }
+        } catch (SQLException qre) {
+            throw new QueryTestFailedException("Can't get results metadata: " + qre.getMessage()); //$NON-NLS-1$
+        }
+
+        // Get rows
+        try {
+            // Read all the rows
+            for (int row = 0; results.next(); row++) {
+                final List currentRecord = new ArrayList(colCount);
+                // Read values for this row
+                for (int col = 1; col <= colCount; col++) {
+                    currentRecord.add(results.getObject(col));
+                }
+                records.add(currentRecord);
+                // If this row is the (fetch size - 1)th row, record first batch response time
+                if (row == batchSize) {
+                    firstBatchResponseTime = System.currentTimeMillis();
+                }
+            }
+        } catch (SQLException qre) {
+            throw new QueryTestFailedException("Can't get results: " + qre.getMessage()); //$NON-NLS-1$
+        }
+
+        // Set info on resultsHolder
+        resultsHolder.setRows(records);
+        resultsHolder.setIdentifiers(columnTypeNames);
+        resultsHolder.setTypes(columnTypes);
+
+        return firstBatchResponseTime;
+    }
+    
+    /**
+     * Added primarily for public access to the compare code for testing.
+     * 
+     * @param actualResults
+     * @param expectedResults
+     * @param eMsg
+     * @param isOrdered
+     * @throws QueryTestFailedException
+     */
+     protected void compareResults(final ResultsHolder actualResults,
+                                      final ResultsHolder expectedResults,
+                                      final String eMsg,
+                                      boolean isOrdered) throws QueryTestFailedException {
+//        if (actualResults.isException() && expectedResults.isException()) {
+//            // Compare exceptions
+//            compareExceptions(actualResults, expectedResults, eMsg);
+//        } else 
+            
+ //           if (actualResults.isResult() && expectedResults.isResult()) {
+            // Compare results
+            if (isOrdered == false && actualResults.hasRows() && expectedResults.hasRows()) {
+                // If the results are not ordered, we can sort both
+                // results and expected results to compare record for record
+                // Otherwise, actual and expected results are already assumed
+                // to be in same order
+
+                //sort the sortedResults in ascending order
+                final List actualRows = actualResults.getRows();
+                sortRecords(actualRows, true);
+                actualResults.setRows(actualRows);
+
+                //sort the expectedResults with ascending order
+                final List expectedRows = expectedResults.getRows();
+                sortRecords(expectedRows, true);
+                expectedResults.setRows(expectedRows);
+            }
+            
+            compareResultSets(actualResults.getRows(),
+                              actualResults.getTypes(),
+                              actualResults.getIdentifiers(),
+                              expectedResults.getRows(),
+                              expectedResults.getTypes(),
+                              expectedResults.getIdentifiers(),
+                              eMsg);
+//        } else if (actualResults.isResult() && expectedResults.isException()) {
+//            // Error - expected exception but got result
+//        } else if (actualResults.isException() && expectedResults.isResult()) {
+//            // Error - expected result but got exception
+//        }
+    }
+     
+     /**
+      * sort one result that is composed of records of all columns
+      */
+     private static void sortRecords(List records,
+                                     boolean ascending) {
+         //if record's size == 0, don't need to sort
+         if (records.size() != 0) {
+             int nFields = ((List)records.get(0)).size();
+             for (int k = 0; k < nFields; k++) {
+                 for (int m = k; m < nFields; m++) {
+                     int[] params = new int[m - k + 1];
+
+                     for (int n = k, j = 0; n <= m; n++, j++) {
+                         params[j] = n;
+                     }
+
+                     Collections.sort(records, new ListNestedSortComparator(params, ascending));
+                 }
+             }
+         }
+     }
+    
+    private void compareExceptions(final ResultsHolder actualResults,
+			final ResultsHolder expectedResults, String eMsg)
+			throws QueryTestFailedException {
+
+		final String expectedExceptionClass = expectedResults
+				.getExceptionClassName();
+		final String expectedExceptionMsg = expectedResults.getExceptionMsg().toLowerCase();
+		final String actualExceptionClass = actualResults
+				.getExceptionClassName();
+		final String actualExceptionMsg = actualResults.getExceptionMsg().toLowerCase();
+
+		if (actualExceptionClass == null) {
+			// We didn't get an actual exception, we should have
+			throw new QueryTestFailedException(eMsg + "Expected exception: " //$NON-NLS-1$
+					+ expectedExceptionClass + " but got none."); //$NON-NLS-1$
+		}
+		// Compare exception classes
+		if (!expectedExceptionClass.equals(actualExceptionClass)) {
+			throw new QueryTestFailedException(eMsg
+					+ "Got wrong exception, expected \"" //$NON-NLS-1$
+					+ expectedExceptionClass + "\" but got \"" + //$NON-NLS-1$
+					actualExceptionClass + "\""); //$NON-NLS-1$
+		}
+		// Compare exception messages
+		if (!expectedExceptionMsg.equals(actualExceptionMsg)) {
+			// Give it another chance by comparing w/o line separators
+			if (!compareStrTokens(expectedExceptionMsg, actualExceptionMsg)) {
+				throw new QueryTestFailedException(
+						eMsg
+								+ "Got expected exception but with wrong message. Got " + actualExceptionMsg); //$NON-NLS-1$
+			}
+		}
+	}
+
+    private boolean compareStrTokens(String expectedStr, String gotStr) {
+		String newline = System.getProperty("line.separator"); //$NON-NLS-1$
+		List expectedTokens = StringUtil.split(expectedStr, newline);
+		List gotTokens = StringUtil.split(gotStr, newline);
+		for (int i = 0; i < expectedTokens.size(); i++) {
+			String expected = (String) expectedTokens.get(i);
+			String got = (String) gotTokens.get(i);
+			if (!expected.equals(got)) {
+				return false;
+			}
+		}
+		return true;
+	}
+    
+    /**
+     * Compare actual results, identifiers and types with expected. <br>
+     * <strong>Note </strong>: result list are expected to match element for element.</br>
+     * 
+     * @param actualResults
+     * @param actualDatatypes
+     * @param actualIdentifiers
+     * @param expectedResults
+     * @param expectedDatatypes
+     * @param expectedIdentifiers
+     * @param eMsg
+     * @throws QueryTestFailedException
+     *             If comparison fails.
+     */
+    protected void compareResultSets(final List actualResults,
+                                          final List actualDatatypes,
+                                          final List actualIdentifiers,
+                                          final List expectedResults,
+                                          final List expectedDatatypes,
+                                          final List expectedIdentifiers,
+                                          final String eMsg) throws QueryTestFailedException {
+        // Compare column names and types
+        compareIdentifiers(actualIdentifiers, expectedIdentifiers, actualDatatypes, expectedDatatypes);
+
+        // Walk through records and compare actual against expected
+        final int actualRowCount = actualResults.size();
+        final int expectedRowCount = expectedResults.size();
+        final int actualColumnCount = actualIdentifiers.size();
+
+        // Check for less records than in expected results
+        if (actualRowCount < expectedRowCount) {
+            throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
+                                               " records but received only " + actualRowCount); //$NON-NLS-1$
+        } else if (actualRowCount > expectedRowCount) {
+            // Check also for more records than expected
+            throw new QueryTestFailedException(eMsg + "Expected " + expectedRowCount + //$NON-NLS-1$
+                                               " records but received " + actualRowCount); //$NON-NLS-1$
+        }
+
+        //      DEBUG:
+        //       debugOut.println("================== Compariing Rows ===================");
+ 
+        // Loop through rows
+        for (int row = 0; row < actualRowCount; row++) {
+
+            // Get actual record
+            final List actualRecord = (List)actualResults.get(row);
+
+            // Get expected record
+            final List expectedRecord = (List)expectedResults.get(row);
+
+            //          DEBUG:
+            //            debugOut.println("Row: " + (row + 1));
+            //            debugOut.println(" expectedRecord: " + expectedRecord);
+            //            debugOut.println(" actualRecord: " + actualRecord);
+            // Loop through columns
+            // Compare actual elements with expected elements column by column in this row
+            for (int col = 0; col < actualColumnCount; col++) {
+                // Get actual value
+                Object actualValue = actualRecord.get(col);
+                // Get expected value
+                Object expectedValue = expectedRecord.get(col);
+ 
+                //              DEBUG:
+                //                debugOut.println(" Col: " +(col +1) + ": expectedValue:[" + expectedValue + "] actualValue:[" + actualValue +
+                // "]");
+
+                // Compare these values
+                if ( ( expectedValue == null && actualValue != null) ||
+                		(actualValue == null && expectedValue != null) ){
+                    // Compare nulls
+                        throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
+                                                           + " and column " + (col + 1) //$NON-NLS-1$
+                                                           + ": expected = [" //$NON-NLS-1$
+                                                           + (expectedValue!=null?expectedValue:"null") + "], actual = [" //$NON-NLS-1$
+                                                           + (actualValue!=null?actualValue:"null")  + "]"); //$NON-NLS-1$
+
+                } 
+                
+                if (expectedValue == null && actualValue == null) {
+                	continue;
+                }
+                	
+                if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) {
+                    	 
+                	if (actualValue instanceof Clob){
+                		Clob c = (Clob)actualValue;
+                		try {
+							actualValue = ObjectConverterUtil.convertToString(c.getAsciiStream());
+							
+						} catch (Throwable e) {
+							// TODO Auto-generated catch block
+							throw new QueryTestFailedException(e);
+						}
+                	} else if (actualValue instanceof Blob){
+                    		Blob b = (Blob)actualValue;
+                    		try {
+    							actualValue = ObjectConverterUtil.convertToString(b.getBinaryStream());
+    							
+    						} catch (Throwable e) {
+    							// TODO Auto-generated catch block
+    							throw new QueryTestFailedException(e);
+    						}
+                    } else if (actualValue instanceof SQLXML){
+                    	SQLXML s = (SQLXML)actualValue;
+                		try {
+							actualValue = ObjectConverterUtil.convertToString(s.getBinaryStream());
+							
+						} catch (Throwable e) {
+							// TODO Auto-generated catch block
+							throw new QueryTestFailedException(e);
+						}
+                    } 
+
+                	
+                	if (!(expectedValue instanceof String)) {
+                		expectedValue = expectedValue.toString();
+                	}
+                } 
+                	
+                    // Compare values with equals
+                    if (!expectedValue.equals(actualValue)) {
+                        // DEBUG:
+                        //                        debugOut.println(" ExpectedType: " + expectedValue.getClass() + " ActualType: " +
+                        // actualValue.getClass());
+                	
+                         if (expectedValue instanceof String) {
+                            final String expectedString = (String)expectedValue;
+//                            if (actualValue instanceof Blob || actualValue instanceof Clob || actualValue instanceof SQLXML) {
+//                            	
+//                            	Clob c = (Clob)actualValue;
+//                                // LOB types are special case - metadata says they're Object types so
+//                                // expected results are of type String. Actual object type is MMBlob, MMClob.
+//                                // Must compare w/ String verion of actual!
+//                                if (!expectedValue.equals(actualValue.toString())) {
+//                                    throw new QueryTestFailedException(eMsg + "LOB Value mismatch at row " + (row + 1) //$NON-NLS-1$
+//                                                                       + " and column " + (col + 1) //$NON-NLS-1$
+//                                                                       + ": expected = [" //$NON-NLS-1$
+//                                                                       + expectedValue + "], actual = [" //$NON-NLS-1$
+//                                                                       + actualValue + "]"); //$NON-NLS-1$
+//                                }
+//                            } else 
+                            if (!(actualValue instanceof String)) {
+                                throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
+                                                                   + " and column " + (col + 1) //$NON-NLS-1$
+                                                                   + ": expected = [" //$NON-NLS-1$
+                                                                   + expectedValue + "], actual = [" //$NON-NLS-1$
+                                                                   + actualValue + "]"); //$NON-NLS-1$
+                            } else if (expectedString.length() > 0) {
+                                // Check for String difference
+                                assertStringsMatch(expectedString, (String)actualValue, (row + 1), (col + 1), eMsg);
+                            }
+                        } else {
+                            
+                            throw new QueryTestFailedException(eMsg + "Value mismatch at row " + (row + 1) //$NON-NLS-1$
+                                    + " and column " + (col + 1) //$NON-NLS-1$
+                                    + ": expected = [" //$NON-NLS-1$
+                                    + expectedValue + "], actual = [" //$NON-NLS-1$
+                                    + actualValue + "]"); //$NON-NLS-1$
+              
+                        }
+                    }
+
+            } // end loop through columns
+        } // end loop through rows
+    }
+    
+ 
+    
+    protected void compareIdentifiers(List actualIdentifiers,
+			List expectedIdentifiers, List actualDataTypes,
+			List expectedDatatypes) throws QueryTestFailedException {
+
+		// Check sizes
+		if (expectedIdentifiers.size() != actualIdentifiers.size()) {
+			throw new QueryTestFailedException(
+					"Got incorrect number of columns, expected = " + expectedIdentifiers.size() + ", actual = " //$NON-NLS-1$ //$NON-NLS-2$
+							+ actualIdentifiers.size());
+		}
+
+		// Compare identifier lists only by short name
+		for (int i = 0; i < actualIdentifiers.size(); i++) {
+			String actualIdent = (String) actualIdentifiers.get(i);
+			String expectedIdent = (String) expectedIdentifiers.get(i);
+			String actualType = (String) actualDataTypes.get(i);
+			String expectedType = (String) expectedDatatypes.get(i);
+
+			// Get short name for each identifier
+			String actualShort = getShortName(actualIdent);
+			String expectedShort = getShortName(expectedIdent);
+
+			if (!expectedShort.equalsIgnoreCase(actualShort)) {
+				throw new QueryTestFailedException(
+						"Got incorrect column name at column " + i + ", expected = " + expectedShort + " but got = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+								+ actualShort);
+			}
+			if (actualType.equalsIgnoreCase("xml")) {//$NON-NLS-1$
+				actualType = "string";//$NON-NLS-1$
+			}
+			if (actualType.equalsIgnoreCase("clob")) {//$NON-NLS-1$
+				actualType = "string";//$NON-NLS-1$
+			}
+			if (!expectedType.equalsIgnoreCase(actualType)) {
+				throw new QueryTestFailedException(
+						"Got incorrect column type at column " + i + ", expected = " + expectedType + " but got = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+								+ actualType);
+			}
+		}
+	}
+
+
+   protected  String getShortName(String ident) {
+        int index = ident.lastIndexOf("."); //$NON-NLS-1$
+        if (index >= 0) {
+            return ident.substring(index + 1);
+        }
+        return ident;
+    }
+    
+    private static final int MISMATCH_OFFSET = 20;
+    private static final int MAX_MESSAGE_SIZE = 50;
+
+ 
+    
+   protected void assertStringsMatch(final String expectedStr, final String actualStr,
+			final int row, final int col, final String eMsg)
+			throws QueryTestFailedException {
+		// TODO: Replace stripCR() with XMLUnit comparison for XML results.
+		// stripCR() is a workaround for comparing XML Queries
+		// that have '\r'.
+		String expected = stripCR(expectedStr).trim();
+		String actual = stripCR(actualStr).trim();
+
+		String locationText = ""; //$NON-NLS-1$
+		int mismatchIndex = -1;
+		
+		
+		boolean isequal = Arrays.equals(expected.toCharArray(), actual.toCharArray());
+		
+		//if (!expected.equals(actual)) {
+		if (!isequal) {
+			if (expected != null && actual != null) {
+				int shortestStringLength = expected.length();
+				if (actual.length() < expected.length()) {
+					shortestStringLength = actual.length();
+				} 
+				for (int i = 0; i < shortestStringLength; i++) {
+					if (expected.charAt(i) != actual.charAt(i)) {
+						locationText = "  Strings do not match at character: " + (i + 1) + //$NON-NLS-1$
+								". Expected [" + expected.charAt(i)
+								+ "] but got [" + actual.charAt(i) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						mismatchIndex = i;
+						break;
+					}
+				}
+			}
+
+			String expectedPartOfMessage = expected;
+			String actualPartOfMessage = actual;
+			if (expected.length() + actual.length() > MAX_MESSAGE_SIZE) {
+				expectedPartOfMessage = safeSubString(expected, mismatchIndex
+						- MISMATCH_OFFSET, mismatchIndex + MISMATCH_OFFSET);
+				actualPartOfMessage = safeSubString(actual, mismatchIndex
+						- MISMATCH_OFFSET, mismatchIndex + MISMATCH_OFFSET);
+			}
+
+			String message = eMsg + "Value mismatch at row " + row + //$NON-NLS-1$
+					" and column " + col + //$NON-NLS-1$
+					". Expected: {0} but was: {1}" + locationText; //$NON-NLS-1$
+			message = MessageFormat.format(message, new Object[] {
+					expectedPartOfMessage, actualPartOfMessage });
+			throw new QueryTestFailedException(message);
+		}
+	}
+    
+    private String safeSubString(String text, int startIndex,
+			int endIndex) {
+		String prefix = "...'"; //$NON-NLS-1$
+		String suffix = "'..."; //$NON-NLS-1$
+
+		int actualStartIndex = startIndex;
+		if (actualStartIndex < 0) {
+			actualStartIndex = 0;
+			prefix = "'"; //$NON-NLS-1$
+		}
+		int actualEndIndex = endIndex;
+		if (actualEndIndex > text.length() - 1) {
+			actualEndIndex = text.length() - 1;
+			if (actualEndIndex < 0) {
+				actualEndIndex = 0;
+			}
+		}
+		if (actualEndIndex == text.length() - 1 || text.length() == 0) {
+			suffix = "'"; //$NON-NLS-1$
+		}
+
+		return prefix + text.substring(actualStartIndex, actualEndIndex)
+				+ suffix;
+	}
+
+
+    
+    private String stripCR(final String text) {
+        if (text.indexOf('\r') >= 0) {
+            StringBuffer stripped = new StringBuffer(text.length());
+            int len = text.length();
+            for (int i = 0; i < len; i++) {
+                char current = text.charAt(i);
+                if (current != '\r') {
+                    stripped.append(current);
+                }
+            }
+            return stripped.toString();
+        }
+        return text;
+    }
+
+
+	@Override
+	public Object getMetaData(String queryidentifier) {
+		// TODO Auto-generated method stub
+		return null;
+	}
+
+
+	private ResultsHolder loadExpectedResults(File resultsFile) throws QueryTestFailedException {
+        XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
+        final ResultsHolder expectedResult;
+        try {
+            expectedResult = jstrat.parseXMLResultsFile(resultsFile);
+        } catch (IOException e) {
+            throw new QueryTestFailedException("Unable to load expected results: " + e.getMessage()); //$NON-NLS-1$
+        } catch (JDOMException e) {
+            throw new QueryTestFailedException("Unable to load expected results: " + e.getMessage()); //$NON-NLS-1$
+        }
+        return expectedResult;
+    }
+	
+    private File findExpectedResultsFile(String queryIdentifier,
+			String querySetIdentifier) throws QueryTestFailedException {
+		String resultFileName = queryIdentifier + ".xml"; //$NON-NLS-1$
+		File file = new File(results_dir_loc + "/" + querySetIdentifier, resultFileName);
+		if (!file.exists() && this.isExpectedResultsNeeded()) {
+			throw new QueryTestFailedException("Query results file " + file.getAbsolutePath() + " cannot be found");
+		}
+		
+		return file;
+
+	}
+    
+	public static void main(String[] args) {
+		System.setProperty(ConfigPropertyNames.CONFIG_FILE, "ctc-bqt-test.properties");
+
+		ConfigPropertyLoader _instance = ConfigPropertyLoader.getInstance();
+		Properties p = _instance.getProperties();
+		if (p == null || p.isEmpty()) {
+			throw new RuntimeException("Failed to load config properties file");
+
+		}
+		
+		QueryScenario set = ClassFactory.createQueryScenario("testscenario");
+
+		
+		_instance.setProperty(XMLQueryReader.PROP_QUERY_FILES_ROOT_DIR, new File("src/main/resources/").getAbsolutePath() );
+		
+
+		
+
+		try {
+
+		    Iterator<String> it = set.getQuerySetIDs().iterator();
+		    while (it.hasNext()) {
+			String querySetID = it.next();
+
+			List<QueryTest> queries = set.getQueries(querySetID);
+			if (queries.size() == 0l) {
+				System.out.println("Failed, didn't load any queries " );
+			}
+			
+				
+				ExpectedResults er = set.getExpectedResults(querySetID);
+				    //new XMLExpectedResults(_instance.getProperties(), querySetID);
+								
+				ResultsGenerator gr = set.getResultsGenerator();
+				    //new XMLGenerateResults(_instance.getProperties(), "testname", set.getOutputDirectory());
+
+				Iterator<QueryTest> qIt = queries.iterator();
+				while(qIt.hasNext()) {
+				    QueryTest q = qIt.next();
+				//	String qId = (String) qIt.next();
+				//	String sql = (String) queries.get(qId);
+					
+//					System.out.println("SetID #: " + cnt + "  Qid: " + qId + "   sql: " + sql);
+					
+					File resultsFile = er.getResultsFile(q.getQueryID());
+					if (resultsFile == null) {
+						System.out.println("Failed to get results file for queryID " + q.getQueryID());
+					}
+					
+	
+					
+					
+				}
+
+		    }
+			
+			System.out.println("Completed Test");
+
+		} catch (QueryTestFailedException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+
+	}
+    
+	private  long compareResults(final ResultsHolder expectedResults,
+	    final ResultSet results, final int testStatus, final Throwable actualException,
+	    final boolean isOrdered, final int batchSize)
+	    throws QueryTestFailedException {
+
+	ResultsHolder actualResults;
+	long firstBatchResponseTime = 0;
+	final String eMsg = "CompareResults Error: "; //$NON-NLS-1$
+	
+	       switch (testStatus) {
+		case TestResult.RESULT_STATE.TEST_EXCEPTION:
+	                throw new QueryTestFailedException(eMsg + "TestResult indicates test exception occured, the process should not have passed it in for comparison."); //$NON-NLS-1$
+			
+			
+//			break;
+			
+		case TestResult.RESULT_STATE.TEST_EXPECTED_EXCEPTION:
+		//    String actualExceptionClass = actualException.getClass().getName();
+
+		            if (!expectedResults.isException()) {
+		                // The actual exception was expected, but the expected results was not
+		                throw new QueryTestFailedException(eMsg + "The actual result was an exception, but the Expected results wasn't an exception.  Actual exception: '" //$NON-NLS-1$
+		                                                   + actualException.getMessage() + "'"); //$NON-NLS-1$
+		            }
+		            // We got an exception that we expected - convert actual exception to ResultsHolder
+		            actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
+		            actualResults.setQueryID(expectedResults.getQueryID());
+
+		            actualResults = convertException(actualException, actualResults);
+		            
+		            compareExceptions(actualResults, expectedResults, eMsg);
+
+		            return firstBatchResponseTime;
+		    
+//		    	break;
+		    
+	       }
+	       
+
+
+//	if (results == null) {
+//	    // The result is an exception - compare exceptions
+//
+//	    String actualExceptionClass = null;
+//	    if (actualException != null) {
+//		actualExceptionClass = actualException.getClass().getName();
+//	    } else {
+//		// We didn't get results but there was no exception either
+//		throw new QueryTestFailedException(eMsg
+//			+ "Didn't get results or exception '"); //$NON-NLS-1$
+//	    }
+//
+//	    if (!expectedResults.isException()) {
+//		// We didn't get results but there was no expected exception
+//		// either
+//		throw new QueryTestFailedException(
+//			eMsg
+//				+ "Expected results but didn't get results or exception '" //$NON-NLS-1$
+//				+ actualExceptionClass + "'"); //$NON-NLS-1$
+//	    }
+//	    // We got an exception that we expected - convert actual exception
+//	    // to ResultsHolder
+//	    actualResults = new ResultsHolder(TagNames.Elements.EXCEPTION);
+//	    actualResults.setQueryID(expectedResults.getQueryID());
+//
+//	    actualResults = convertException(actualException, actualResults);
+//
+//	} else {
+	    // The result is a ResultSet - compare actual results with expected
+
+	    if (expectedResults.isException()) {
+		throw new QueryTestFailedException(
+			eMsg
+				+ "Expected exception " + expectedResults.getExceptionMsg() //$NON-NLS-1$
+				+ " but got results"); //$NON-NLS-1$
+	    }
+	    // DEBUG:
+	    // debugOut.println("*** Expected Results (holder): " +
+	    // expectedResults);
+	    // DEBUG:
+	    // debugOut.println("*** Actual Results (ResultSet): " +
+	    // printResultSet(results));
+
+	    // Convert results to ResultsHolder
+	    actualResults = new ResultsHolder(TagNames.Elements.QUERY_RESULTS);
+	    actualResults.setQueryID(expectedResults.getQueryID());
+	    firstBatchResponseTime = convertResults(results, batchSize,
+		    actualResults);
+
+	    // DEBUG:
+	    // debugOut.println("*** Actual Results (holder): " +
+	    // actualResults);
+//	} // end is resultSet
+
+	// Compare expected results with actual results, record by record
+	compareResults(actualResults, expectedResults, eMsg, isOrdered);
+
+	return firstBatchResponseTime;
+    }
+
+
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,548 +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.test.client.ctc;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-
-import org.jdom.Attribute;
-import org.jdom.CDATA;
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.JDOMException;
-import org.jdom.output.XMLOutputter;
-import org.junit.Assert;
-import org.teiid.core.util.FileUtils;
-import org.teiid.core.util.StringUtil;
-import org.teiid.internal.core.xml.JdomHelper;
-import org.teiid.test.client.ResultsGenerator;
-import org.teiid.test.client.TestProperties;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.util.TestResultSetUtil;
-
-
-public class XMLGenerateResults implements ResultsGenerator {
-    private static final SimpleDateFormat FILE_NAME_DATE_FORMATER = new SimpleDateFormat(
-	    "yyyyMMdd_HHmmss"); //$NON-NLS-1$
-    private static final int MAX_COL_WIDTH = 65;
-    
-    private String outputDir = "";
-    private String generateDir = "";
-    
-
-    public XMLGenerateResults( String testname, Properties props) {
-	
-	outputDir = props.getProperty(TestProperties.PROP_OUTPUT_DIR, ".");
-
-	Assert.assertNotNull("Property " + TestProperties.PROP_OUTPUT_DIR
-		+ " was not specified", outputDir);
-
-	outputDir = outputDir + "/" + testname;
-
-	File d = new File(this.outputDir);
-	this.outputDir = d.getAbsolutePath();
-	d = new File(this.outputDir);
-	if (d.exists()) {
-	    FileUtils.removeDirectoryAndChildren(d);
-
-	}
-	if (!d.exists()) {
-	    d.mkdirs();
-	}
-
-	generateDir = props.getProperty(PROP_GENERATE_DIR, ".");
-	Assert.assertNotNull("Property " + PROP_GENERATE_DIR
-		+ " was not specified", this.generateDir);
-
-	d = new File(generateDir, testname);
-	generateDir = d.getAbsolutePath();
-	d = new File(generateDir);
-	if (d.exists()) {
-	    FileUtils.removeDirectoryAndChildren(d);
-	}
-	if (!d.exists()) {
-	    d.mkdirs();
-	}
-
-    }
-
-    @Override
-    public String getGenerateDir() {
-	// TODO Auto-generated method stub
-	return this.generateDir;
-    }
-
-    @Override
-    public String getOutputDir() {
-	// TODO Auto-generated method stub
-	return outputDir;
-    }
-
-    /**
-     * Generate query results. These are actual results from the server and may
-     * be used for comparing to results from a later test run.
-     * 
-     * @param queryID
-     * @param resultsFile
-     * @param result
-     * @param ex
-     * @throws QueryTestFailedException
-     */
-
-    public void generateQueryResultFile(String querySetID, String queryID,
-	    String query, ResultSet result, Throwable ex, int testStatus)
-	    throws QueryTestFailedException {
-
-    	try {
-			System.out.println("GENERATE QRF: " + result.isClosed());
-		} catch (SQLException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		}
-	File resultsFile = createNewResultsFile(queryID, querySetID,
-		getGenerateDir());
-	OutputStream outputStream;
-	try {
-	    FileOutputStream fos = new FileOutputStream(resultsFile);
-	    outputStream = new BufferedOutputStream(fos);
-	} catch (IOException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to open new results file: " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	try {
-	    XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
-
-	    // Create root JDOM element
-	    Element rootElement = new Element(TagNames.Elements.ROOT_ELEMENT);
-
-	    // Create Query element
-	    Element queryElement = new Element(TagNames.Elements.QUERY);
-	    queryElement.addContent(new CDATA(query));
-	    rootElement.addContent(queryElement);
-
-	    // create a result attribute for the queryID
-	    Attribute resultsIDAttribute = new Attribute(
-		    TagNames.Attributes.NAME, queryID);
-
-	    if (result != null) {
-		// produce a JDOM element from the results object
-		Element resultsElement = jstrat.produceResults(result);
-		// set the resultsIDAttribute on the results element
-		resultsElement.setAttribute(resultsIDAttribute);
-		// add the results elements to the root element
-		rootElement.addContent(resultsElement);
-		// debug:
-		// System.out.println("\n Result: " + printResultSet(result));
-	    } else {
-		// create a JDOM element from the exception object with the
-		// results tag
-		Element exceptionElement = new Element(
-			TagNames.Elements.QUERY_RESULTS);
-		// produce xml for the actualException and this to the
-		// exceptionElement
-		if (ex != null) {
-		    exceptionElement.addContent(jstrat.produceMsg(ex, null));
-		}
-		// set the resultsIDAttribute on the exception element
-		exceptionElement.setAttribute(resultsIDAttribute);
-		// add the results elements to the root element
-		rootElement.addContent(exceptionElement);
-
-	    }
-
-	    // Output xml
-	    XMLOutputter outputter = new XMLOutputter(JdomHelper.getFormat(
-		    "  ", true)); //$NON-NLS-1$
-	    outputter.output(new Document(rootElement), outputStream);
-
-	} catch (SQLException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert results to JDOM: " + e.getMessage()); //$NON-NLS-1$
-	} catch (JDOMException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert results to JDOM: " + e.getMessage()); //$NON-NLS-1$
-	} catch (IOException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to output new results to " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
-	} catch (Throwable e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert results to JDOM: " + StringUtil.getStackTrace(e)); //$NON-NLS-1$
-	} finally {
-	    try {
-		outputStream.close();
-	    } catch (IOException e) {
-	    }
-	}
-    }
-    
-//  Begin New from Impl
-    
-    
-    public String generateErrorFile_keep(final String querySetID,
-	    final String queryID, final String sql, final ResultSet resultSet,
-	    final Throwable queryError, final Object results)
-	    throws QueryTestFailedException {
-
-	String errorFileName = null;
-	try {
-	    // write actual results to error file
-	    errorFileName = generateErrorFileName(queryID, querySetID);
-	    // configID, queryID, Integer.toString(clientID));
-	    //           CombinedTestClient.log("\t" + this.clientID + ": Writing error file with actual results: " + errorFileName); //$NON-NLS-1$ //$NON-NLS-2$
-	    File errorFile = new File(getOutputDir(), errorFileName);
-	    
-	    // the resultset will be passed in as null when
-	    // the error was due to a thrown exception, and not based comparison issues 
-	    if (resultSet == null) {
-		FileOutputStream actualOut = null;
-		try {
-		    actualOut = new FileOutputStream(errorFile);
-		    PrintStream filePrintStream = new PrintStream(actualOut);
-		    
-
-		    TestResultSetUtil.printThrowable(queryError, sql, filePrintStream);
-		    
-		    filePrintStream.flush();
-
-		} catch (Exception e) {
-			    e.printStackTrace();
-			    throw new QueryTestFailedException(e);
-		} finally {
-		    	if (actualOut != null) {
-				try {
-				    actualOut.close();
-				} catch (IOException e) {
-				    // TODO Auto-generated catch block
-				    e.printStackTrace();
-				}
-			}
-		}
-		return errorFileName;
-
-	    }
-
-	    // rewind resultset
-
-	    resultSet.beforeFirst();
-
-	    generateErrorResults(querySetID, queryID, sql, errorFile,
-		    resultSet, (File) results);
-
-	} catch (Throwable e) {
-	    throw new QueryTestFailedException(e.getMessage());
-	    //           CombinedTestClient.logError("Error writing error file \"" + outputDir + "\"/" + errorFileName + ": " + e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	return errorFileName;
-    }
-
-    
-    /**
-     * Generate an error file for a query that failed comparison. File should
-     * have the SQL, the actual results returned from the server and the results
-     * that were expected.
-     * 
-     * @param queryID
-     * @param sql
-     * @param resultsFile
-     * @param actualResult
-     * @param expectedResultFile
-     * @param ex
-     * @throws QueryTestFailedException
-     */
-    private void generateErrorResults(String querySetID, String queryID,
-	    String sql, File resultsFile, ResultSet actualResult,
-	    File results)
-	    throws QueryTestFailedException {
-	
-	FileOutputStream actualOut = null;
-	try {
-	    actualOut = new FileOutputStream(resultsFile);
-	    PrintStream filePrintStream = new PrintStream(actualOut);
-	    
-	    TestResultSetUtil.printResultSet(actualResult, sql, MAX_COL_WIDTH, true, filePrintStream);
-    	    
-
-	} catch (Exception e) {
-	    e.printStackTrace();
-	    throw new QueryTestFailedException(e);
-	} finally {
-	    if (actualOut != null) {
-		try {
-		    actualOut.close();
-		} catch (IOException e) {
-		    // TODO Auto-generated catch block
-		    e.printStackTrace();
-		}
-	    }
-	}
-    }
-//  End of copy from impl 
-   
-    public String generateErrorFile(final String querySetID,
-	    final String queryID, final String sql, final ResultSet resultSet,
-	    final Throwable queryError, final Object expectedResultsFile)
-	    throws QueryTestFailedException {
-
-	String errorFileName = null;
-	try {
-	    // write actual results to error file
-	    errorFileName = generateErrorFileName(queryID, querySetID);
-	    // configID, queryID, Integer.toString(clientID));
-	    //           CombinedTestClient.log("\t" + this.clientID + ": Writing error file with actual results: " + errorFileName); //$NON-NLS-1$ //$NON-NLS-2$
-	    File errorFile = new File(getOutputDir(), errorFileName);
-
-	    // rewind resultset
-	    if (resultSet != null) {
-		resultSet.beforeFirst();
-	    }
-	    generateErrorResults(querySetID, queryID, sql, errorFile,
-		    resultSet, (File) expectedResultsFile, queryError);
-
-	} catch (Throwable e) {
-	    throw new QueryTestFailedException(e.getMessage());
-	    //           CombinedTestClient.logError("Error writing error file \"" + outputDir + "\"/" + errorFileName + ": " + e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-	}
-	return errorFileName;
-    }
-
-    private File createNewResultsFile(String queryID, String querySetID,
-	    String genDir) {
-	String resultFileName = queryID + ".xml"; //$NON-NLS-1$
-
-	String targetDirname = genDir + File.separator + querySetID; //$NON-NLS-1$
-	File targetDir = new File(targetDirname);
-	targetDir.mkdirs();
-
-	return new File(targetDir, resultFileName);
-    }
-
-    //    
-    // private String generateErrorFileName(String queryID,
-    // String querySetID,
-    // String outputdir) {
-    //    	
-    // File resultsFile = createNewResultsFile(queryID, querySetID,
-    // this.outputDir);
-    //    	
-    // // String queryFileName = queryFile.getName();
-    // String name =
-    // FileUtils.getFilenameWithoutExtension(resultsFile.getName());
-    // String errorFileName = "ERROR_"
-    //                                   + name + "_" //$NON-NLS-1$
-    //                                   + FILE_NAME_DATE_FORMATER.format(new Date(System.currentTimeMillis())) + ".xml"; //$NON-NLS-1$
-    // return errorFileName;
-    //  	
-    // }
-
-    private String generateErrorFileName(String queryID, String querySetID) {
-//	String errorFileName = "ERROR_"
-		// configID + "_" //$NON-NLS-1$ //$NON-NLS-2$
-		//                               + querySetID + "_" //$NON-NLS-1$
-//	    String errorFileName = queryID +
-//		+ "_" //$NON-NLS-1$
-//		+ FILE_NAME_DATE_FORMATER.format(new Date(System
-//			.currentTimeMillis())) + ".xml"; //$NON-NLS-1$
-//	return errorFileName;
-	
-	return  queryID + ".err";
-    }
-
-    /**
-     * Generate an error file for a query that failed comparison. File should
-     * have the SQL, the actual results returned from the server and the results
-     * that were expected.
-     * 
-     * @param queryID
-     * @param sql
-     * @param resultsFile
-     * @param actualResult
-     * @param expectedResultFile
-     * @param ex
-     * @throws QueryTestFailedException
-     */
-    private void generateErrorResults(String querySetID, String queryID,
-	    String sql, File resultsFile, ResultSet actualResult,
-	    File expectedResultFile, Throwable ex)
-	    throws QueryTestFailedException {
-	OutputStream outputStream;
-	try {
-	    FileOutputStream fos = new FileOutputStream(resultsFile);
-	    outputStream = new BufferedOutputStream(fos);
-	} catch (IOException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to open error results file: " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
-	}
-
-	try {
-	    XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
-
-	    // Create root JDOM element
-	    Element rootElement = new Element(TagNames.Elements.ROOT_ELEMENT);
-
-	    // create a JDOM element for the results
-	    Element resultElement = new Element(TagNames.Elements.QUERY_RESULTS);
-	    // set the queryIDAttr on the exception element
-	    resultElement.setAttribute(new Attribute(TagNames.Attributes.NAME,
-		    queryID));
-	    // set the querySQLAttr on the exception element
-	    resultElement.setAttribute(new Attribute(TagNames.Attributes.VALUE,
-		    sql));
-
-	    // ---------------------
-	    // Actual Exception
-	    // ---------------------
-	    // create a JDOM element from the actual exception object
-	    // produce xml for the actualException and this to the
-	    // exceptionElement
-	    if (ex != null) {
-		Element actualExceptionElement = new Element(
-			TagNames.Elements.ACTUAL_EXCEPTION);
-
-		actualExceptionElement = XMLQueryVisitationStrategy
-			.jdomException(ex, actualExceptionElement);
-		resultElement.addContent(actualExceptionElement);
-	    }
-
-	    if (actualResult != null) {
-		// ------------------------------
-		// Got a ResultSet from server
-		// error was in comparing results
-		// ------------------------------
-
-		// --------------------------
-		// Actual Result - ResultSet
-		// --------------------------
-		// produce a JDOM element from the actual results object
-		Element actualResultsElement = new Element(
-			TagNames.Elements.ACTUAL_QUERY_RESULTS);
-		actualResultsElement = jstrat.produceMsg(actualResult,
-			actualResultsElement);
-
-		// add the results elements to the root element
-		resultElement.addContent(actualResultsElement);
-
-		// ---------------------
-		// Expected Results - ...
-		// ---------------------
-		// produce xml for the expected results
-		// Get expected results
-		Element expectedResult = new Element("bogus"); //$NON-NLS-1$
-		expectedResult = jstrat.parseXMLResultsFile(expectedResultFile,
-			expectedResult);
-		if (expectedResult.getChild(TagNames.Elements.SELECT) != null) {
-		    //----------------------------------------------------------
-		    // -
-		    // Expected result was a ResultSet set element name to
-		    // reflect
-		    //----------------------------------------------------------
-		    // -
-		    expectedResult
-			    .setName(TagNames.Elements.EXPECTED_QUERY_RESULTS);
-		} else {
-		    //----------------------------------------------------------
-		    // --
-		    // Expected result was an exception set element name to
-		    // reflect
-		    //----------------------------------------------------------
-		    // --
-		    expectedResult
-			    .setName(TagNames.Elements.EXPECTED_EXCEPTION);
-		}
-		resultElement.addContent(expectedResult);
-	    } else {
-
-		// ---------------------
-		// Expected Results - ...
-		// ---------------------
-		// produce xml for the expected results
-		// Get expected results
-		Element expectedResult = new Element("bogus"); //$NON-NLS-1$
-		expectedResult = jstrat.parseXMLResultsFile(expectedResultFile,
-			expectedResult);
-		if (expectedResult.getChild(TagNames.Elements.SELECT) != null) {
-		    //----------------------------------------------------------
-		    // -
-		    // Expected result was a ResultSet set element name to
-		    // reflect
-		    //----------------------------------------------------------
-		    // -
-		    expectedResult
-			    .setName(TagNames.Elements.EXPECTED_QUERY_RESULTS);
-		} else {
-		    //----------------------------------------------------------
-		    // --
-		    // Expected result was an exception set element name to
-		    // reflect
-		    //----------------------------------------------------------
-		    // --
-		    expectedResult
-			    .setName(TagNames.Elements.EXPECTED_EXCEPTION);
-		}
-		resultElement.addContent(expectedResult);
-	    }
-
-	    // ------------------------------
-	    // Got an exeption from the server
-	    // error was in comparing exceptions
-	    // ------------------------------
-
-	    // add the results elements to the root element
-	    rootElement.addContent(resultElement);
-
-	    // Output xml
-	    XMLOutputter outputter = new XMLOutputter(JdomHelper.getFormat(
-		    "  ", true)); //$NON-NLS-1$
-	    outputter.output(new Document(rootElement), outputStream);
-
-	} catch (SQLException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert error results to JDOM: " + e.getMessage()); //$NON-NLS-1$
-	} catch (JDOMException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert error results to JDOM: " + e.getMessage()); //$NON-NLS-1$
-	} catch (IOException e) {
-	    throw new QueryTestFailedException(
-		    "Failed to output error results to " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
-	} catch (Throwable e) {
-	    throw new QueryTestFailedException(
-		    "Failed to convert error results to JDOM: " + StringUtil.getStackTrace(e)); //$NON-NLS-1$
-	} finally {
-	    try {
-		outputStream.close();
-	    } catch (IOException e) {
-	    }
-	}
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLGenerateResults.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,547 @@
+/*
+ * 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.test.client.ctc;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+
+import org.jdom.Attribute;
+import org.jdom.CDATA;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.JDOMException;
+import org.jdom.output.XMLOutputter;
+import org.junit.Assert;
+import org.teiid.core.util.FileUtils;
+import org.teiid.core.util.StringUtil;
+import org.teiid.internal.core.xml.JdomHelper;
+import org.teiid.test.client.ResultsGenerator;
+import org.teiid.test.client.TestProperties;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.util.TestResultSetUtil;
+
+
+public class XMLGenerateResults implements ResultsGenerator {
+    private static final SimpleDateFormat FILE_NAME_DATE_FORMATER = new SimpleDateFormat(
+	    "yyyyMMdd_HHmmss"); //$NON-NLS-1$
+    private static final int MAX_COL_WIDTH = 65;
+    
+    private String outputDir = "";
+    private String generateDir = "";
+    
+
+    public XMLGenerateResults( String testname, Properties props) {
+	
+	outputDir = props.getProperty(TestProperties.PROP_OUTPUT_DIR, ".");
+
+	Assert.assertNotNull("Property " + TestProperties.PROP_OUTPUT_DIR
+		+ " was not specified", outputDir);
+
+	outputDir = outputDir + "/" + testname;
+
+	File d = new File(this.outputDir);
+	this.outputDir = d.getAbsolutePath();
+	d = new File(this.outputDir);
+	if (d.exists()) {
+	    FileUtils.removeDirectoryAndChildren(d);
+
+	}
+	if (!d.exists()) {
+	    d.mkdirs();
+	}
+
+	generateDir = props.getProperty(PROP_GENERATE_DIR, ".");
+	Assert.assertNotNull("Property " + PROP_GENERATE_DIR
+		+ " was not specified", this.generateDir);
+
+	d = new File(generateDir, testname);
+	generateDir = d.getAbsolutePath();
+	d = new File(generateDir);
+	if (d.exists()) {
+	    FileUtils.removeDirectoryAndChildren(d);
+	}
+	if (!d.exists()) {
+	    d.mkdirs();
+	}
+
+    }
+
+    @Override
+    public String getGenerateDir() {
+	// TODO Auto-generated method stub
+	return this.generateDir;
+    }
+
+    @Override
+    public String getOutputDir() {
+	// TODO Auto-generated method stub
+	return outputDir;
+    }
+
+    /**
+     * Generate query results. These are actual results from the server and may
+     * be used for comparing to results from a later test run.
+     * 
+     * @param queryID
+     * @param resultsFile
+     * @param result
+     * @param ex
+     * @throws QueryTestFailedException
+     */
+
+    public void generateQueryResultFile(String querySetID, String queryID,
+	    String query, ResultSet result, Throwable ex, int testStatus)
+	    throws QueryTestFailedException {
+
+    	try {
+			if (result != null ) result.isClosed();
+		} catch (SQLException e1) {
+			e1.printStackTrace();
+		}
+	File resultsFile = createNewResultsFile(queryID, querySetID,
+		getGenerateDir());
+	OutputStream outputStream;
+	try {
+	    FileOutputStream fos = new FileOutputStream(resultsFile);
+	    outputStream = new BufferedOutputStream(fos);
+	} catch (IOException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to open new results file: " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	try {
+	    XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
+
+	    // Create root JDOM element
+	    Element rootElement = new Element(TagNames.Elements.ROOT_ELEMENT);
+
+	    // Create Query element
+	    Element queryElement = new Element(TagNames.Elements.QUERY);
+	    queryElement.addContent(new CDATA(query));
+	    rootElement.addContent(queryElement);
+
+	    // create a result attribute for the queryID
+	    Attribute resultsIDAttribute = new Attribute(
+		    TagNames.Attributes.NAME, queryID);
+
+	    if (result != null) {
+		// produce a JDOM element from the results object
+		Element resultsElement = jstrat.produceResults(result);
+		// set the resultsIDAttribute on the results element
+		resultsElement.setAttribute(resultsIDAttribute);
+		// add the results elements to the root element
+		rootElement.addContent(resultsElement);
+		// debug:
+		// System.out.println("\n Result: " + printResultSet(result));
+	    } else {
+		// create a JDOM element from the exception object with the
+		// results tag
+		Element exceptionElement = new Element(
+			TagNames.Elements.QUERY_RESULTS);
+		// produce xml for the actualException and this to the
+		// exceptionElement
+		if (ex != null) {
+		    exceptionElement.addContent(jstrat.produceMsg(ex, null));
+		}
+		// set the resultsIDAttribute on the exception element
+		exceptionElement.setAttribute(resultsIDAttribute);
+		// add the results elements to the root element
+		rootElement.addContent(exceptionElement);
+
+	    }
+
+	    // Output xml
+	    XMLOutputter outputter = new XMLOutputter(JdomHelper.getFormat(
+		    "  ", true)); //$NON-NLS-1$
+	    outputter.output(new Document(rootElement), outputStream);
+
+	} catch (SQLException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert results to JDOM: " + e.getMessage()); //$NON-NLS-1$
+	} catch (JDOMException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert results to JDOM: " + e.getMessage()); //$NON-NLS-1$
+	} catch (IOException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to output new results to " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+	} catch (Throwable e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert results to JDOM: " + StringUtil.getStackTrace(e)); //$NON-NLS-1$
+	} finally {
+	    try {
+		outputStream.close();
+	    } catch (IOException e) {
+	    }
+	}
+    }
+    
+//  Begin New from Impl
+    
+    
+    public String generateErrorFile_keep(final String querySetID,
+	    final String queryID, final String sql, final ResultSet resultSet,
+	    final Throwable queryError, final Object results)
+	    throws QueryTestFailedException {
+
+	String errorFileName = null;
+	try {
+	    // write actual results to error file
+	    errorFileName = generateErrorFileName(queryID, querySetID);
+	    // configID, queryID, Integer.toString(clientID));
+	    //           CombinedTestClient.log("\t" + this.clientID + ": Writing error file with actual results: " + errorFileName); //$NON-NLS-1$ //$NON-NLS-2$
+	    File errorFile = new File(getOutputDir(), errorFileName);
+	    
+	    // the resultset will be passed in as null when
+	    // the error was due to a thrown exception, and not based comparison issues 
+	    if (resultSet == null) {
+		FileOutputStream actualOut = null;
+		try {
+		    actualOut = new FileOutputStream(errorFile);
+		    PrintStream filePrintStream = new PrintStream(actualOut);
+		    
+
+		    TestResultSetUtil.printThrowable(queryError, sql, filePrintStream);
+		    
+		    filePrintStream.flush();
+
+		} catch (Exception e) {
+			    e.printStackTrace();
+			    throw new QueryTestFailedException(e);
+		} finally {
+		    	if (actualOut != null) {
+				try {
+				    actualOut.close();
+				} catch (IOException e) {
+				    // TODO Auto-generated catch block
+				    e.printStackTrace();
+				}
+			}
+		}
+		return errorFileName;
+
+	    }
+
+	    // rewind resultset
+
+	    resultSet.beforeFirst();
+
+	    generateErrorResults(querySetID, queryID, sql, errorFile,
+		    resultSet, (File) results);
+
+	} catch (Throwable e) {
+	    throw new QueryTestFailedException(e.getMessage());
+	    //           CombinedTestClient.logError("Error writing error file \"" + outputDir + "\"/" + errorFileName + ": " + e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	return errorFileName;
+    }
+
+    
+    /**
+     * Generate an error file for a query that failed comparison. File should
+     * have the SQL, the actual results returned from the server and the results
+     * that were expected.
+     * 
+     * @param queryID
+     * @param sql
+     * @param resultsFile
+     * @param actualResult
+     * @param expectedResultFile
+     * @param ex
+     * @throws QueryTestFailedException
+     */
+    private void generateErrorResults(String querySetID, String queryID,
+	    String sql, File resultsFile, ResultSet actualResult,
+	    File results)
+	    throws QueryTestFailedException {
+	
+	FileOutputStream actualOut = null;
+	try {
+	    actualOut = new FileOutputStream(resultsFile);
+	    PrintStream filePrintStream = new PrintStream(actualOut);
+	    
+	    TestResultSetUtil.printResultSet(actualResult, sql, MAX_COL_WIDTH, true, filePrintStream);
+    	    
+
+	} catch (Exception e) {
+	    e.printStackTrace();
+	    throw new QueryTestFailedException(e);
+	} finally {
+	    if (actualOut != null) {
+		try {
+		    actualOut.close();
+		} catch (IOException e) {
+		    // TODO Auto-generated catch block
+		    e.printStackTrace();
+		}
+	    }
+	}
+    }
+//  End of copy from impl 
+   
+    public String generateErrorFile(final String querySetID,
+	    final String queryID, final String sql, final ResultSet resultSet,
+	    final Throwable queryError, final Object expectedResultsFile)
+	    throws QueryTestFailedException {
+
+	String errorFileName = null;
+	try {
+	    // write actual results to error file
+	    errorFileName = generateErrorFileName(queryID, querySetID);
+	    // configID, queryID, Integer.toString(clientID));
+	    //           CombinedTestClient.log("\t" + this.clientID + ": Writing error file with actual results: " + errorFileName); //$NON-NLS-1$ //$NON-NLS-2$
+	    File errorFile = new File(getOutputDir(), errorFileName);
+
+	    // rewind resultset
+	    if (resultSet != null) {
+		resultSet.beforeFirst();
+	    }
+	    generateErrorResults(querySetID, queryID, sql, errorFile,
+		    resultSet, (File) expectedResultsFile, queryError);
+
+	} catch (Throwable e) {
+	    throw new QueryTestFailedException(e.getMessage());
+	    //           CombinedTestClient.logError("Error writing error file \"" + outputDir + "\"/" + errorFileName + ": " + e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	}
+	return errorFileName;
+    }
+
+    private File createNewResultsFile(String queryID, String querySetID,
+	    String genDir) {
+	String resultFileName = queryID + ".xml"; //$NON-NLS-1$
+
+	String targetDirname = genDir + File.separator + querySetID; //$NON-NLS-1$
+	File targetDir = new File(targetDirname);
+	targetDir.mkdirs();
+
+	return new File(targetDir, resultFileName);
+    }
+
+    //    
+    // private String generateErrorFileName(String queryID,
+    // String querySetID,
+    // String outputdir) {
+    //    	
+    // File resultsFile = createNewResultsFile(queryID, querySetID,
+    // this.outputDir);
+    //    	
+    // // String queryFileName = queryFile.getName();
+    // String name =
+    // FileUtils.getFilenameWithoutExtension(resultsFile.getName());
+    // String errorFileName = "ERROR_"
+    //                                   + name + "_" //$NON-NLS-1$
+    //                                   + FILE_NAME_DATE_FORMATER.format(new Date(System.currentTimeMillis())) + ".xml"; //$NON-NLS-1$
+    // return errorFileName;
+    //  	
+    // }
+
+    private String generateErrorFileName(String queryID, String querySetID) {
+//	String errorFileName = "ERROR_"
+		// configID + "_" //$NON-NLS-1$ //$NON-NLS-2$
+		//                               + querySetID + "_" //$NON-NLS-1$
+//	    String errorFileName = queryID +
+//		+ "_" //$NON-NLS-1$
+//		+ FILE_NAME_DATE_FORMATER.format(new Date(System
+//			.currentTimeMillis())) + ".xml"; //$NON-NLS-1$
+//	return errorFileName;
+	
+	return  queryID + ".err";
+    }
+
+    /**
+     * Generate an error file for a query that failed comparison. File should
+     * have the SQL, the actual results returned from the server and the results
+     * that were expected.
+     * 
+     * @param queryID
+     * @param sql
+     * @param resultsFile
+     * @param actualResult
+     * @param expectedResultFile
+     * @param ex
+     * @throws QueryTestFailedException
+     */
+    private void generateErrorResults(String querySetID, String queryID,
+	    String sql, File resultsFile, ResultSet actualResult,
+	    File expectedResultFile, Throwable ex)
+	    throws QueryTestFailedException {
+	OutputStream outputStream;
+	try {
+	    FileOutputStream fos = new FileOutputStream(resultsFile);
+	    outputStream = new BufferedOutputStream(fos);
+	} catch (IOException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to open error results file: " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+	}
+
+	try {
+	    XMLQueryVisitationStrategy jstrat = new XMLQueryVisitationStrategy();
+
+	    // Create root JDOM element
+	    Element rootElement = new Element(TagNames.Elements.ROOT_ELEMENT);
+
+	    // create a JDOM element for the results
+	    Element resultElement = new Element(TagNames.Elements.QUERY_RESULTS);
+	    // set the queryIDAttr on the exception element
+	    resultElement.setAttribute(new Attribute(TagNames.Attributes.NAME,
+		    queryID));
+	    // set the querySQLAttr on the exception element
+	    resultElement.setAttribute(new Attribute(TagNames.Attributes.VALUE,
+		    sql));
+
+	    // ---------------------
+	    // Actual Exception
+	    // ---------------------
+	    // create a JDOM element from the actual exception object
+	    // produce xml for the actualException and this to the
+	    // exceptionElement
+	    if (ex != null) {
+		Element actualExceptionElement = new Element(
+			TagNames.Elements.ACTUAL_EXCEPTION);
+
+		actualExceptionElement = XMLQueryVisitationStrategy
+			.jdomException(ex, actualExceptionElement);
+		resultElement.addContent(actualExceptionElement);
+	    }
+
+	    if (actualResult != null) {
+		// ------------------------------
+		// Got a ResultSet from server
+		// error was in comparing results
+		// ------------------------------
+
+		// --------------------------
+		// Actual Result - ResultSet
+		// --------------------------
+		// produce a JDOM element from the actual results object
+		Element actualResultsElement = new Element(
+			TagNames.Elements.ACTUAL_QUERY_RESULTS);
+		actualResultsElement = jstrat.produceMsg(actualResult,
+			actualResultsElement);
+
+		// add the results elements to the root element
+		resultElement.addContent(actualResultsElement);
+
+		// ---------------------
+		// Expected Results - ...
+		// ---------------------
+		// produce xml for the expected results
+		// Get expected results
+		Element expectedResult = new Element("bogus"); //$NON-NLS-1$
+		expectedResult = jstrat.parseXMLResultsFile(expectedResultFile,
+			expectedResult);
+		if (expectedResult.getChild(TagNames.Elements.SELECT) != null) {
+		    //----------------------------------------------------------
+		    // -
+		    // Expected result was a ResultSet set element name to
+		    // reflect
+		    //----------------------------------------------------------
+		    // -
+		    expectedResult
+			    .setName(TagNames.Elements.EXPECTED_QUERY_RESULTS);
+		} else {
+		    //----------------------------------------------------------
+		    // --
+		    // Expected result was an exception set element name to
+		    // reflect
+		    //----------------------------------------------------------
+		    // --
+		    expectedResult
+			    .setName(TagNames.Elements.EXPECTED_EXCEPTION);
+		}
+		resultElement.addContent(expectedResult);
+	    } else {
+
+		// ---------------------
+		// Expected Results - ...
+		// ---------------------
+		// produce xml for the expected results
+		// Get expected results
+		Element expectedResult = new Element("bogus"); //$NON-NLS-1$
+		expectedResult = jstrat.parseXMLResultsFile(expectedResultFile,
+			expectedResult);
+		if (expectedResult.getChild(TagNames.Elements.SELECT) != null) {
+		    //----------------------------------------------------------
+		    // -
+		    // Expected result was a ResultSet set element name to
+		    // reflect
+		    //----------------------------------------------------------
+		    // -
+		    expectedResult
+			    .setName(TagNames.Elements.EXPECTED_QUERY_RESULTS);
+		} else {
+		    //----------------------------------------------------------
+		    // --
+		    // Expected result was an exception set element name to
+		    // reflect
+		    //----------------------------------------------------------
+		    // --
+		    expectedResult
+			    .setName(TagNames.Elements.EXPECTED_EXCEPTION);
+		}
+		resultElement.addContent(expectedResult);
+	    }
+
+	    // ------------------------------
+	    // Got an exeption from the server
+	    // error was in comparing exceptions
+	    // ------------------------------
+
+	    // add the results elements to the root element
+	    rootElement.addContent(resultElement);
+
+	    // Output xml
+	    XMLOutputter outputter = new XMLOutputter(JdomHelper.getFormat(
+		    "  ", true)); //$NON-NLS-1$
+	    outputter.output(new Document(rootElement), outputStream);
+
+	} catch (SQLException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert error results to JDOM: " + e.getMessage()); //$NON-NLS-1$
+	} catch (JDOMException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert error results to JDOM: " + e.getMessage()); //$NON-NLS-1$
+	} catch (IOException e) {
+	    throw new QueryTestFailedException(
+		    "Failed to output error results to " + resultsFile.getPath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+	} catch (Throwable e) {
+	    throw new QueryTestFailedException(
+		    "Failed to convert error results to JDOM: " + StringUtil.getStackTrace(e)); //$NON-NLS-1$
+	} finally {
+	    try {
+		outputStream.close();
+	    } catch (IOException e) {
+	    }
+	}
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,1677 +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.test.client.ctc;
-
-import java.io.File;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.sql.Blob;
-import java.sql.Clob;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.SQLXML;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.jdom.Attribute;
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.JDOMException;
-import org.jdom.input.SAXBuilder;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.internal.core.xml.SAXBuilderHelper;
-import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.test.client.QuerySQL;
-import org.teiid.test.client.QueryTest;
-import org.teiid.test.client.ctc.QueryResults.ColumnInfo;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.util.StringUtil;
-
-
-
-/**
- * <P> This program helps in parsing XML Query and Results files into
- * map objects containing individual queries/ResultSets</P>
- *
- * <P> This program is useful to convert the JDBC ResultSet objects into
- * XML format. We physically walk through the ResultSet object and use JDOM to
- * convert the ResultSets into XML. This also helps convert Exceptions into XML
- * format.</P>
- */
-
-public class XMLQueryVisitationStrategy {
-
-    //the row from which we start converting ResultSets to XML
-    private static final int START_ROW = 1;
-
-    // list containing datatypes of field identifiers
-
-    public XMLQueryVisitationStrategy() {
-    }
-
-    /**
-     * Consume an XML Query File and produce a Map containing queries, with
-     * queryNames/IDs as Keys.
-     * <br>
-     * @param queryFile the XML file object that is to be parsed
-     * @return the List containing quers.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    public List parseXMLQueryFile(String queryScenarioID, File queryFile, String querySetID) throws IOException, JDOMException {
-
-	List<QueryTest> queries = new LinkedList();
-//        HashMap queryMap = new HashMap();
-        SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
-        Document queryDocument = builder.build(queryFile);
-        List queryElements = queryDocument.getRootElement().getChildren(TagNames.Elements.QUERY);
-        Iterator iter = queryElements.iterator();
-        while ( iter.hasNext() ) {
-            Element queryElement = (Element) iter.next();
-            String queryName = queryElement.getAttributeValue(TagNames.Attributes.NAME);
-            if ( queryElement.getChild(TagNames.Elements.EXCEPTION) == null ) {
-        	String uniqueID = querySetID + "_" + queryName;
-        	
-		List<Element> parmChildren = queryElement.getChildren(TagNames.Elements.SQL);
-        	
-		if (parmChildren == null || parmChildren.isEmpty()) {
-        	    TestLogger.logDebug("=======  Single QueryTest ");
-        	    QuerySQL sql = createQuerySQL(queryElement);
-         	    
-        	    QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, new QuerySQL[] {sql}, false);
-        	    queries.add(q);
-        	} else {
-        	    TestLogger.logDebug("=======  QueryTest has multiple sql statements");
-         		QuerySQL[] querysql = new QuerySQL[parmChildren.size()];
-        		int c = 0;
-        		
-        		final Iterator<Element> sqliter = parmChildren.iterator();
-        		while ( sqliter.hasNext() ) {
-        			final Element sqlElement = (Element) sqliter.next();
-        			QuerySQL sql = createQuerySQL(sqlElement);
-        			querysql[c] = sql;
-        			c++;	
-        		}
-        		QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, querysql, false);
-        		queries.add(q);
-               		
-        		
-       	    
-        	}
- //               queryMap.put(queryName, query);
-            } else {
-                Element exceptionElement = queryElement.getChild(TagNames.Elements.EXCEPTION);
-                String exceptionType = exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim();
-                
-                String uniqueID = querySetID + "_" + queryName;
-                QuerySQL sql = new QuerySQL(exceptionType, null);
-                
-                QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, new QuerySQL[] {sql}, true);
-                queries.add(q);
-
-                
- //               queryMap.put(queryName, exceptionType);
-            }
-        }
-        return queries;
-    }
-    
-    private QuerySQL createQuerySQL(Element queryElement) {
- 	    String query = queryElement.getTextTrim();
- 	    	    
-	    Object[] parms = getParms(queryElement);
-	    	    
-	    QuerySQL sql = new QuerySQL(query, parms);
-	    
- 	    String updateCnt = queryElement.getAttributeValue(TagNames.Attributes.UPDATE_CNT);
- 	    if (updateCnt != null && updateCnt.trim().length() > 0) {
- 		int cnt = Integer.parseInt(updateCnt);
- 		sql.setUpdateCnt(cnt);
- 	    }
- 	    
- 	    String rowCnt = queryElement.getAttributeValue(TagNames.Attributes.TABLE_ROW_COUNT);
- 	    if (rowCnt != null && rowCnt.trim().length() > 0) {
- 		int cnt = Integer.parseInt(rowCnt);
- 		sql.setRowCnt(cnt);
- 	    }
-	    
-	    return sql;	
-    }
-    
-    private Object[] getParms(Element parent) {
-	List<Element> parmChildren = parent.getChildren(TagNames.Elements.PARM);
-	if (parmChildren == null) {
-	    return null;
-	}
-	
-	Object[] parms = new Object[parmChildren.size()];
-	int i = 0;
-	final Iterator<Element> iter = parmChildren.iterator();
-	while ( iter.hasNext() ) {
-		final Element parmElement = (Element) iter.next();
-		try {
-		    Object parm = createParmType(parmElement);
-		    parms[i] = parm;
-		    i++;
-		} catch (JDOMException e) {
-		    throw new TransactionRuntimeException(e);
-		}		
-	}
-	
-	
-	
-	return parms;
-    }
-    
-    private Object createParmType(Element cellElement) throws JDOMException {
-
-        Object cellObject = null;
-        
-        final String typeName = cellElement.getAttributeValue(TagNames.Attributes.TYPE);
- 
-        if ( typeName.equalsIgnoreCase(TagNames.Elements.BOOLEAN) ) {
-            cellObject = consumeMsg((Boolean) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.STRING) ) {
-            cellObject = consumeMsg((String) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.CHAR) ) {
-            cellObject = consumeMsg((Character) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BYTE) ) {
-            cellObject = consumeMsg((Byte) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.DOUBLE) ) {
-            cellObject = consumeMsg((Double) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.DATE) ) {
-            cellObject = consumeMsg((java.sql.Date) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.TIME) ) {
-            cellObject = consumeMsg((Time) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.TIMESTAMP) ) {
-            cellObject = consumeMsg((Timestamp) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.FLOAT) ) {
-            cellObject = consumeMsg((Float) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BIGDECIMAL) ) {
-            cellObject = consumeMsg((BigDecimal) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BIGINTEGER) ) {
-            cellObject = consumeMsg((BigInteger) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.INTEGER) ) {
-            cellObject = consumeMsg((Integer) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.LONG) ) {
-            cellObject = consumeMsg((Long) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.SHORT) ) {
-            cellObject = consumeMsg((Short) cellObject, cellElement);
-        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.OBJECT) ) {
-            cellObject = consumeMsg((String) cellObject, cellElement);
-        }
-
-        return cellObject;
-    }
-
-    /**
-     * Consume an XML results File and produce a Map containing query results
-     * as List objects, with resultNames/IDs as Keys.
-     * <br>
-     * @param resultsFile the XML file object that is to be parsed
-     * @return the Map containig results.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    public ResultsHolder parseXMLResultsFile(final File resultsFile) throws IOException, JDOMException {
-
-        QueryResults queryResults;
-        ResultsHolder expectedResults = null;
-
-        final SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
-        final Document resultsDocument = builder.build(resultsFile);
-        final String query = resultsDocument.getRootElement().getChildText(TagNames.Elements.QUERY);
-        final List resultElements = resultsDocument.getRootElement().getChildren(TagNames.Elements.QUERY_RESULTS);
-        final Iterator iter = resultElements.iterator();
-        while ( iter.hasNext() ) {
-            final Element resultElement = (Element) iter.next();
-            final String resultName = resultElement.getAttributeValue(TagNames.Attributes.NAME);
-            queryResults = consumeMsg(new QueryResults(), resultElement);
-            if ( queryResults.getFieldCount() != 0 ) {
-                //
-                // We've got a ResultSet
-                //
-                expectedResults = new ResultsHolder( TagNames.Elements.QUERY_RESULTS );
-                expectedResults.setQueryID( resultName );
-                expectedResults.setQuery(query);
-                expectedResults.setIdentifiers( queryResults.getFieldIdents() );
-                expectedResults.setTypes( queryResults.getTypes() );
-                if ( queryResults.getRecordCount() > 0 ) {
-                    expectedResults.setRows(queryResults.getRecords());
-                }
-            } else {
-                //
-                // We've got an exception
-                //
-                expectedResults = new ResultsHolder( TagNames.Elements.EXCEPTION );
-                expectedResults.setQueryID( resultName );
-                expectedResults.setQuery(query);
-
-                final Element exceptionElement = resultElement.getChild(TagNames.Elements.EXCEPTION);
-                if ( exceptionElement != null ) {
-                    expectedResults.setExceptionClassName(exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim());
-                    String msg = exceptionElement.getChild(TagNames.Elements.MESSAGE).getTextTrim();   
-                    expectedResults.setExceptionMsg(StringUtil.removeChars(msg, new char[] {'\r'}));
-                }
-            }
-        }
-        return expectedResults;
-    }
-
-    /**
-     * Consume an XML results File, produce results as JDOM and add results to the given parent.
-     * <br>
-     * @param resultsFile the XML file object that is to be parsed
-     * @param parent the parent Element to assign results to
-     * @return the modified parent
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    public Element parseXMLResultsFile(File resultsFile, Element parent) throws IOException, JDOMException {
-
-        SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
-        Document resultsDocument = builder.build(resultsFile);
-        List resultElements = resultsDocument.getRootElement().getChildren(TagNames.Elements.QUERY_RESULTS);
-        Iterator iter = resultElements.iterator();
-        while ( iter.hasNext() ) {
-            Element resultElement = (Element) iter.next();
-            if ( resultElement.getChild(TagNames.Elements.SELECT) == null ) {
-                // We've got an exception
-                Element exceptionElement = resultElement.getChild(TagNames.Elements.EXCEPTION);
-                if ( exceptionElement != null ) {
-                    // ---------------------------------
-                    // Add the ExceptionType element ...
-                    // ---------------------------------
-                    Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
-                    typeElement.setText(exceptionElement.getChild(TagNames.Elements.EXCEPTION_TYPE).getTextTrim());
-                    parent.addContent(typeElement);
-
-                    // ---------------------------
-                    // Add the Message element ...
-                    // ---------------------------
-                    Element messageElement = new Element(TagNames.Elements.MESSAGE);    
-                    String msg = exceptionElement.getChild(TagNames.Elements.MESSAGE).getTextTrim();   
-                    
-                    messageElement.setText(StringUtil.removeChars(msg, new char[] {'\r'}));
-                    parent.addContent(messageElement);
-
-                    // -------------------------
-                    // Add the Class element ...
-                    // -------------------------
-                    Element classElement = new Element(TagNames.Elements.CLASS);
-                    classElement.setText(exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim());
-                    parent.addContent(classElement);
-                }
-            } else {
-                // We've got results
-
-                // -------------------------------
-                // Read the SELECT elements
-                // -------------------------------
-                Element selectElement = resultElement.getChild(TagNames.Elements.SELECT);
-                resultElement.removeChild(TagNames.Elements.SELECT);
-                parent.addContent(selectElement);
-
-                // -------------------------------
-                // Read the TABLE of data
-                // -------------------------------
-                Element tableElement = resultElement.getChild(TagNames.Elements.TABLE);
-                resultElement.removeChild(TagNames.Elements.TABLE);
-                parent.addContent(tableElement);
-            }
-        }
-        return parent;
-    }
-
-    /*********************************************************************************************
-     *********************************************************************************************
-     CONSUME METHODS
-     *********************************************************************************************
-     ********************************************************************************************/
-
-    /**
-     * Generate XML for an exception in Object form.
-     *
-     * @param ex
-     * @param exceptionElement
-     * @return The JDOM exception element.
-     */
-    public static Element jdomException(Throwable ex, Element exceptionElement) {
-        // ---------------------------------
-        // Add the ExceptionType element ...
-        // ---------------------------------
-        String className = ex.getClass().getName();
-        int index = className.lastIndexOf('.');
-        if ( index != -1 && (++index) < className.length() ) {
-            className = className.substring(index);
-        }
-        Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
-        typeElement.setText(className);
-        exceptionElement.addContent(typeElement);
-
-        // ---------------------------
-        // Add the Message element ...
-        // ---------------------------
- 
-        Element messageElement = new Element(TagNames.Elements.MESSAGE);
-        messageElement.setText(StringUtil.removeChars(ex.getMessage(), new char[] {'\r'}));     
-        		
-        exceptionElement.addContent(messageElement);
-
-        // -------------------------
-        // Add the Class element ...
-        // -------------------------
-        Element classElement = new Element(TagNames.Elements.CLASS);
-        classElement.setText(ex.getClass().getName());
-        exceptionElement.addContent(classElement);
-
-        return exceptionElement;
-    }
-
-    /**
-     * Consume an XML message and update the specified QueryResults instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param resultsElement the XML element that contains the data
-     * @return the updated instance.
-     */
-    private QueryResults consumeMsg(QueryResults object, Element resultsElement) throws JDOMException {
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        QueryResults results = object;
-        if ( results == null ) {
-            results = new QueryResults();
-        }
-
-        if ( resultsElement.getChild(TagNames.Elements.SELECT) == null ) {
-            return results;
-        }
-        // -------------------------------
-        // Read the SELECT elements
-        // -------------------------------
-        Element selectElement = resultsElement.getChild(TagNames.Elements.SELECT);
-        Select select = new Select();
-        select = consumeMsg(select, selectElement);
-
-        List listOfElementSymbols = select.getSymbols();
-        Iterator elementSymbolItr = listOfElementSymbols.iterator();
-        Collection collectionOfColumnInfos = new ArrayList();
-        while ( elementSymbolItr.hasNext() ) {
-            ElementSymbol elementSymbol = (ElementSymbol) elementSymbolItr.next();
-            Class elementType = elementSymbol.getType();
-            String dataType = DataTypeManager.getDataTypeName(elementType);
-            ColumnInfo columnInfo = new ColumnInfo(elementSymbol.getName(), dataType, elementType);
-            collectionOfColumnInfos.add(columnInfo);
-        }
-        // Save column info
-        results.addFields(collectionOfColumnInfos);
-        // -------------------------------
-        // Read the TABLE of data
-        // -------------------------------
-
-        Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
-        List tableRows = tableElement.getChildren(TagNames.Elements.TABLE_ROW);
-        if ( tableRows.size() > 0 ) {
-            Iterator rowIter = tableRows.iterator();
-
-            while ( rowIter.hasNext() ) {
-                Element rowElement = (Element) rowIter.next();
-                List cellElements = rowElement.getChildren(TagNames.Elements.TABLE_CELL);
-                Iterator cellIter = cellElements.iterator();
-                // Read cells of the table
-                ArrayList row = new ArrayList();
-                Object evalue = null;
-                while ( cellIter.hasNext() ) {
-                    Element cellElement = (Element) cellIter.next();
-                    if ( cellElement.getTextTrim().equalsIgnoreCase(TagNames.Elements.NULL) ) {
-                        row.add(null);
-                    } else {
-                        Element cellChildElement = (Element) cellElement.getChildren().get(0);
-                        evalue = consumeMsg(cellChildElement);
-                        row.add(evalue);
-                    }
-                }
-                // Save row
-                results.addRecord(row);
-            }
-        }
-        return results;
-    }
-
-    /**
-     * Consume an XML message and update the specified Select instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param selectElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Select consumeMsg(Select object, Element selectElement) throws JDOMException {
-
-        Select select = (object != null) ? (Select) object : new Select();
-        // --------------------------------
-        // Read the DISTINCT attribute
-        // --------------------------------
-
-        String distinct = selectElement.getAttributeValue(TagNames.Attributes.DISTINCT);
-        if ( distinct != null ) {
-            if ( distinct.equalsIgnoreCase("true") ) { //$NON-NLS-1$
-                select.setDistinct(true);
-            }
-        }
-
-        // --------------------------------
-        // Read the STAR attribute
-        // --------------------------------
-
-        String star = selectElement.getAttributeValue(TagNames.Attributes.STAR);
-        if ( star != null ) {
-            if ( star.equalsIgnoreCase("true") ) { //$NON-NLS-1$
-                if ( selectElement.getChildren() != null ) {
-                    throw new JDOMException("No children expected when star is chosen."); //$NON-NLS-1$
-                }
-                return select;
-            }
-        }
-
-        // --------------------------------
-        // Read the IDENTIFIER elements ...
-        // --------------------------------
-        List idents = selectElement.getChildren();
-        Iterator identIter = idents.iterator();
-        while ( identIter.hasNext() ) {
-            Element dataElement = (Element) identIter.next();
-            Attribute dataType = dataElement.getAttribute(TagNames.Attributes.TYPE);
-            // add the dataType of the element to the list containing dataTypes
-            ElementSymbol nodeID = new ElementSymbol(dataElement.getText());
-            Class nodeType = (Class) TagNames.TYPE_MAP.get(dataType.getValue());
-            if (nodeType == null)  {
-                throw new JDOMException("Unknown class for type \"" + dataType.getValue() + "\"."); //$NON-NLS-1$ //$NON-NLS-2$
-            }
-            nodeID.setType(nodeType);
-            select.addSymbol(nodeID);
-        }
-
-        return select;
-    }
-
-
-    /**
-     * Produce a JDOM Element for the instance of any Object.
-     * <br>
-     * @param cellElement the XML element that is to produce the XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing XML.
-     */
-    private Object consumeMsg(Element cellElement) throws JDOMException {
-
-        Object cellObject = null;
-        String cellName = cellElement.getName();
-
-        if ( cellName.equalsIgnoreCase(TagNames.Elements.BOOLEAN) ) {
-            cellObject = consumeMsg((Boolean) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.STRING) ) {
-            cellObject = consumeMsg((String) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.CHAR) ) {
-            cellObject = consumeMsg((Character) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BYTE) ) {
-            cellObject = consumeMsg((Byte) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.DOUBLE) ) {
-            cellObject = consumeMsg((Double) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.DATE) ) {
-            cellObject = consumeMsg((java.sql.Date) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.TIME) ) {
-            cellObject = consumeMsg((Time) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.TIMESTAMP) ) {
-            cellObject = consumeMsg((Timestamp) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.FLOAT) ) {
-            cellObject = consumeMsg((Float) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BIGDECIMAL) ) {
-            cellObject = consumeMsg((BigDecimal) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BIGINTEGER) ) {
-            cellObject = consumeMsg((BigInteger) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.INTEGER) ) {
-            cellObject = consumeMsg((Integer) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.LONG) ) {
-            cellObject = consumeMsg((Long) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.SHORT) ) {
-            cellObject = consumeMsg((Short) cellObject, cellElement);
-        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.OBJECT) ) {
-            cellObject = consumeMsg((String) cellObject, cellElement);
-        }
-
-        return cellObject;
-    }
-
-    /**
-     * Consume an XML message and update the specified Boolean instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Boolean object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        boolean result = false;
-        String value = cellElement.getTextTrim();
-        if ( value.equalsIgnoreCase(TagNames.Values.TRUE) ) {
-            result = true;
-        } else if ( value.equalsIgnoreCase(TagNames.Values.FALSE) ) {
-            result = false;
-        } else {
-            throw new JDOMException("Invalid value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: \"" + value + "\" must be either \"" + //$NON-NLS-1$ //$NON-NLS-2$
-                                    TagNames.Values.TRUE + "\" or \"" + //$NON-NLS-1$
-                                    TagNames.Values.FALSE + "\""); //$NON-NLS-1$
-        }
-
-        return new Boolean(result);
-    }
-
-    /**
-     * Consume an XML message and update the specified java.sql.Date instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(java.sql.Date object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        java.sql.Date result;
-        try {
-            result = java.sql.Date.valueOf(cellElement.getTextTrim());
-        } catch ( Exception e ) {
-            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Time instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Time object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Time result;
-        try {
-            result = Time.valueOf(cellElement.getTextTrim());
-        } catch ( Exception e ) {
-            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Timestamp instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Timestamp object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Timestamp result;
-        try {
-            result = Timestamp.valueOf(cellElement.getTextTrim());
-        } catch ( Exception e ) {
-            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
-        }
-
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Double instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Double object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        String strElement = cellElement.getTextTrim();
-        Double result;
-
-        if ( strElement.equals("NaN") ) { //$NON-NLS-1$
-            result = new Double(Double.NaN);
-        } else if ( strElement.equals("-Infinity") ) { //$NON-NLS-1$
-            result = new Double(Double.NEGATIVE_INFINITY);
-        } else if ( strElement.equals("Infinity") ) { //$NON-NLS-1$
-            result = new Double(Double.POSITIVE_INFINITY);
-        } else {
-            try {
-                result = Double.valueOf(strElement);
-            } catch ( NumberFormatException e ) {
-                throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                        " element: " + strElement, e); //$NON-NLS-1$
-            }
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Float instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Float object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        String strElement = cellElement.getTextTrim();
-        Float result;
-
-        if ( strElement.equals("NaN") ) { //$NON-NLS-1$
-            result = new Float(Float.NaN);
-        } else if ( strElement.equals("-Infinity") ) { //$NON-NLS-1$
-            result = new Float(Float.NEGATIVE_INFINITY);
-        } else if ( strElement.equals("Infinity") ) { //$NON-NLS-1$
-            result = new Float(Float.POSITIVE_INFINITY);
-        } else {
-            try {
-                result = Float.valueOf(strElement);
-            } catch ( NumberFormatException e ) {
-                throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                        " element: " + strElement, e); //$NON-NLS-1$
-            }
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified BigDecimal instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(BigDecimal object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        BigDecimal result;
-        try {
-            result = new BigDecimal(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified BigInteger instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(BigInteger object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        BigInteger result;
-        try {
-            result = new BigInteger(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified String instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(String object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-
-        return cellElement.getText();
-    }
-
-    /**
-     * Consume an XML message and update the specified Character instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Character object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Character result;
-        try {
-            if ( cellElement.getTextTrim().length() == 0 ) {
-                return null;
-            }
-            result = new Character(cellElement.getTextTrim().charAt(0));
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Byte instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Byte object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Byte result;
-        try {
-            result = new Byte(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Integer instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Integer object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Integer result;
-        try {
-            result = Integer.valueOf(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Long instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Long object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Long result;
-        try {
-            result = Long.valueOf(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /**
-     * Consume an XML message and update the specified Long instance.
-     * <br>
-     * @param object the instance that is to be updated with the XML message data.
-     * @param cellElement the XML element that contains the data
-     * @return the updated instance.
-     * @exception JDOMException if there is an error consuming the message.
-     */
-    private Object consumeMsg(Short object, Element cellElement) throws JDOMException {
-
-        // -----------------------
-        // Process the element ...
-        // -----------------------
-        Short result;
-        try {
-            result = Short.valueOf(cellElement.getTextTrim());
-        } catch ( NumberFormatException e ) {
-            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
-                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
-        }
-        return result;
-    }
-
-    /*********************************************************************************************
-     *********************************************************************************************
-     PRODUCE METHODS
-     *********************************************************************************************
-     ********************************************************************************************/
-
-    /**
-     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
-     * <br>
-     * @param object for which the JDOM Element is to be produced.
-     * @return the JDOM element of the ResultSet object that was converted to XML.
-     * @exception JDOMException if there is an error producing XML.
-     * @exception JDOMException if there is an error producing XML.
-     * @exception SQLException if there is an error walking through the ResultSet object.
-     */
-    public Element produceResults(ResultSet object) throws JDOMException, SQLException {
-
-        // When no begin and end
-        return produceResults(object, START_ROW, Integer.MAX_VALUE);
-    }
-
-    /**
-     * Produce a JDOM Element for an instance of Results object.
-     * <br>
-     * @param object for which the JDOM Element is to be produced.
-     * @param beginRow The starting row from which the results are to be converted to XML.
-     * @param endRow The row until which the results are to be converted to XML.
-     * @return the JDOM element of the results object that was converted to XML.
-     * @exception JDOMException if there is an error producing XML.
-     * @exception SQLException if there is an error walking through the ResultSet object.
-     */
-    private Element produceResults(ResultSet object, int beginRow, int endRow)
-            throws JDOMException, SQLException {
-
-    	if (object.isClosed()) {
-            throw new SQLException(
-            "ResultSet is closed at this point, unable to product results"); //$NON-NLS-1$
-    		
-    	}
-    	
-        if ( beginRow < START_ROW ) {
-            throw new IllegalArgumentException(
-                    "The starting row cannot be less than 1."); //$NON-NLS-1$
-        } else if ( beginRow > endRow ) {
-            throw new IllegalArgumentException(
-                    "The starting row cannot be less than the ending row."); //$NON-NLS-1$
-        }
-
-        int currentRow = object.getRow() + 1;
-
-        if ( beginRow > currentRow ) {
-            while ( !object.isLast() && currentRow != beginRow ) {
-                object.next();
-                currentRow++;
-            }
-
-        } else if ( beginRow < currentRow ) {
-            while ( !object.isFirst() && currentRow != beginRow ) {
-                object.previous();
-                currentRow--;
-            }
-        }
-
-        return produceMsg(object, endRow);
-    }
-
-    /**
-     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
-     * <br>
-     * @param object for which the JDOM Element is to be produced.
-     * @param endRow The row until which the results are to be converted to XML.
-     * @return the JDOM element of the results object that was converted to XML.
-     * @exception JDOMException if there is an error producing XML.
-     * @exception SQLException if there is an error walking through the ResultSet object.
-     */
-    private Element produceMsg(ResultSet object, int endRow) throws JDOMException, SQLException {
-
-        // -----------------------------------
-        // Create the QueryResults element ...
-        // -----------------------------------
-        Element resultsElement = new Element(TagNames.Elements.QUERY_RESULTS);
-
-        // -----------------------------------
-        // Add the Select (header) element ...
-        // -----------------------------------
-        try {
-            ResultSetMetaData rmdata = object.getMetaData();
-            List identList = new ArrayList(rmdata.getColumnCount());
-            for ( int i = 1; i <= rmdata.getColumnCount(); i++ ) {
-                identList.add(new ElementSymbol(rmdata.getColumnName(i)));
-            }
-            Select select = new Select(identList);
-            resultsElement = produceMsg(select, rmdata, resultsElement);
-
-            // -------------------------
-            // Add the Table element ...
-            // -------------------------
-            resultsElement.addContent(new Element(TagNames.Elements.TABLE));
-            Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
-            int rowCount = 0;
-            int colCount = rmdata.getColumnCount();
-
-            while ( object.next() && (object.getRow() <= endRow) ) {
-
-                // -------------------------
-                // Add the ROW element ...
-                // -------------------------
-                Element rowElement = new Element(TagNames.Elements.TABLE_ROW);
-
-                for ( int i = 1; i <= colCount; i++ ) {
-                    // -------------------------
-                    // Add the Cell element ...
-                    // -------------------------
-                    Element cellElement = new Element(TagNames.Elements.TABLE_CELL);
-                    Object cellValue = object.getObject(i);
-                    if ( cellValue != null ) {
-                        cellElement = produceMsg(cellValue, cellElement);
-                    } else {
-                        cellElement = cellElement.addContent(TagNames.Elements.NULL);
-                    }
-                    rowElement.addContent(cellElement);
-                }
-                tableElement.addContent(rowElement);
-                rowCount++;
-            }
-            Attribute rowCountAttribute = new Attribute(TagNames.Attributes.TABLE_ROW_COUNT,
-                                                        Integer.toString(rowCount));
-            Attribute columnCountAttribute = new Attribute(TagNames.Attributes.TABLE_COLUMN_COUNT,
-                                                           Integer.toString(colCount));
-            tableElement.setAttribute(rowCountAttribute);
-            tableElement.setAttribute(columnCountAttribute);
-        } catch ( SQLException e ) {
-            // error while reading results
-            throw(e);
-        }
-
-        return resultsElement;
-    }
-
-    /**
-     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
-     * <br>
-     * @param object for which the JDOM Element is to be produced.
-     * @return the JDOM element of the results object that was converted to XML.
-     * @exception JDOMException if there is an error producing XML.
-     * @exception SQLException if there is an error walking through the ResultSet object.
-     */
-    public Element produceMsg(ResultSet object, Element resultsElement) throws JDOMException, SQLException {
-
-        // -----------------------------------
-        // Add the Select (header) element ...
-        // -----------------------------------
-        try {
-            ResultSetMetaData rmdata = object.getMetaData();
-            List identList = new ArrayList(rmdata.getColumnCount());
-            for ( int i = 1; i <= rmdata.getColumnCount(); i++ ) {
-                identList.add(new ElementSymbol(rmdata.getColumnName(i)));
-            }
-            Select select = new Select(identList);
-            resultsElement = produceMsg(select, rmdata, resultsElement);
-
-            // -------------------------
-            // Add the Table element ...
-            // -------------------------
-            resultsElement.addContent(new Element(TagNames.Elements.TABLE));
-            Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
-            int rowCount = 0;
-            int colCount = rmdata.getColumnCount();
-
-            while ( object.next() ) {
-
-                // -------------------------
-                // Add the ROW element ...
-                // -------------------------
-                Element rowElement = new Element(TagNames.Elements.TABLE_ROW);
-
-                for ( int i = 1; i <= colCount; i++ ) {
-                    // -------------------------
-                    // Add the Cell element ...
-                    // -------------------------
-                    Element cellElement = new Element(TagNames.Elements.TABLE_CELL);
-                    Object cellValue = object.getObject(i);
-                    if ( cellValue != null ) {
-                        cellElement = produceMsg(cellValue, cellElement);
-                    } else {
-                        cellElement = cellElement.addContent(TagNames.Elements.NULL);
-                    }
-                    rowElement.addContent(cellElement);
-                }
-                tableElement.addContent(rowElement);
-                rowCount++;
-            }
-            Attribute rowCountAttribute = new Attribute(TagNames.Attributes.TABLE_ROW_COUNT,
-                                                        Integer.toString(rowCount));
-            Attribute columnCountAttribute = new Attribute(TagNames.Attributes.TABLE_COLUMN_COUNT,
-                                                           Integer.toString(colCount));
-            tableElement.setAttribute(rowCountAttribute);
-            tableElement.setAttribute(columnCountAttribute);
-        } catch ( SQLException e ) {
-            // error while reading results
-            throw(e);
-        }
-
-        return resultsElement;
-    }
-
-    /**
-     * Produce a JDOM Element for the instance of any Object.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing XML.
-     */
-    public Element produceMsg(Object object, Element parent) throws JDOMException, SQLException {
-        if ( object == null ) {
-            throw new IllegalArgumentException("Null object reference."); //$NON-NLS-1$
-        }
-        Element element = null;
-
-        if ( object instanceof Boolean ) {
-            element = produceMsg((Boolean) object, parent);
-        } else if ( object instanceof String ) {
-            element = produceMsg((String) object, parent);
-        } else if ( object instanceof Character ) {
-            element = produceMsg((Character) object, parent);
-        } else if ( object instanceof Byte ) {
-            element = produceMsg((Byte) object, parent);
-        } else if ( object instanceof Double ) {
-            element = produceMsg((Double) object, parent);
-        } else if ( object instanceof java.sql.Date ) {
-            element = produceMsg((java.sql.Date) object, parent);
-        } else if ( object instanceof Time ) {
-            element = produceMsg((Time) object, parent);
-        } else if ( object instanceof Timestamp ) {
-            element = produceMsg((Timestamp) object, parent);
-        } else if ( object instanceof Float ) {
-            element = produceMsg((Float) object, parent);
-        } else if ( object instanceof BigDecimal ) {
-            element = produceMsg((BigDecimal) object, parent);
-        } else if ( object instanceof BigInteger ) {
-            element = produceMsg((BigInteger) object, parent);
-        } else if ( object instanceof Integer ) {
-            element = produceMsg((Integer) object, parent);
-        } else if ( object instanceof Long ) {
-            element = produceMsg((Long) object, parent);
-        } else if ( object instanceof Short ) {
-            element = produceMsg((Short) object, parent);
-        } else if ( object instanceof Throwable ) {
-            element = produceMsg((Throwable) object, parent);
-        } else {
-            element = produceObject(object, parent);
-        }
-
-        return element;
-    }
-
-    /**
-     * new ----
-     * @param select
-     * @param rmdata
-     * @param parent
-     * @return
-     * @throws JDOMException
-     */
-    private Element produceMsg(Select select, ResultSetMetaData rmdata, Element parent)
-            throws JDOMException {
-
-        // -----------------------------------
-        // Create the Select element ...
-        // -----------------------------------
-
-        Element selectElement = new Element(TagNames.Elements.SELECT);
-
-        // ---------------------------------
-        // Create the DISTINCT attribute ...
-        // ---------------------------------
-        boolean distinct = select.isDistinct();
-        if ( distinct ) {
-            Attribute distinctAttribute = new Attribute(TagNames.Attributes.DISTINCT, "true"); //$NON-NLS-1$
-            selectElement.setAttribute(distinctAttribute);
-        } // else default is false so no need
-
-        // ----------------------------------
-        // Create the STAR attribute ...
-        // ----------------------------------
-        if ( select.isStar() ) {
-            Attribute starAttribute = new Attribute(TagNames.Attributes.STAR, "true"); //$NON-NLS-1$
-            selectElement.setAttribute(starAttribute);
-        }
-
-        // --------------------------------
-        // Create the DATANODE elements ...
-        // --------------------------------
-        int col = 0;
-        Iterator iter = select.getSymbols().iterator();
-        while ( iter.hasNext() ) {
-            Element dataElement = new Element(TagNames.Elements.DATA_ELEMENT);
-            ElementSymbol symbol = (ElementSymbol) iter.next();
-            String elementName = symbol.getName();
-            Attribute dataType = null;
-            try {
-                dataType = new Attribute(TagNames.Attributes.TYPE, rmdata.getColumnTypeName(++col));
-            } catch ( SQLException e ) {
-                //
-            }
-            dataElement.setAttribute(dataType);
-            dataElement.setText(elementName);
-            selectElement.addContent(dataElement);
-        }
-        if ( parent != null ) {
-            selectElement = parent.addContent(selectElement);
-        }
-
-        return selectElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Object.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceObject(Object object, Element parent) throws JDOMException, SQLException {
-
-    	System.out.println("PRODUCT OBJECT");
-        // ----------------------
-        // Create the Object element ...
-        // ----------------------
-        Element objectElement = new Element(TagNames.Elements.OBJECT);
-        
-        String result = null;
-        if (object instanceof Blob || object instanceof Clob || object instanceof SQLXML) {
-       	 
-        	if (object instanceof Clob){
-        		Clob c = (Clob)object;
-        		try {
-        			result = ObjectConverterUtil.convertToString(c.getAsciiStream());
-					
-				} catch (Throwable e) {
-					// TODO Auto-generated catch block
-					throw new SQLException(e);
-				}
-        	} else if (object instanceof Blob){
-            		Blob b = (Blob)object;
-            		try {
-            			result = ObjectConverterUtil.convertToString(b.getBinaryStream());
-						
-					} catch (Throwable e) {
-						// TODO Auto-generated catch block
-						throw new SQLException(e);
-					}
-            } else if (object instanceof SQLXML){
-            	SQLXML s = (SQLXML)object;
-        		try {
-        			result = ObjectConverterUtil.convertToString(s.getBinaryStream());
-					
-				} catch (Throwable e) {
-					// TODO Auto-generated catch block
-					throw new SQLException(e);
-				}
-            } 
-        } else {
-        	result = object.toString();
-        }
-        
- //       System.out.println("ProductObject (before encoding): " + object.toString() );
- //       try {
-            objectElement.setText(result);
-            	//	URLEncoder.encode(object.toString(), "UTF-8"));
- //       } catch (UnsupportedEncodingException e) {
-            // UTF-8 is supported natively by all jvms
- //       }
-//        System.out.println("ProductObject (after encoding): " + objectElement.getText() );
-
-        
-        if ( parent != null ) {
-            objectElement = parent.addContent(objectElement);
-        }
-
-        return objectElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the String.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(String object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the String element ...
-        // ----------------------
-        Element stringElement = new Element(TagNames.Elements.STRING);
-        stringElement.setText(object);
-        if ( parent != null ) {
-            stringElement = parent.addContent(stringElement);
-        }
-
-        return stringElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Character.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Character object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Character element ...
-        // ----------------------
-        Element charElement = new Element(TagNames.Elements.CHAR);
-               
-        String v = object.toString();
-        if (v != null && v.length() != 0) {
-            
-	    String toReplace = new String( new Character( (char)0x0).toString() );
-	    v.replaceAll(toReplace," ");
-	    charElement.setText(v.trim());
-
-        }
-        if ( parent != null ) {
-            charElement = parent.addContent(charElement);
-        }
-
-
-        return charElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Byte.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Byte object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Byte element ...
-        // ----------------------
-        Element byteElement = new Element(TagNames.Elements.BYTE);
-        byteElement.setText(object.toString());
-        if ( parent != null ) {
-            byteElement = parent.addContent(byteElement);
-        }
-
-        return byteElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Boolean.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Boolean object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Boolean element ...
-        // ----------------------
-        Element booleanElement = new Element(TagNames.Elements.BOOLEAN);
-
-        if ( object.booleanValue() == true ) {
-            booleanElement.setText(TagNames.Values.TRUE);
-        } else {
-            booleanElement.setText(TagNames.Values.FALSE);
-        }
-
-        if ( parent != null ) {
-            booleanElement = parent.addContent(booleanElement);
-        }
-
-        return booleanElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Float.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Float object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Float element ...
-        // ----------------------
-        Element floatElement = new Element(TagNames.Elements.FLOAT);
-        floatElement.setText(object.toString());
-        if ( parent != null ) {
-            floatElement = parent.addContent(floatElement);
-        }
-
-        return floatElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Double.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Double object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Double element ...
-        // ----------------------
-        Element doubleElement = new Element(TagNames.Elements.DOUBLE);
-        doubleElement.setText(object.toString());
-        if ( parent != null ) {
-            doubleElement = parent.addContent(doubleElement);
-        }
-
-        return doubleElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the BigDecimal.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(BigDecimal object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the BigDecimal element ...
-        // ----------------------
-        Element bigDecimalElement = new Element(TagNames.Elements.BIGDECIMAL);
-        bigDecimalElement.setText(object.toString());
-        if ( parent != null ) {
-            bigDecimalElement = parent.addContent(bigDecimalElement);
-        }
-
-        return bigDecimalElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the BigInteger.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(BigInteger object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the BigInteger element ...
-        // ----------------------
-        Element bigIntegerElement = new Element(TagNames.Elements.BIGINTEGER);
-        bigIntegerElement.setText(object.toString());
-        if ( parent != null ) {
-            bigIntegerElement = parent.addContent(bigIntegerElement);
-        }
-
-        return bigIntegerElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the java.sql.Date.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(java.sql.Date object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the java.sql.Date element ...
-        // ----------------------
-        Element sqldateElement = new Element(TagNames.Elements.DATE);
-        sqldateElement.setText(object.toString());
-        if ( parent != null ) {
-            sqldateElement = parent.addContent(sqldateElement);
-        }
-
-        return sqldateElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Time.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Time object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Time element ...
-        // ----------------------
-        Element timeElement = new Element(TagNames.Elements.TIME);
-        timeElement.setText(object.toString());
-        if ( parent != null ) {
-            timeElement = parent.addContent(timeElement);
-        }
-
-        return timeElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Timestamp.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Timestamp object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Timestamp element ...
-        // ----------------------
-        Element timestampElement = new Element(TagNames.Elements.TIMESTAMP);
-        timestampElement.setText(object.toString());
-        if ( parent != null ) {
-            timestampElement = parent.addContent(timestampElement);
-        }
-
-        return timestampElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Integer.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Integer object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Integer element ...
-        // ----------------------
-        Element integerElement = new Element(TagNames.Elements.INTEGER);
-        integerElement.setText(object.toString());
-        if ( parent != null ) {
-            integerElement = parent.addContent(integerElement);
-        }
-
-        return integerElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Long.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Long object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Long element ...
-        // ----------------------
-        Element longElement = new Element(TagNames.Elements.LONG);
-        longElement.setText(object.toString());
-        if ( parent != null ) {
-            longElement = parent.addContent(longElement);
-        }
-
-        return longElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the Short.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Short object, Element parent) throws JDOMException {
-
-        // ----------------------
-        // Create the Long element ...
-        // ----------------------
-        Element shortElement = new Element(TagNames.Elements.SHORT);
-        shortElement.setText(object.toString());
-        if ( parent != null ) {
-            shortElement = parent.addContent(shortElement);
-        }
-
-        return shortElement;
-    }
-
-    /**
-     * Produce an XML message for an instance of the SQLException.
-     * <br>
-     * @param object the instance for which the message is to be produced.
-     * @param parent the XML element that is to be the parent of the produced XML message.
-     * @return the root element of the XML segment that was produced.
-     * @exception JDOMException if there is an error producing the message.
-     */
-    private Element produceMsg(Throwable object, Element parent) throws JDOMException {
-
-        Throwable exception = object;
-        Element exceptionElement = null;
-
-        // --------------------------------
-        // Create the Exception element ...
-        // --------------------------------
-        exceptionElement = new Element(TagNames.Elements.EXCEPTION);
-
-        // ---------------------------------
-        // Add the ExceptionType element ...
-        // ---------------------------------
-        String className = exception.getClass().getName();
-        int index = className.lastIndexOf('.');
-        if ( index != -1 && (++index) < className.length() ) {
-            className = className.substring(index);
-        }
-        Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
-        typeElement.setText(className);
-        exceptionElement.addContent(typeElement);
-
-        // ---------------------------
-        // Add the Message element ...
-        // ---------------------------
-        Element messageElement = new Element(TagNames.Elements.MESSAGE);
-        messageElement.setText(StringUtil.removeChars(exception.getMessage(), new char[] {'\r'}));
-         
-        exceptionElement.addContent(messageElement);
-
-        // -------------------------
-        // Add the Class element ...
-        // -------------------------
-        Element classElement = new Element(TagNames.Elements.CLASS);
-        classElement.setText(exception.getClass().getName());
-        exceptionElement.addContent(classElement);
-
-        if ( parent != null ) {
-            exceptionElement = parent.addContent(exceptionElement);
-        }
-
-        return exceptionElement;
-    }
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/ctc/XMLQueryVisitationStrategy.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,1754 @@
+/*
+ * 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.test.client.ctc;
+
+import java.io.File;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.jdom.Attribute;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.JDOMException;
+import org.jdom.input.SAXBuilder;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.internal.core.xml.SAXBuilderHelper;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.test.client.QuerySQL;
+import org.teiid.test.client.QueryTest;
+import org.teiid.test.client.ctc.QueryResults.ColumnInfo;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+import org.teiid.test.util.StringUtil;
+
+
+
+/**
+ * <P> This program helps in parsing XML Query and Results files into
+ * map objects containing individual queries/ResultSets</P>
+ *
+ * <P> This program is useful to convert the JDBC ResultSet objects into
+ * XML format. We physically walk through the ResultSet object and use JDOM to
+ * convert the ResultSets into XML. This also helps convert Exceptions into XML
+ * format.</P>
+ */
+
+public class XMLQueryVisitationStrategy {
+
+    //the row from which we start converting ResultSets to XML
+    private static final int START_ROW = 1;
+
+    // list containing datatypes of field identifiers
+
+    public XMLQueryVisitationStrategy() {
+    }
+
+    /**
+     * Consume an XML Query File and produce a Map containing queries, with
+     * queryNames/IDs as Keys.
+     * <br>
+     * @param queryFile the XML file object that is to be parsed
+     * @return the List containing quers.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    public List parseXMLQueryFile(String queryScenarioID, File queryFile, String querySetID) throws IOException, JDOMException {
+
+	List<QueryTest> queries = new LinkedList();
+//        HashMap queryMap = new HashMap();
+        SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
+        Document queryDocument = builder.build(queryFile);
+        List queryElements = queryDocument.getRootElement().getChildren(TagNames.Elements.QUERY);
+        Iterator iter = queryElements.iterator();
+        while ( iter.hasNext() ) {
+            Element queryElement = (Element) iter.next();
+            String queryName = queryElement.getAttributeValue(TagNames.Attributes.NAME);
+            if ( queryElement.getChild(TagNames.Elements.EXCEPTION) == null ) {
+        	String uniqueID = querySetID + "_" + queryName;
+        	
+		List<Element> parmChildren = queryElement.getChildren(TagNames.Elements.SQL);
+        	
+		if (parmChildren == null || parmChildren.isEmpty()) {
+        	    TestLogger.logDebug("=======  Single QueryTest ");
+        	    QuerySQL sql = createQuerySQL(queryElement);
+         	    
+        	    QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, new QuerySQL[] {sql}, false);
+        	    queries.add(q);
+        	} else {
+        	    TestLogger.logDebug("=======  QueryTest has multiple sql statements");
+         		QuerySQL[] querysql = new QuerySQL[parmChildren.size()];
+        		int c = 0;
+        		
+        		final Iterator<Element> sqliter = parmChildren.iterator();
+        		while ( sqliter.hasNext() ) {
+        			final Element sqlElement = (Element) sqliter.next();
+        			QuerySQL sql = createQuerySQL(sqlElement);
+        			querysql[c] = sql;
+        			c++;	
+        		}
+        		QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, querysql, false);
+        		queries.add(q);
+               		
+        		
+       	    
+        	}
+ //               queryMap.put(queryName, query);
+            } else {
+                Element exceptionElement = queryElement.getChild(TagNames.Elements.EXCEPTION);
+                String exceptionType = exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim();
+                
+                String uniqueID = querySetID + "_" + queryName;
+                QuerySQL sql = new QuerySQL(exceptionType, null);
+                
+                QueryTest q = new QueryTest(queryScenarioID, uniqueID, querySetID, new QuerySQL[] {sql}, true);
+                queries.add(q);
+
+                
+ //               queryMap.put(queryName, exceptionType);
+            }
+        }
+        return queries;
+    }
+    
+    private QuerySQL createQuerySQL(Element queryElement) {
+ 	    String query = queryElement.getTextTrim();
+ 	    	    
+	    Object[] parms = getParms(queryElement);
+	    	    
+	    QuerySQL sql = new QuerySQL(query, parms);
+	    
+ 	    String updateCnt = queryElement.getAttributeValue(TagNames.Attributes.UPDATE_CNT);
+ 	    if (updateCnt != null && updateCnt.trim().length() > 0) {
+ 		int cnt = Integer.parseInt(updateCnt);
+ 		sql.setUpdateCnt(cnt);
+ 	    }
+ 	    
+ 	    String rowCnt = queryElement.getAttributeValue(TagNames.Attributes.TABLE_ROW_COUNT);
+ 	    if (rowCnt != null && rowCnt.trim().length() > 0) {
+ 		int cnt = Integer.parseInt(rowCnt);
+ 		sql.setRowCnt(cnt);
+ 	    }
+	    
+	    return sql;	
+    }
+    
+    private Object[] getParms(Element parent) {
+	List<Element> parmChildren = parent.getChildren(TagNames.Elements.PARM);
+	if (parmChildren == null) {
+	    return null;
+	}
+	
+	Object[] parms = new Object[parmChildren.size()];
+	int i = 0;
+	final Iterator<Element> iter = parmChildren.iterator();
+	while ( iter.hasNext() ) {
+		final Element parmElement = (Element) iter.next();
+		try {
+		    Object parm = createParmType(parmElement);
+		    parms[i] = parm;
+		    i++;
+		} catch (JDOMException e) {
+		    throw new TransactionRuntimeException(e);
+		}		
+	}
+	
+	
+	
+	return parms;
+    }
+    
+    private Object createParmType(Element cellElement) throws JDOMException {
+
+        Object cellObject = null;
+        
+        final String typeName = cellElement.getAttributeValue(TagNames.Attributes.TYPE);
+ 
+        if ( typeName.equalsIgnoreCase(TagNames.Elements.BOOLEAN) ) {
+            cellObject = consumeMsg((Boolean) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.STRING) ) {
+            cellObject = consumeMsg((String) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.CHAR) ) {
+            cellObject = consumeMsg((Character) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BYTE) ) {
+            cellObject = consumeMsg((Byte) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.DOUBLE) ) {
+            cellObject = consumeMsg((Double) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.DATE) ) {
+            cellObject = consumeMsg((java.sql.Date) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.TIME) ) {
+            cellObject = consumeMsg((Time) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.TIMESTAMP) ) {
+            cellObject = consumeMsg((Timestamp) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.FLOAT) ) {
+            cellObject = consumeMsg((Float) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BIGDECIMAL) ) {
+            cellObject = consumeMsg((BigDecimal) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.BIGINTEGER) ) {
+            cellObject = consumeMsg((BigInteger) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.INTEGER) ) {
+            cellObject = consumeMsg((Integer) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.LONG) ) {
+            cellObject = consumeMsg((Long) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.SHORT) ) {
+            cellObject = consumeMsg((Short) cellObject, cellElement);
+        } else if ( typeName.equalsIgnoreCase(TagNames.Elements.OBJECT) ) {
+            cellObject = consumeMsg((String) cellObject, cellElement);
+        }
+
+        return cellObject;
+    }
+
+    /**
+     * Consume an XML results File and produce a Map containing query results
+     * as List objects, with resultNames/IDs as Keys.
+     * <br>
+     * @param resultsFile the XML file object that is to be parsed
+     * @return the Map containig results.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    public ResultsHolder parseXMLResultsFile(final File resultsFile) throws IOException, JDOMException {
+
+        QueryResults queryResults;
+        ResultsHolder expectedResults = null;
+
+        final SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
+        final Document resultsDocument = builder.build(resultsFile);
+        final String query = resultsDocument.getRootElement().getChildText(TagNames.Elements.QUERY);
+        final List resultElements = resultsDocument.getRootElement().getChildren(TagNames.Elements.QUERY_RESULTS);
+        final Iterator iter = resultElements.iterator();
+        while ( iter.hasNext() ) {
+            final Element resultElement = (Element) iter.next();
+            final String resultName = resultElement.getAttributeValue(TagNames.Attributes.NAME);
+            queryResults = consumeMsg(new QueryResults(), resultElement);
+            if ( queryResults.getFieldCount() != 0 ) {
+                //
+                // We've got a ResultSet
+                //
+                expectedResults = new ResultsHolder( TagNames.Elements.QUERY_RESULTS );
+                expectedResults.setQueryID( resultName );
+                expectedResults.setQuery(query);
+                expectedResults.setIdentifiers( queryResults.getFieldIdents() );
+                expectedResults.setTypes( queryResults.getTypes() );
+                if ( queryResults.getRecordCount() > 0 ) {
+                    expectedResults.setRows(queryResults.getRecords());
+                }
+            } else {
+                //
+                // We've got an exception
+                //
+                expectedResults = new ResultsHolder( TagNames.Elements.EXCEPTION );
+                expectedResults.setQueryID( resultName );
+                expectedResults.setQuery(query);
+
+                final Element exceptionElement = resultElement.getChild(TagNames.Elements.EXCEPTION);
+                if ( exceptionElement != null ) {
+                    expectedResults.setExceptionClassName(exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim());
+                    String msg = exceptionElement.getChild(TagNames.Elements.MESSAGE).getTextTrim();   
+                    expectedResults.setExceptionMsg(StringUtil.removeChars(msg, new char[] {'\r'}));
+                }
+            }
+        }
+        return expectedResults;
+    }
+
+    /**
+     * Consume an XML results File, produce results as JDOM and add results to the given parent.
+     * <br>
+     * @param resultsFile the XML file object that is to be parsed
+     * @param parent the parent Element to assign results to
+     * @return the modified parent
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    public Element parseXMLResultsFile(File resultsFile, Element parent) throws IOException, JDOMException {
+
+        SAXBuilder builder = SAXBuilderHelper.createSAXBuilder(false);
+        Document resultsDocument = builder.build(resultsFile);
+        List resultElements = resultsDocument.getRootElement().getChildren(TagNames.Elements.QUERY_RESULTS);
+        Iterator iter = resultElements.iterator();
+        while ( iter.hasNext() ) {
+            Element resultElement = (Element) iter.next();
+            if ( resultElement.getChild(TagNames.Elements.SELECT) == null ) {
+                // We've got an exception
+                Element exceptionElement = resultElement.getChild(TagNames.Elements.EXCEPTION);
+                if ( exceptionElement != null ) {
+                    // ---------------------------------
+                    // Add the ExceptionType element ...
+                    // ---------------------------------
+                    Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
+                    typeElement.setText(exceptionElement.getChild(TagNames.Elements.EXCEPTION_TYPE).getTextTrim());
+                    parent.addContent(typeElement);
+
+                    // ---------------------------
+                    // Add the Message element ...
+                    // ---------------------------
+                    Element messageElement = new Element(TagNames.Elements.MESSAGE);    
+                    String msg = exceptionElement.getChild(TagNames.Elements.MESSAGE).getTextTrim();   
+                    
+                    messageElement.setText(StringUtil.removeChars(msg, new char[] {'\r'}));
+                    parent.addContent(messageElement);
+
+                    // -------------------------
+                    // Add the Class element ...
+                    // -------------------------
+                    Element classElement = new Element(TagNames.Elements.CLASS);
+                    classElement.setText(exceptionElement.getChild(TagNames.Elements.CLASS).getTextTrim());
+                    parent.addContent(classElement);
+                }
+            } else {
+                // We've got results
+
+                // -------------------------------
+                // Read the SELECT elements
+                // -------------------------------
+                Element selectElement = resultElement.getChild(TagNames.Elements.SELECT);
+                resultElement.removeChild(TagNames.Elements.SELECT);
+                parent.addContent(selectElement);
+
+                // -------------------------------
+                // Read the TABLE of data
+                // -------------------------------
+                Element tableElement = resultElement.getChild(TagNames.Elements.TABLE);
+                resultElement.removeChild(TagNames.Elements.TABLE);
+                parent.addContent(tableElement);
+            }
+        }
+        return parent;
+    }
+
+    /*********************************************************************************************
+     *********************************************************************************************
+     CONSUME METHODS
+     *********************************************************************************************
+     ********************************************************************************************/
+
+    /**
+     * Generate XML for an exception in Object form.
+     *
+     * @param ex
+     * @param exceptionElement
+     * @return The JDOM exception element.
+     */
+    public static Element jdomException(Throwable ex, Element exceptionElement) {
+        // ---------------------------------
+        // Add the ExceptionType element ...
+        // ---------------------------------
+        String className = ex.getClass().getName();
+        int index = className.lastIndexOf('.');
+        if ( index != -1 && (++index) < className.length() ) {
+            className = className.substring(index);
+        }
+        Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
+        typeElement.setText(className);
+        exceptionElement.addContent(typeElement);
+
+        // ---------------------------
+        // Add the Message element ...
+        // ---------------------------
+ 
+        Element messageElement = new Element(TagNames.Elements.MESSAGE);
+        messageElement.setText(StringUtil.removeChars(ex.getMessage(), new char[] {'\r'}));     
+        		
+        exceptionElement.addContent(messageElement);
+
+        // -------------------------
+        // Add the Class element ...
+        // -------------------------
+        Element classElement = new Element(TagNames.Elements.CLASS);
+        classElement.setText(ex.getClass().getName());
+        exceptionElement.addContent(classElement);
+
+        return exceptionElement;
+    }
+
+    /**
+     * Consume an XML message and update the specified QueryResults instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param resultsElement the XML element that contains the data
+     * @return the updated instance.
+     */
+    private QueryResults consumeMsg(QueryResults object, Element resultsElement) throws JDOMException {
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        QueryResults results = object;
+        if ( results == null ) {
+            results = new QueryResults();
+        }
+
+        if ( resultsElement.getChild(TagNames.Elements.SELECT) == null ) {
+            return results;
+        }
+        // -------------------------------
+        // Read the SELECT elements
+        // -------------------------------
+        Element selectElement = resultsElement.getChild(TagNames.Elements.SELECT);
+        Select select = new Select();
+        select = consumeMsg(select, selectElement);
+
+        List listOfElementSymbols = select.getSymbols();
+        Iterator elementSymbolItr = listOfElementSymbols.iterator();
+        Collection collectionOfColumnInfos = new ArrayList();
+        while ( elementSymbolItr.hasNext() ) {
+            ElementSymbol elementSymbol = (ElementSymbol) elementSymbolItr.next();
+            Class elementType = elementSymbol.getType();
+            String dataType = DataTypeManager.getDataTypeName(elementType);
+            ColumnInfo columnInfo = new ColumnInfo(elementSymbol.getName(), dataType, elementType);
+            collectionOfColumnInfos.add(columnInfo);
+        }
+        // Save column info
+        results.addFields(collectionOfColumnInfos);
+        // -------------------------------
+        // Read the TABLE of data
+        // -------------------------------
+
+        Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
+        List tableRows = tableElement.getChildren(TagNames.Elements.TABLE_ROW);
+        if ( tableRows.size() > 0 ) {
+            Iterator rowIter = tableRows.iterator();
+
+            while ( rowIter.hasNext() ) {
+                Element rowElement = (Element) rowIter.next();
+                List cellElements = rowElement.getChildren(TagNames.Elements.TABLE_CELL);
+                Iterator cellIter = cellElements.iterator();
+                // Read cells of the table
+                ArrayList row = new ArrayList();
+                Object evalue = null;
+                while ( cellIter.hasNext() ) {
+                    Element cellElement = (Element) cellIter.next();
+                    if ( cellElement.getTextTrim().equalsIgnoreCase(TagNames.Elements.NULL) ) {
+                        row.add(null);
+                    } else {
+                        Element cellChildElement = (Element) cellElement.getChildren().get(0);
+                        evalue = consumeMsg(cellChildElement);
+                        row.add(evalue);
+                    }
+                }
+                // Save row
+                results.addRecord(row);
+            }
+        }
+        return results;
+    }
+
+    /**
+     * Consume an XML message and update the specified Select instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param selectElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Select consumeMsg(Select object, Element selectElement) throws JDOMException {
+
+        Select select = (object != null) ? (Select) object : new Select();
+        // --------------------------------
+        // Read the DISTINCT attribute
+        // --------------------------------
+
+        String distinct = selectElement.getAttributeValue(TagNames.Attributes.DISTINCT);
+        if ( distinct != null ) {
+            if ( distinct.equalsIgnoreCase("true") ) { //$NON-NLS-1$
+                select.setDistinct(true);
+            }
+        }
+
+        // --------------------------------
+        // Read the STAR attribute
+        // --------------------------------
+
+        String star = selectElement.getAttributeValue(TagNames.Attributes.STAR);
+        if ( star != null ) {
+            if ( star.equalsIgnoreCase("true") ) { //$NON-NLS-1$
+                if ( selectElement.getChildren() != null ) {
+                    throw new JDOMException("No children expected when star is chosen."); //$NON-NLS-1$
+                }
+                return select;
+            }
+        }
+
+        // --------------------------------
+        // Read the IDENTIFIER elements ...
+        // --------------------------------
+        List idents = selectElement.getChildren();
+        Iterator identIter = idents.iterator();
+        while ( identIter.hasNext() ) {
+            Element dataElement = (Element) identIter.next();
+            Attribute dataType = dataElement.getAttribute(TagNames.Attributes.TYPE);
+            // add the dataType of the element to the list containing dataTypes
+            ElementSymbol nodeID = new ElementSymbol(dataElement.getText());
+            Class nodeType = (Class) TagNames.TYPE_MAP.get(dataType.getValue());
+            if (nodeType == null)  {
+                throw new JDOMException("Unknown class for type \"" + dataType.getValue() + "\"."); //$NON-NLS-1$ //$NON-NLS-2$
+            }
+            nodeID.setType(nodeType);
+            select.addSymbol(nodeID);
+        }
+
+        return select;
+    }
+
+
+    /**
+     * Produce a JDOM Element for the instance of any Object.
+     * <br>
+     * @param cellElement the XML element that is to produce the XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing XML.
+     */
+    private Object consumeMsg(Element cellElement) throws JDOMException {
+
+        Object cellObject = null;;
+        String cellName = cellElement.getName();
+
+        if ( cellName.equalsIgnoreCase(TagNames.Elements.BOOLEAN) ) {
+            cellObject = consumeMsg((Boolean) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.STRING) ) {
+            cellObject = consumeMsg((String) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.CHAR) ) {
+            cellObject = consumeMsg((Character) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BYTE) ) {
+            cellObject = consumeMsg((Byte) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.DOUBLE) ) {
+            cellObject = consumeMsg((Double) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.DATE) ) {
+            cellObject = consumeMsg((java.sql.Date) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.TIME) ) {
+            cellObject = consumeMsg((Time) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.TIMESTAMP) ) {
+            cellObject = consumeMsg((Timestamp) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.FLOAT) ) {
+            cellObject = consumeMsg((Float) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BIGDECIMAL) ) {
+            cellObject = consumeMsg((BigDecimal) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.BIGINTEGER) ) {
+            cellObject = consumeMsg((BigInteger) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.INTEGER) ) {
+            cellObject = consumeMsg((Integer) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.LONG) ) {
+            cellObject = consumeMsg((Long) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.SHORT) ) {
+            cellObject = consumeMsg((Short) cellObject, cellElement);
+        } else if ( cellName.equalsIgnoreCase(TagNames.Elements.OBJECT) ) {
+            cellObject = consumeMsg((String) cellObject, cellElement);
+        } else {
+        	cellObject = consumeMsg(cellObject, cellElement);
+        }
+
+        return cellObject;
+    }
+
+    /**
+     * Consume an XML message and update the specified Boolean instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Boolean object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        boolean result = false;
+        String value = cellElement.getTextTrim();
+        if ( value.equalsIgnoreCase(TagNames.Values.TRUE) ) {
+            result = true;
+        } else if ( value.equalsIgnoreCase(TagNames.Values.FALSE) ) {
+            result = false;
+        } else {
+            throw new JDOMException("Invalid value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: \"" + value + "\" must be either \"" + //$NON-NLS-1$ //$NON-NLS-2$
+                                    TagNames.Values.TRUE + "\" or \"" + //$NON-NLS-1$
+                                    TagNames.Values.FALSE + "\""); //$NON-NLS-1$
+        }
+
+        return new Boolean(result);
+    }
+
+    /**
+     * Consume an XML message and update the specified java.sql.Date instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(java.sql.Date object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        java.sql.Date result;
+        try {
+            result = java.sql.Date.valueOf(cellElement.getTextTrim());
+        } catch ( Exception e ) {
+            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Time instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Time object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Time result;
+        try {
+            result = Time.valueOf(cellElement.getTextTrim());
+        } catch ( Exception e ) {
+            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Timestamp instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Timestamp object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Timestamp result;
+        try {
+            result = Timestamp.valueOf(cellElement.getTextTrim());
+        } catch ( Exception e ) {
+            throw new JDOMException("Invalid input format ", e); //$NON-NLS-1$
+        }
+
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Double instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Double object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        String strElement = cellElement.getTextTrim();
+        Double result;
+
+        if ( strElement.equals("NaN") ) { //$NON-NLS-1$
+            result = new Double(Double.NaN);
+        } else if ( strElement.equals("-Infinity") ) { //$NON-NLS-1$
+            result = new Double(Double.NEGATIVE_INFINITY);
+        } else if ( strElement.equals("Infinity") ) { //$NON-NLS-1$
+            result = new Double(Double.POSITIVE_INFINITY);
+        } else {
+            try {
+                result = Double.valueOf(strElement);
+            } catch ( NumberFormatException e ) {
+                throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                        " element: " + strElement, e); //$NON-NLS-1$
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Float instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Float object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        String strElement = cellElement.getTextTrim();
+        Float result;
+
+        if ( strElement.equals("NaN") ) { //$NON-NLS-1$
+            result = new Float(Float.NaN);
+        } else if ( strElement.equals("-Infinity") ) { //$NON-NLS-1$
+            result = new Float(Float.NEGATIVE_INFINITY);
+        } else if ( strElement.equals("Infinity") ) { //$NON-NLS-1$
+            result = new Float(Float.POSITIVE_INFINITY);
+        } else {
+            try {
+                result = Float.valueOf(strElement);
+            } catch ( NumberFormatException e ) {
+                throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                        " element: " + strElement, e); //$NON-NLS-1$
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified BigDecimal instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(BigDecimal object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        BigDecimal result;
+        try {
+            result = new BigDecimal(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified BigInteger instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(BigInteger object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        BigInteger result;
+        try {
+            result = new BigInteger(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified String instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(String object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+
+        return cellElement.getText();
+    }
+
+    /**
+     * Consume an XML message and update the specified Character instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Character object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Character result;
+        try {
+            if ( cellElement.getTextTrim().length() == 0 ) {
+                return null;
+            }
+            result = new Character(cellElement.getTextTrim().charAt(0));
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Byte instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Byte object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Byte result;
+        try {
+            result = new Byte(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Integer instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Integer object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Integer result;
+        try {
+            result = Integer.valueOf(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /**
+     * Consume an XML message and update the specified Long instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Long object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Long result;
+        try {
+            result = Long.valueOf(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
+        }
+        return result;
+    }
+    
+    
+    /**
+     * Consume an XML message and update the specified Byte instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    @SuppressWarnings("unused")
+	private Object consumeMsg(Object object, Element cellElement) throws JDOMException {
+
+//        // -----------------------
+//        // Process the element ...
+//        // -----------------------
+//        Byte result;
+//        try {
+//            result = new Byte(cellElement.getTextTrim());
+//        } catch ( NumberFormatException e ) {
+//            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+//                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-1$
+//        }
+//        return result;
+        
+    	return cellElement.getText();
+        // ----------------------
+        // Create the Object element ...
+        // ----------------------
+//        Element objectElement = new Element(TagNames.Elements.OBJECT);
+//        
+//        String result = null;
+//        if (object instanceof Blob || object instanceof Clob || object instanceof SQLXML) {
+//       	 
+//        	if (object instanceof Clob){
+//        		Clob c = (Clob)object;
+//        		try {
+//        			result = ObjectConverterUtil.convertToString(c.getAsciiStream());
+//					
+//				} catch (Throwable e) {
+//					// TODO Auto-generated catch block
+//					throw new SQLException(e);
+//				}
+//        	} else if (object instanceof Blob){
+//            		Blob b = (Blob)object;
+//            		try {
+//            			result = ObjectConverterUtil.convertToString(b.getBinaryStream());
+//						
+//					} catch (Throwable e) {
+//						// TODO Auto-generated catch block
+//						throw new SQLException(e);
+//					}
+//            } else if (object instanceof SQLXML){
+//            	SQLXML s = (SQLXML)object;
+//        		try {
+//        			result = ObjectConverterUtil.convertToString(s.getBinaryStream());
+//					
+//				} catch (Throwable e) {
+//					// TODO Auto-generated catch block
+//					throw new SQLException(e);
+//				}
+//            } 
+//        } else {
+//        	result = object.toString();
+//        }
+//        
+// //       System.out.println("ProductObject (before encoding): " + object.toString() );
+// //       try {
+//            objectElement.setText(result);
+//            	//	URLEncoder.encode(object.toString(), "UTF-8"));
+// //       } catch (UnsupportedEncodingException e) {
+//            // UTF-8 is supported natively by all jvms
+// //       }
+////        System.out.println("ProductObject (after encoding): " + objectElement.getText() );
+//
+//        
+//        if ( parent != null ) {
+//            objectElement = parent.addContent(objectElement);
+//        }
+//
+//        return objectElement;
+
+    }
+
+    /**
+     * Consume an XML message and update the specified Long instance.
+     * <br>
+     * @param object the instance that is to be updated with the XML message data.
+     * @param cellElement the XML element that contains the data
+     * @return the updated instance.
+     * @exception JDOMException if there is an error consuming the message.
+     */
+    private Object consumeMsg(Short object, Element cellElement) throws JDOMException {
+
+        // -----------------------
+        // Process the element ...
+        // -----------------------
+        Short result;
+        try {
+            result = Short.valueOf(cellElement.getTextTrim());
+        } catch ( NumberFormatException e ) {
+            throw new JDOMException("Unable to parse the value for " + cellElement.getName() + //$NON-NLS-1$
+                                    " element: " + cellElement.getTextTrim(), e); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$ //$NON-NLS-1$
+        }
+        return result;
+    }
+
+    /*********************************************************************************************
+     *********************************************************************************************
+     PRODUCE METHODS
+     *********************************************************************************************
+     ********************************************************************************************/
+
+    /**
+     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
+     * <br>
+     * @param object for which the JDOM Element is to be produced.
+     * @return the JDOM element of the ResultSet object that was converted to XML.
+     * @exception JDOMException if there is an error producing XML.
+     * @exception JDOMException if there is an error producing XML.
+     * @exception SQLException if there is an error walking through the ResultSet object.
+     */
+    public Element produceResults(ResultSet object) throws JDOMException, SQLException {
+
+        // When no begin and end
+        return produceResults(object, START_ROW, Integer.MAX_VALUE);
+    }
+
+    /**
+     * Produce a JDOM Element for an instance of Results object.
+     * <br>
+     * @param object for which the JDOM Element is to be produced.
+     * @param beginRow The starting row from which the results are to be converted to XML.
+     * @param endRow The row until which the results are to be converted to XML.
+     * @return the JDOM element of the results object that was converted to XML.
+     * @exception JDOMException if there is an error producing XML.
+     * @exception SQLException if there is an error walking through the ResultSet object.
+     */
+    private Element produceResults(ResultSet object, int beginRow, int endRow)
+            throws JDOMException, SQLException {
+
+    	if (object.isClosed()) {
+            throw new SQLException(
+            "ResultSet is closed at this point, unable to product results"); //$NON-NLS-1$
+    		
+    	}
+    	
+        if ( beginRow < START_ROW ) {
+            throw new IllegalArgumentException(
+                    "The starting row cannot be less than 1."); //$NON-NLS-1$
+        } else if ( beginRow > endRow ) {
+            throw new IllegalArgumentException(
+                    "The starting row cannot be less than the ending row."); //$NON-NLS-1$
+        }
+
+        int currentRow = object.getRow() + 1;
+
+        if ( beginRow > currentRow ) {
+            while ( !object.isLast() && currentRow != beginRow ) {
+                object.next();
+                currentRow++;
+            }
+
+        } else if ( beginRow < currentRow ) {
+            while ( !object.isFirst() && currentRow != beginRow ) {
+                object.previous();
+                currentRow--;
+            }
+        }
+
+        return produceMsg(object, endRow);
+    }
+
+    /**
+     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
+     * <br>
+     * @param object for which the JDOM Element is to be produced.
+     * @param endRow The row until which the results are to be converted to XML.
+     * @return the JDOM element of the results object that was converted to XML.
+     * @exception JDOMException if there is an error producing XML.
+     * @exception SQLException if there is an error walking through the ResultSet object.
+     */
+    private Element produceMsg(ResultSet object, int endRow) throws JDOMException, SQLException {
+
+        // -----------------------------------
+        // Create the QueryResults element ...
+        // -----------------------------------
+        Element resultsElement = new Element(TagNames.Elements.QUERY_RESULTS);
+
+        // -----------------------------------
+        // Add the Select (header) element ...
+        // -----------------------------------
+        try {
+            ResultSetMetaData rmdata = object.getMetaData();
+            List identList = new ArrayList(rmdata.getColumnCount());
+            for ( int i = 1; i <= rmdata.getColumnCount(); i++ ) {
+                identList.add(new ElementSymbol(rmdata.getColumnName(i)));
+            }
+            Select select = new Select(identList);
+            resultsElement = produceMsg(select, rmdata, resultsElement);
+
+            // -------------------------
+            // Add the Table element ...
+            // -------------------------
+            resultsElement.addContent(new Element(TagNames.Elements.TABLE));
+            Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
+            int rowCount = 0;
+            int colCount = rmdata.getColumnCount();
+
+            while ( object.next() && (object.getRow() <= endRow) ) {
+
+                // -------------------------
+                // Add the ROW element ...
+                // -------------------------
+                Element rowElement = new Element(TagNames.Elements.TABLE_ROW);
+
+                for ( int i = 1; i <= colCount; i++ ) {
+                    // -------------------------
+                    // Add the Cell element ...
+                    // -------------------------
+                    Element cellElement = new Element(TagNames.Elements.TABLE_CELL);
+                    Object cellValue = object.getObject(i);
+                    if ( cellValue != null ) {
+                        cellElement = produceMsg(cellValue, cellElement);
+                    } else {
+                        cellElement = cellElement.addContent(TagNames.Elements.NULL);
+                    }
+                    rowElement.addContent(cellElement);
+                }
+                tableElement.addContent(rowElement);
+                rowCount++;
+            }
+            Attribute rowCountAttribute = new Attribute(TagNames.Attributes.TABLE_ROW_COUNT,
+                                                        Integer.toString(rowCount));
+            Attribute columnCountAttribute = new Attribute(TagNames.Attributes.TABLE_COLUMN_COUNT,
+                                                           Integer.toString(colCount));
+            tableElement.setAttribute(rowCountAttribute);
+            tableElement.setAttribute(columnCountAttribute);
+        } catch ( SQLException e ) {
+            // error while reading results
+            throw(e);
+        }
+
+        return resultsElement;
+    }
+
+    /**
+     * Produce a JDOM Element for an instance of a JDBC ResultSet object.
+     * <br>
+     * @param object for which the JDOM Element is to be produced.
+     * @return the JDOM element of the results object that was converted to XML.
+     * @exception JDOMException if there is an error producing XML.
+     * @exception SQLException if there is an error walking through the ResultSet object.
+     */
+    public Element produceMsg(ResultSet object, Element resultsElement) throws JDOMException, SQLException {
+
+        // -----------------------------------
+        // Add the Select (header) element ...
+        // -----------------------------------
+        try {
+            ResultSetMetaData rmdata = object.getMetaData();
+            List identList = new ArrayList(rmdata.getColumnCount());
+            for ( int i = 1; i <= rmdata.getColumnCount(); i++ ) {
+                identList.add(new ElementSymbol(rmdata.getColumnName(i)));
+            }
+            Select select = new Select(identList);
+            resultsElement = produceMsg(select, rmdata, resultsElement);
+
+            // -------------------------
+            // Add the Table element ...
+            // -------------------------
+            resultsElement.addContent(new Element(TagNames.Elements.TABLE));
+            Element tableElement = resultsElement.getChild(TagNames.Elements.TABLE);
+            int rowCount = 0;
+            int colCount = rmdata.getColumnCount();
+
+            while ( object.next() ) {
+
+                // -------------------------
+                // Add the ROW element ...
+                // -------------------------
+                Element rowElement = new Element(TagNames.Elements.TABLE_ROW);
+
+                for ( int i = 1; i <= colCount; i++ ) {
+                    // -------------------------
+                    // Add the Cell element ...
+                    // -------------------------
+                    Element cellElement = new Element(TagNames.Elements.TABLE_CELL);
+                    Object cellValue = object.getObject(i);
+                    if ( cellValue != null ) {
+                        cellElement = produceMsg(cellValue, cellElement);
+                    } else {
+                        cellElement = cellElement.addContent(TagNames.Elements.NULL);
+                    }
+                    rowElement.addContent(cellElement);
+                }
+                tableElement.addContent(rowElement);
+                rowCount++;
+            }
+            Attribute rowCountAttribute = new Attribute(TagNames.Attributes.TABLE_ROW_COUNT,
+                                                        Integer.toString(rowCount));
+            Attribute columnCountAttribute = new Attribute(TagNames.Attributes.TABLE_COLUMN_COUNT,
+                                                           Integer.toString(colCount));
+            tableElement.setAttribute(rowCountAttribute);
+            tableElement.setAttribute(columnCountAttribute);
+        } catch ( SQLException e ) {
+            // error while reading results
+            throw(e);
+        }
+
+        return resultsElement;
+    }
+
+    /**
+     * Produce a JDOM Element for the instance of any Object.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing XML.
+     */
+    public Element produceMsg(Object object, Element parent) throws JDOMException, SQLException {
+        if ( object == null ) {
+            throw new IllegalArgumentException("Null object reference."); //$NON-NLS-1$
+        }
+        Element element = null;
+
+        if ( object instanceof Boolean ) {
+            element = produceMsg((Boolean) object, parent);
+        } else if ( object instanceof String ) {
+            element = produceMsg((String) object, parent);
+        } else if ( object instanceof Character ) {
+            element = produceMsg((Character) object, parent);
+        } else if ( object instanceof Byte ) {
+            element = produceMsg((Byte) object, parent);
+        } else if ( object instanceof Double ) {
+            element = produceMsg((Double) object, parent);
+        } else if ( object instanceof java.sql.Date ) {
+            element = produceMsg((java.sql.Date) object, parent);
+        } else if ( object instanceof Time ) {
+            element = produceMsg((Time) object, parent);
+        } else if ( object instanceof Timestamp ) {
+            element = produceMsg((Timestamp) object, parent);
+        } else if ( object instanceof Float ) {
+            element = produceMsg((Float) object, parent);
+        } else if ( object instanceof BigDecimal ) {
+            element = produceMsg((BigDecimal) object, parent);
+        } else if ( object instanceof BigInteger ) {
+            element = produceMsg((BigInteger) object, parent);
+        } else if ( object instanceof Integer ) {
+            element = produceMsg((Integer) object, parent);
+        } else if ( object instanceof Long ) {
+            element = produceMsg((Long) object, parent);
+        } else if ( object instanceof Short ) {
+            element = produceMsg((Short) object, parent);
+        } else if ( object instanceof Throwable ) {
+            element = produceMsg((Throwable) object, parent);
+        } else {
+            element = produceObject(object, parent);
+        }
+
+        return element;
+    }
+
+    /**
+     * new ----
+     * @param select
+     * @param rmdata
+     * @param parent
+     * @return
+     * @throws JDOMException
+     */
+    private Element produceMsg(Select select, ResultSetMetaData rmdata, Element parent)
+            throws JDOMException {
+
+        // -----------------------------------
+        // Create the Select element ...
+        // -----------------------------------
+
+        Element selectElement = new Element(TagNames.Elements.SELECT);
+
+        // ---------------------------------
+        // Create the DISTINCT attribute ...
+        // ---------------------------------
+        boolean distinct = select.isDistinct();
+        if ( distinct ) {
+            Attribute distinctAttribute = new Attribute(TagNames.Attributes.DISTINCT, "true"); //$NON-NLS-1$
+            selectElement.setAttribute(distinctAttribute);
+        } // else default is false so no need
+
+        // ----------------------------------
+        // Create the STAR attribute ...
+        // ----------------------------------
+        if ( select.isStar() ) {
+            Attribute starAttribute = new Attribute(TagNames.Attributes.STAR, "true"); //$NON-NLS-1$
+            selectElement.setAttribute(starAttribute);
+        }
+
+        // --------------------------------
+        // Create the DATANODE elements ...
+        // --------------------------------
+        int col = 0;
+        Iterator iter = select.getSymbols().iterator();
+        while ( iter.hasNext() ) {
+            Element dataElement = new Element(TagNames.Elements.DATA_ELEMENT);
+            ElementSymbol symbol = (ElementSymbol) iter.next();
+            String elementName = symbol.getName();
+            Attribute dataType = null;
+            try {
+                dataType = new Attribute(TagNames.Attributes.TYPE, rmdata.getColumnTypeName(++col));
+            } catch ( SQLException e ) {
+                //
+            }
+            dataElement.setAttribute(dataType);
+            dataElement.setText(elementName);
+            selectElement.addContent(dataElement);
+        }
+        if ( parent != null ) {
+            selectElement = parent.addContent(selectElement);
+        }
+
+        return selectElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Object.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceObject(Object object, Element parent) throws JDOMException, SQLException {
+
+         // ----------------------
+        // Create the Object element ...
+        // ----------------------
+        Element objectElement = new Element(TagNames.Elements.OBJECT);
+        
+        String result = null;
+        if (object instanceof Blob || object instanceof Clob || object instanceof SQLXML) {
+       	 
+        	if (object instanceof Clob){
+        		Clob c = (Clob)object;
+        		try {
+        			result = ObjectConverterUtil.convertToString(c.getAsciiStream());
+					
+				} catch (Throwable e) {
+					// TODO Auto-generated catch block
+					throw new SQLException(e);
+				}
+        	} else if (object instanceof Blob){
+            		Blob b = (Blob)object;
+            		try {
+            			result = ObjectConverterUtil.convertToString(b.getBinaryStream());
+						
+					} catch (Throwable e) {
+						// TODO Auto-generated catch block
+						throw new SQLException(e);
+					}
+            } else if (object instanceof SQLXML){
+            	SQLXML s = (SQLXML)object;
+        		try {
+        			result = ObjectConverterUtil.convertToString(s.getBinaryStream());
+					
+				} catch (Throwable e) {
+					// TODO Auto-generated catch block
+					throw new SQLException(e);
+				}
+            } 
+        } else {
+        	result = object.toString();
+        }
+        
+         objectElement.setText(result);
+
+        
+        if ( parent != null ) {
+            objectElement = parent.addContent(objectElement);
+        }
+
+        return objectElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the String.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(String object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the String element ...
+        // ----------------------
+        Element stringElement = new Element(TagNames.Elements.STRING);
+        stringElement.setText(object);
+        if ( parent != null ) {
+            stringElement = parent.addContent(stringElement);
+        }
+
+        return stringElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Character.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Character object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Character element ...
+        // ----------------------
+        Element charElement = new Element(TagNames.Elements.CHAR);
+               
+        String v = object.toString();
+        if (v != null && v.length() != 0) {
+            
+	    String toReplace = new String( new Character( (char)0x0).toString() );
+	    v.replaceAll(toReplace," ");
+	    charElement.setText(v.trim());
+
+        }
+        if ( parent != null ) {
+            charElement = parent.addContent(charElement);
+        }
+
+
+        return charElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Byte.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Byte object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Byte element ...
+        // ----------------------
+        Element byteElement = new Element(TagNames.Elements.BYTE);
+        byteElement.setText(object.toString());
+        if ( parent != null ) {
+            byteElement = parent.addContent(byteElement);
+        }
+
+        return byteElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Boolean.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Boolean object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Boolean element ...
+        // ----------------------
+        Element booleanElement = new Element(TagNames.Elements.BOOLEAN);
+
+        if ( object.booleanValue() == true ) {
+            booleanElement.setText(TagNames.Values.TRUE);
+        } else {
+            booleanElement.setText(TagNames.Values.FALSE);
+        }
+
+        if ( parent != null ) {
+            booleanElement = parent.addContent(booleanElement);
+        }
+
+        return booleanElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Float.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Float object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Float element ...
+        // ----------------------
+        Element floatElement = new Element(TagNames.Elements.FLOAT);
+        floatElement.setText(object.toString());
+        if ( parent != null ) {
+            floatElement = parent.addContent(floatElement);
+        }
+
+        return floatElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Double.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Double object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Double element ...
+        // ----------------------
+        Element doubleElement = new Element(TagNames.Elements.DOUBLE);
+        doubleElement.setText(object.toString());
+        if ( parent != null ) {
+            doubleElement = parent.addContent(doubleElement);
+        }
+
+        return doubleElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the BigDecimal.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(BigDecimal object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the BigDecimal element ...
+        // ----------------------
+        Element bigDecimalElement = new Element(TagNames.Elements.BIGDECIMAL);
+        bigDecimalElement.setText(object.toString());
+        if ( parent != null ) {
+            bigDecimalElement = parent.addContent(bigDecimalElement);
+        }
+
+        return bigDecimalElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the BigInteger.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(BigInteger object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the BigInteger element ...
+        // ----------------------
+        Element bigIntegerElement = new Element(TagNames.Elements.BIGINTEGER);
+        bigIntegerElement.setText(object.toString());
+        if ( parent != null ) {
+            bigIntegerElement = parent.addContent(bigIntegerElement);
+        }
+
+        return bigIntegerElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the java.sql.Date.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(java.sql.Date object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the java.sql.Date element ...
+        // ----------------------
+        Element sqldateElement = new Element(TagNames.Elements.DATE);
+        sqldateElement.setText(object.toString());
+        if ( parent != null ) {
+            sqldateElement = parent.addContent(sqldateElement);
+        }
+
+        return sqldateElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Time.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Time object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Time element ...
+        // ----------------------
+        Element timeElement = new Element(TagNames.Elements.TIME);
+        timeElement.setText(object.toString());
+        if ( parent != null ) {
+            timeElement = parent.addContent(timeElement);
+        }
+
+        return timeElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Timestamp.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Timestamp object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Timestamp element ...
+        // ----------------------
+        Element timestampElement = new Element(TagNames.Elements.TIMESTAMP);
+        timestampElement.setText(object.toString());
+        if ( parent != null ) {
+            timestampElement = parent.addContent(timestampElement);
+        }
+
+        return timestampElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Integer.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Integer object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Integer element ...
+        // ----------------------
+        Element integerElement = new Element(TagNames.Elements.INTEGER);
+        integerElement.setText(object.toString());
+        if ( parent != null ) {
+            integerElement = parent.addContent(integerElement);
+        }
+
+        return integerElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Long.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Long object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Long element ...
+        // ----------------------
+        Element longElement = new Element(TagNames.Elements.LONG);
+        longElement.setText(object.toString());
+        if ( parent != null ) {
+            longElement = parent.addContent(longElement);
+        }
+
+        return longElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the Short.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Short object, Element parent) throws JDOMException {
+
+        // ----------------------
+        // Create the Long element ...
+        // ----------------------
+        Element shortElement = new Element(TagNames.Elements.SHORT);
+        shortElement.setText(object.toString());
+        if ( parent != null ) {
+            shortElement = parent.addContent(shortElement);
+        }
+
+        return shortElement;
+    }
+
+    /**
+     * Produce an XML message for an instance of the SQLException.
+     * <br>
+     * @param object the instance for which the message is to be produced.
+     * @param parent the XML element that is to be the parent of the produced XML message.
+     * @return the root element of the XML segment that was produced.
+     * @exception JDOMException if there is an error producing the message.
+     */
+    private Element produceMsg(Throwable object, Element parent) throws JDOMException {
+
+        Throwable exception = object;
+        Element exceptionElement = null;
+
+        // --------------------------------
+        // Create the Exception element ...
+        // --------------------------------
+        exceptionElement = new Element(TagNames.Elements.EXCEPTION);
+
+        // ---------------------------------
+        // Add the ExceptionType element ...
+        // ---------------------------------
+        String className = exception.getClass().getName();
+        int index = className.lastIndexOf('.');
+        if ( index != -1 && (++index) < className.length() ) {
+            className = className.substring(index);
+        }
+        Element typeElement = new Element(TagNames.Elements.EXCEPTION_TYPE);
+        typeElement.setText(className);
+        exceptionElement.addContent(typeElement);
+
+        // ---------------------------
+        // Add the Message element ...
+        // ---------------------------
+        Element messageElement = new Element(TagNames.Elements.MESSAGE);
+        messageElement.setText(StringUtil.removeChars(exception.getMessage(), new char[] {'\r'}));
+         
+        exceptionElement.addContent(messageElement);
+
+        // -------------------------
+        // Add the Class element ...
+        // -------------------------
+        Element classElement = new Element(TagNames.Elements.CLASS);
+        classElement.setText(exception.getClass().getName());
+        exceptionElement.addContent(classElement);
+
+        if ( parent != null ) {
+            exceptionElement = parent.addContent(exceptionElement);
+        }
+
+        return exceptionElement;
+    }
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,217 +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.test.client.impl;
-
-import java.io.File;
-import java.sql.ResultSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.core.util.SqlUtil;
-import org.teiid.test.client.ExpectedResults;
-import org.teiid.test.client.ctc.ResultsHolder;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.util.TestResultSetUtil;
-
-
-public class ExpectedResultsImpl implements ExpectedResults {
-
-    private static final int MAX_COL_WIDTH = 65;
-
-    protected Properties props;
-    protected int resultMode = -1;
-    protected String generateDir = null;
-    protected String querySetIdentifier = null;
-    protected String results_dir_loc = null;
-
-    protected Map<String, ResultsHolder> loadedResults = new HashMap<String, ResultsHolder>();
-
-    public ExpectedResultsImpl(String querySetIdentifier, Properties properties) {
-	this.props = properties;
-	this.querySetIdentifier = querySetIdentifier;
-
-	this.results_dir_loc = props.getProperty(PROP_EXPECTED_RESULTS_DIR_LOC,
-		"");
-
-	String expected_root_loc = this.props
-		.getProperty(PROP_EXPECTED_RESULTS_ROOT_DIR);
-
-	if (expected_root_loc != null) {
-	    File dir = new File(expected_root_loc, results_dir_loc);
-	    this.results_dir_loc = dir.getAbsolutePath();
-	}
-
-	TestLogger.logInfo("Expected results loc: " + this.results_dir_loc);
-    }
-
-    @Override
-    public boolean isExceptionExpected(String queryidentifier)
-	    throws QueryTestFailedException {
-	return false;
-    }
-
-    @Override
-    public String getQuerySetID() {
-	return this.querySetIdentifier;
-    }
-
-    @Override
-    public synchronized File getResultsFile(String queryidentifier)
-	    throws QueryTestFailedException {
-	return findExpectedResultsFile(queryidentifier, this.querySetIdentifier);
-
-    }
-
-    /**
-     * Compare the results of a query with those that were expected.
-     * 
-     * @param expectedResults
-     *            The expected results.
-     * @param results
-     *            The actual results - may be null if
-     *            <code>actualException</code>.
-     * @param actualException
-     *            The actual exception recieved durring query execution - may be
-     *            null if <code>results</code>.
-     * @param isOrdered
-     *            Are the actual results ordered?
-     * @param batchSize
-     *            Size of the batch(es) used in determining when the first batch
-     *            of results were read.
-     * @return The response time for comparing the first batch (sizes) of
-     *         resutls.
-     * @throws QueryTestFailedException
-     *             If comparison fails.
-     */
-    public Object compareResults(final String queryIdentifier, final String sql,
-	    final ResultSet resultSet, final Throwable actualException,
-	    final int testStatus, final boolean isOrdered, final int updateCnt,
-	    final boolean resultFromQuery) throws QueryTestFailedException {
-
-	File expectedResultsFile = getResultsFile(queryIdentifier);
-
-	List<?> results = null;
-	if (actualException != null) {
-	    try {
-		results = TestResultSetUtil.compareThrowable(
-			actualException, sql, expectedResultsFile, false);
-
-	    } catch (Throwable e) {
-		QueryTestFailedException t = new QueryTestFailedException(
-			e.getMessage());
-		t.initCause(e);
-		throw t;
-	    }
-	    
-	    if (results != null && results.size() > 0) {
-		return results;
-	    }
-	    
-	    return null;
-
-	}
-
-	// update sql or procedure(with no results) has no results set
-	if (!resultFromQuery) {
-
-	    if (SqlUtil.isUpdateSql(sql)) {
-		if (updateCnt == 0 && expectedResultsFile.length() > 0) {
-		    throw new QueryTestFailedException("Update cnt was zero: " + expectedResultsFile.getName());
-		}
-		if (updateCnt > 0 && expectedResultsFile.length() == 0) {
-		    throw new QueryTestFailedException(
-			    "Update cnt was greater than zero, but didnt expected any updates");
-		}
-
-	    } else {
-		if (expectedResultsFile.length() > 0) {
-		    throw new QueryTestFailedException("No results from query, but expected results");
-		}
-	    }
-	    
-	    
-	} else {
-
-	    try {
-		if (expectedResultsFile.length() == 0) {
-		    // if the expectedResult file is empty
-		    // and the result doesnt have a first row-meaning its empty
-		    // then this is good
-		    if (!resultSet.first()) {
-			throw new QueryTestFailedException(
-				"Expected results is empty, but query produced results");
-		    }
-		    return results;
-		} 
-		
-		resultSet.beforeFirst();
-
-		results = TestResultSetUtil.writeAndCompareResultSet(resultSet, sql,
-			MAX_COL_WIDTH, false, null, expectedResultsFile, false);
-
-	    } catch (QueryTestFailedException qe) {
-		throw qe;
-	    } catch (Throwable e) {
-		QueryTestFailedException t = new QueryTestFailedException(
-			e.getMessage());
-		t.initCause(e);
-		throw t;
-	    }
-
-	    
-	    if (results != null && results.size() > 0) {
-		return results;
-	    }
-	    
-	    return null;
-
-	}
-	
-	return results;
-
-    }
-
-    @Override
-    public Object getMetaData(String queryidentifier) {
-	// TODO Auto-generated method stub
-	return null;
-    }
-
-    private File findExpectedResultsFile(String queryIdentifier,
-	    String querySetIdentifier) throws QueryTestFailedException {
-	String resultFileName = queryIdentifier + ".txt"; //$NON-NLS-1$
-	File file = new File(results_dir_loc + "/" + querySetIdentifier,
-		resultFileName);
-	if (!file.exists()) {
-	    throw new QueryTestFailedException("Query results file "
-		    + file.getAbsolutePath() + " cannot be found");
-	}
-
-	return file;
-
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/client/impl/ExpectedResultsImpl.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,224 @@
+/*
+ * 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.test.client.impl;
+
+import java.io.File;
+import java.sql.ResultSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.teiid.core.util.SqlUtil;
+import org.teiid.test.client.ExpectedResults;
+import org.teiid.test.client.TestProperties;
+import org.teiid.test.client.ctc.ResultsHolder;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.util.TestResultSetUtil;
+
+
+public class ExpectedResultsImpl implements ExpectedResults {
+
+    private static final int MAX_COL_WIDTH = 65;
+
+    protected Properties props;
+    protected int resultMode = -1;
+    protected String generateDir = null;
+    protected String querySetIdentifier = null;
+    protected String results_dir_loc = null;
+
+    protected Map<String, ResultsHolder> loadedResults = new HashMap<String, ResultsHolder>();
+
+    public ExpectedResultsImpl(String querySetIdentifier, Properties properties) {
+	this.props = properties;
+	this.querySetIdentifier = querySetIdentifier;
+
+	this.results_dir_loc = props.getProperty(PROP_EXPECTED_RESULTS_DIR_LOC,
+		"");
+
+	String expected_root_loc = this.props
+		.getProperty(PROP_EXPECTED_RESULTS_ROOT_DIR);
+
+	if (expected_root_loc != null) {
+	    File dir = new File(expected_root_loc, results_dir_loc);
+	    this.results_dir_loc = dir.getAbsolutePath();
+	}
+
+	TestLogger.logInfo("Expected results loc: " + this.results_dir_loc);
+    }
+
+    @Override
+    public boolean isExceptionExpected(String queryidentifier)
+	    throws QueryTestFailedException {
+	return false;
+    }
+    
+	public boolean isExpectedResultsNeeded() {
+    	return true;
+
+	}
+
+
+    @Override
+    public String getQuerySetID() {
+	return this.querySetIdentifier;
+    }
+
+    @Override
+    public synchronized File getResultsFile(String queryidentifier)
+	    throws QueryTestFailedException {
+	return findExpectedResultsFile(queryidentifier, this.querySetIdentifier);
+
+    }
+
+    /**
+     * Compare the results of a query with those that were expected.
+     * 
+     * @param expectedResults
+     *            The expected results.
+     * @param results
+     *            The actual results - may be null if
+     *            <code>actualException</code>.
+     * @param actualException
+     *            The actual exception recieved durring query execution - may be
+     *            null if <code>results</code>.
+     * @param isOrdered
+     *            Are the actual results ordered?
+     * @param batchSize
+     *            Size of the batch(es) used in determining when the first batch
+     *            of results were read.
+     * @return The response time for comparing the first batch (sizes) of
+     *         resutls.
+     * @throws QueryTestFailedException
+     *             If comparison fails.
+     */
+    public Object compareResults(final String queryIdentifier, final String sql,
+	    final ResultSet resultSet, final Throwable actualException,
+	    final int testStatus, final boolean isOrdered, final int updateCnt,
+	    final boolean resultFromQuery) throws QueryTestFailedException {
+
+	File expectedResultsFile = getResultsFile(queryIdentifier);
+
+	List<?> results = null;
+	if (actualException != null) {
+	    try {
+		results = TestResultSetUtil.compareThrowable(
+			actualException, sql, expectedResultsFile, false);
+
+	    } catch (Throwable e) {
+		QueryTestFailedException t = new QueryTestFailedException(
+			e.getMessage());
+		t.initCause(e);
+		throw t;
+	    }
+	    
+	    if (results != null && results.size() > 0) {
+		return results;
+	    }
+	    
+	    return null;
+
+	}
+
+	// update sql or procedure(with no results) has no results set
+	if (!resultFromQuery) {
+
+	    if (SqlUtil.isUpdateSql(sql)) {
+		if (updateCnt == 0 && expectedResultsFile.length() > 0) {
+		    throw new QueryTestFailedException("Update cnt was zero: " + expectedResultsFile.getName());
+		}
+		if (updateCnt > 0 && expectedResultsFile.length() == 0) {
+		    throw new QueryTestFailedException(
+			    "Update cnt was greater than zero, but didnt expected any updates");
+		}
+
+	    } else {
+		if (expectedResultsFile.length() > 0) {
+		    throw new QueryTestFailedException("No results from query, but expected results");
+		}
+	    }
+	    
+	    
+	} else {
+
+	    try {
+		if (expectedResultsFile.length() == 0) {
+		    // if the expectedResult file is empty
+		    // and the result doesnt have a first row-meaning its empty
+		    // then this is good
+		    if (!resultSet.first()) {
+			throw new QueryTestFailedException(
+				"Expected results is empty, but query produced results");
+		    }
+		    return results;
+		} 
+		
+		resultSet.beforeFirst();
+
+		results = TestResultSetUtil.writeAndCompareResultSet(resultSet, sql,
+			MAX_COL_WIDTH, false, null, expectedResultsFile, false);
+
+	    } catch (QueryTestFailedException qe) {
+		throw qe;
+	    } catch (Throwable e) {
+		QueryTestFailedException t = new QueryTestFailedException(
+			e.getMessage());
+		t.initCause(e);
+		throw t;
+	    }
+
+	    
+	    if (results != null && results.size() > 0) {
+		return results;
+	    }
+	    
+	    return null;
+
+	}
+	
+	return results;
+
+    }
+
+    @Override
+    public Object getMetaData(String queryidentifier) {
+	// TODO Auto-generated method stub
+	return null;
+    }
+
+    private File findExpectedResultsFile(String queryIdentifier,
+	    String querySetIdentifier) throws QueryTestFailedException {
+	String resultFileName = queryIdentifier + ".txt"; //$NON-NLS-1$
+	File file = new File(results_dir_loc + "/" + querySetIdentifier,
+		resultFileName);
+	if (!file.exists()) {
+	    throw new QueryTestFailedException("Query results file "
+		    + file.getAbsolutePath() + " cannot be found");
+	}
+
+	return file;
+
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2000-2007 MetaMatrix, Inc.
- * All rights reserved.
- */
-package org.teiid.test.framework;
-
-import org.teiid.core.util.StringUtil;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-
-
-public abstract class TransactionContainer {
-
-    private String testClassName = null;
-
-
-    protected TransactionContainer() {
-	
-    }
-
-
-    protected void before(TransactionQueryTestCase test) {
-    }
-
-    protected void after(TransactionQueryTestCase test) {
-    }
-
-    public void runTransaction(TransactionQueryTestCase test) {
-
-	this.testClassName = StringUtil.getLastToken(test.getClass().getName(),
-		".");
-
-	try {
-	    detail("Start transaction test: " + test.getTestName());
-
-	    try {
-
-		test.setup();
-
-	    } catch (TransactionRuntimeException tre) {  
-			if (!test.exceptionExpected()) {
-			    tre.printStackTrace();
-			}
-        		throw tre;
-	    } catch (Throwable e) {
-		if (!test.exceptionExpected()) {
-		    e.printStackTrace();
-		}
-		throw new TransactionRuntimeException(e.getMessage());
-	    }
-
-	    runTest(test);
-
-	    detail("Completed transaction test: " + test.getTestName());
-
-	} finally {
-	    debug("	test.cleanup");
-
-		test.cleanup();
-
-	}
-
-    }
-
-    protected void runTest(TransactionQueryTestCase test) {
-	debug("Start runTest: " + test.getTestName());
-
-
-	    debug("	before(test)");
-
-	    before(test);
-	    debug("	test.before");
-
-	    test.before();
-
-	    debug("	test.testcase");
-	    
-	try {
-
-
-	    // run the test
-	    test.testCase();
-	    
-	} catch (Throwable e) {
-	    // this catches the non-SQLExceptions that the AbstractQueryTest catches.
-	    // And therefore, the exception needs to be set as an application exception,
-	    // considered outside the bounds of the normal sqlexceptions.
-	    test.setApplicationException(e);
-
-	}
-	
-	    debug("	test.after");
-
-	    test.after();
-	    debug("	after(test)");
-
-	    after(test);
-
-	    debug("End runTest: " + test.getTestName());
-
-
-
-
-    }
-
-
-    protected void debug(String message) {
-	TestLogger.logDebug("[" + this.testClassName + "] " + message);
-    }
-
-    protected void detail(String message) {
-	TestLogger.log("[" + this.testClassName + "] " + message);
-    }
-
-    protected boolean done() {
-	return true;
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2000-2007 MetaMatrix, Inc.
+ * All rights reserved.
+ */
+package org.teiid.test.framework;
+
+import org.teiid.core.util.StringUtil;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+
+
+public abstract class TransactionContainer {
+
+    private String testClassName = null;
+
+
+    protected TransactionContainer() {
+	
+    }
+
+
+    protected void before(TransactionQueryTestCase test) {
+    }
+
+    protected void after(TransactionQueryTestCase test) {
+    }
+
+    public void runTransaction(TransactionQueryTestCase test) {
+
+	this.testClassName = StringUtil.getLastToken(test.getClass().getName(),
+		".");
+
+	try {
+	    debug("Start transaction test: " + test.getTestName());
+
+	    try {
+
+		test.setup();
+
+	    } catch (TransactionRuntimeException tre) {  
+			if (!test.exceptionExpected()) {
+			    tre.printStackTrace();
+			}
+        		throw tre;
+	    } catch (Throwable e) {
+		if (!test.exceptionExpected()) {
+		    e.printStackTrace();
+		}
+		throw new TransactionRuntimeException(e.getMessage());
+	    }
+
+	    runTest(test);
+
+	    debug("Completed transaction test: " + test.getTestName());
+
+	} finally {
+	    debug("	test.cleanup");
+
+		test.cleanup();
+
+	}
+
+    }
+
+    protected void runTest(TransactionQueryTestCase test) {
+	debug("Start runTest: " + test.getTestName());
+
+
+	    debug("	before(test)");
+
+	    before(test);
+	    debug("	test.before");
+
+	    test.before();
+
+	    debug("	test.testcase");
+	    
+	try {
+
+
+	    // run the test
+	    test.testCase();
+	    
+	} catch (Throwable e) {
+	    // this catches the non-SQLExceptions that the AbstractQueryTest catches.
+	    // And therefore, the exception needs to be set as an application exception,
+	    // considered outside the bounds of the normal sqlexceptions.
+	    test.setApplicationException(e);
+
+	}
+	
+	    debug("	test.after");
+
+	    test.after();
+	    debug("	after(test)");
+
+	    after(test);
+
+	    debug("End runTest: " + test.getTestName());
+
+
+
+
+    }
+
+
+    protected void debug(String message) {
+	TestLogger.logDebug("[" + this.testClassName + "] " + message);
+    }
+
+    protected void detail(String message) {
+	TestLogger.log("[" + this.testClassName + "] " + message);
+    }
+
+    protected boolean done() {
+	return true;
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2000-2007 MetaMatrix, Inc.
- * All rights reserved.
- */
-package org.teiid.test.framework.connection;
-
-import java.util.Properties;
-
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.ConfigPropertyNames;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.datasource.DataSourceFactory;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-
-/**
- * The ConnectionStrategyFactory is responsible for creating a connection strategy that is to be used to provide the type of 
- * connection.
- * @author vanhalbert
- *
- */
-public class ConnectionStrategyFactory {
-	
-    
-	    public static ConnectionStrategy createConnectionStrategy()  {
-
-	    	ConfigPropertyLoader configLoader = ConfigPropertyLoader.getInstance();
-		
-			ConnectionStrategy strategy = null;
-	     	Properties props = configLoader.getProperties();
-           
-	        String type = props.getProperty(ConfigPropertyNames.CONNECTION_TYPE, ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION);
-	        if (type == null) {
-	        	throw new TransactionRuntimeException("Property " + ConfigPropertyNames.CONNECTION_TYPE + " was specified");
-	        }
-	        
-	        try {
-	        
-        	        if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION)) {
-        	        	// pass in null to create new strategy
-        	                strategy = new DriverConnection(props);
-        	                TestLogger.log("Created Driver Strategy");
-        	        }
-        	        else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DATASOURCE_CONNECTION)) {
-        	            strategy = new DataSourceConnection(props);
-        	            TestLogger.log("Created DataSource Strategy");
-        	        }
-        	        else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.JNDI_CONNECTION)) {
-        	            strategy = new JEEConnection(props);
-        	            TestLogger.log("Created JEE Strategy");
-        	        }   
-        	        
-        	        if (strategy == null) {
-        	        	new TransactionRuntimeException("Invalid property value for " + ConfigPropertyNames.CONNECTION_TYPE + " is " + type );
-        	        }
-        	        // call configure here because this is creating the connection to Teiid
-        	        // direct connections to the datasource use the static call directly to create strategy and don't need to configure
-        	    	strategy.configure();
-        	        return strategy;
-	        } catch (Exception e) {
-	            throw new TransactionRuntimeException(e);
-	        }
-
-	    }	    
-	    
-		public static void main(String[] args) {
-			//NOTE: to run this test to validate the DataSourceMgr, do the following:
-			//   ---  need 3 datasources,   Oracle, SqlServer and 1 other
-			
-			ConfigPropertyLoader config = ConfigPropertyLoader.getInstance();
-			
-			new DataSourceFactory(config);
-
-		}
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2000-2007 MetaMatrix, Inc.
+ * All rights reserved.
+ */
+package org.teiid.test.framework.connection;
+
+import java.util.Properties;
+
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.datasource.DataSourceFactory;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+
+/**
+ * The ConnectionStrategyFactory is responsible for creating a connection strategy that is to be used to provide the type of 
+ * connection.
+ * @author vanhalbert
+ *
+ */
+public class ConnectionStrategyFactory {
+	
+    
+	    public static ConnectionStrategy createConnectionStrategy()  {
+
+	    	ConfigPropertyLoader configLoader = ConfigPropertyLoader.getInstance();
+		
+			ConnectionStrategy strategy = null;
+	     	Properties props = configLoader.getProperties();
+           
+	        String type = props.getProperty(ConfigPropertyNames.CONNECTION_TYPE, ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION);
+	        if (type == null) {
+	        	throw new TransactionRuntimeException("Property " + ConfigPropertyNames.CONNECTION_TYPE + " was specified");
+	        }
+	        
+	        try {
+	        
+        	        if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION)) {
+        	        	// pass in null to create new strategy
+        	                strategy = new DriverConnection(props);
+        	                TestLogger.logDebug("Created Driver Strategy");
+        	        }
+        	        else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DATASOURCE_CONNECTION)) {
+        	            strategy = new DataSourceConnection(props);
+        	            TestLogger.logDebug("Created DataSource Strategy");
+        	        }
+        	        else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.JNDI_CONNECTION)) {
+        	            strategy = new JEEConnection(props);
+        	            TestLogger.logDebug("Created JEE Strategy");
+        	        }   
+        	        
+        	        if (strategy == null) {
+        	        	new TransactionRuntimeException("Invalid property value for " + ConfigPropertyNames.CONNECTION_TYPE + " is " + type );
+        	        }
+        	        // call configure here because this is creating the connection to Teiid
+        	        // direct connections to the datasource use the static call directly to create strategy and don't need to configure
+        	    	strategy.configure();
+        	        return strategy;
+	        } catch (Exception e) {
+	            throw new TransactionRuntimeException(e);
+	        }
+
+	    }	    
+	    
+		public static void main(String[] args) {
+			//NOTE: to run this test to validate the DataSourceMgr, do the following:
+			//   ---  need 3 datasources,   Oracle, SqlServer and 1 other
+			
+			ConfigPropertyLoader config = ConfigPropertyLoader.getInstance();
+			
+			new DataSourceFactory(config);
+
+		}
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,305 +0,0 @@
-/*
- * Copyright (c) 2000-2007 MetaMatrix, Inc.
- * All rights reserved.
- */
-package org.teiid.test.framework.datasource;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.core.util.PropertiesUtils;
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.ConfigPropertyNames;
-import org.teiid.test.framework.TestLogger;
-import org.teiid.test.framework.exception.QueryTestFailedException;
-import org.teiid.test.framework.exception.TransactionRuntimeException;
-
-
-/**
- * The DataSourceMgr is responsible for loading and managing the datasources
- * defined by the datasource connection properties file. There's only a need to
- * load the set of available datasources once for the duration of the entire
- * test suite. And it will maintain one {@link DataSource} for each
- * connection.properties file that it finds.
- * 
- * @author vanhalbert
- * 
- */
-public class DataSourceMgr {
-
-    private static DataSourceMgr _instance = null;
-    
-    /**
-     * Defines the default location where the datasource files will be found.
-     * An override can be specified by setting the property {@link ConfigPropertyNames#OVERRIDE_DATASOURCES_LOC}.
-     */
-    public static final String DEFAULT_DATASOURCES_LOC="./src/main/resources/datasources/";
-    
-    /**
-     * When run from maven, the {@link ConfigPropertyNames#OVERRIDE_DATASOURCES_LOC} will be assigned
-     * to this value because of its a place holder for when a user does set the vm argument.
-     */
-    private static final String UNASSIGNEDDSLOC="${";
-
-    private Map<String, DataSource> allDatasourcesMap = new HashMap<String, DataSource>(); // key
-											   // =
-											   // datasource
-											   // name
-
-    // map of the datasources assigned to with model
-    // because only one VDB (Transactions) is used, then this mapping can live
-    // for the
-    // duration of all tests
-    private Map<String, DataSource> modelToDatasourceMap = new HashMap<String, DataSource>(); // key
-											      // =
-											      // modelname
-    
-    private DataSourceFactory dsfactory = null;
-
-
-    private DataSourceMgr() {
-	
-    }
-
-    public static synchronized DataSourceMgr getInstance() {
-	if (_instance == null) {
-	    _instance = new DataSourceMgr();
-	    try {
-		_instance.loadDataSourceMappings();
-	    } catch (QueryTestFailedException e) {
-		throw new TransactionRuntimeException(e);
-	    } catch (TransactionRuntimeException e) {
-		throw e;
-	    }
-
-	}
-	return _instance;
-    }
-    
-    private static synchronized void reset() {
-	_instance = null;
-    }
-
-    public Map<String, DataSource> getDataSources() {
-	Map<String, DataSource> ds = new HashMap<String, DataSource>(
-		allDatasourcesMap.size());
-	ds.putAll(allDatasourcesMap);
-	return ds;
-    }
-
-    public int numberOfAvailDataSources() {
-	return allDatasourcesMap.size();
-    }
-
-    @SuppressWarnings("deprecation")
-    public DataSource getDataSource(String modelname) {
-	if (modelToDatasourceMap.containsKey(modelname)) {
-	    return modelToDatasourceMap.get(modelname);
-	}
-	
-	try {
-	    DataSource ds = dsfactory.getDatasource( modelname);
-	    
-		if (ds == null) {
-		    printAllDatasources();
-		    
-		    try {
-			Thread.sleep(100000);
-		    } catch (InterruptedException e) {
-		    }
-		   Thread.currentThread().getThreadGroup().stop();
-		   
-		   
-//			throw new QueryTestFailedException(
-//					"Unable to assign a datasource for model "
-//							+ modelname );
-
-		}
-	    modelToDatasourceMap.put(modelname, ds);
-	    return ds;
-	} catch (QueryTestFailedException e) {
-	    throw new TransactionRuntimeException(e);
-	}
-    }
-    
-    private void printAllDatasources() {
-	Iterator<String> it=allDatasourcesMap.keySet().iterator();
-	while(it.hasNext()) {
-	    String key = it.next();
-	    DataSource ds = allDatasourcesMap.get(key);
-	    TestLogger.log("DataSource: " + ds.getName());
-	    
-	}
-
-    }
-
-    
-    public void shutdown() {
-	 TestLogger.log("Shutting down data sources");
-	 
-	if (allDatasourcesMap != null && allDatasourcesMap.size() > 0) {
-		Iterator<String> it=allDatasourcesMap.keySet().iterator();
-		while(it.hasNext()) {
-		    String key = it.next();
-		    DataSource ds = allDatasourcesMap.get(key);
-		    try {
-			ds.shutdown();
-		    } catch (Throwable t) {
-			
-		    }
-		}
-		
-		allDatasourcesMap.clear();
-	}
-	
-	if (modelToDatasourceMap != null || modelToDatasourceMap.size() > 0) {
-		Iterator<String> it=modelToDatasourceMap.keySet().iterator();
-		while(it.hasNext()) {
-		    String key = it.next();
-		    DataSource ds = modelToDatasourceMap.get(key);
-		    try {
-			ds.shutdown();
-		    } catch (Throwable t) {
-			
-		    }
-		}
-		
-		modelToDatasourceMap.clear();
-	}
-	
-	if (dsfactory != null) dsfactory.cleanup();
-	
-	DataSourceMgr.reset();
-	
-    }
-
-    public void setDataSource(String modelName, DataSource ds) {
-	modelToDatasourceMap.put(modelName, ds);
-    }
-
-    private void loadDataSourceMappings() throws QueryTestFailedException {
-	if (ConfigPropertyLoader.getInstance().isDataStoreDisabled()) {
-	    TestLogger.log("DataStore usage has been disabled");
-	    return;
-	}
-
-	String dsloc = ConfigPropertyLoader.getInstance().getProperty(ConfigPropertyNames.OVERRIDE_DATASOURCES_LOC);
-	
-	if (dsloc == null || dsloc.indexOf(UNASSIGNEDDSLOC) > -1) {
-	    dsloc = DEFAULT_DATASOURCES_LOC;
-	    TestLogger.log("Using default datasource loc: " +dsloc);
-	} else {
-	    TestLogger.log("Using override for datasources loc: " + dsloc);
-	}
-	
-	File[] dirs = findAllChildDirectories(dsloc);
-	if (dirs == null || dirs.length == 0) {
-	    throw new TransactionRuntimeException(
-		    "No datasource directories found at location "
-			    + dsloc);
-	}
-	for (int i = 0; i < dirs.length; i++) {
-	    File d = dirs[i];
-
-	    addDataSource(d, allDatasourcesMap);
-
-	}
-
-	if (allDatasourcesMap == null || allDatasourcesMap.isEmpty()) {
-	    throw new TransactionRuntimeException(
-		    "Error: No Datasources were loaded.");
-	} else if (allDatasourcesMap.size() < 2) {
-	    throw new TransactionRuntimeException(
-	    	"Error: Must load 2 Datasources, only 1 was found.");
- 
-	}
-
-	TestLogger.logDebug("Number of total datasource mappings loaded "
-		+ allDatasourcesMap.size());
-	
-	
-	dsfactory = new DataSourceFactory(ConfigPropertyLoader.getInstance());
-	dsfactory.config(this);
-
-    }
-
-    /**
-     * Returns a <code>File</code> array that will contain all the directories
-     * that exist in the directory
-     * 
-     * @return File[] of directories in the directory
-     */
-    private static File[] findAllChildDirectories(String dir) {
-
-	// Find all files in the specified directory
-	File mfile = new File(dir);
-
-	File modelsDirFile = null;
-	try {
-	    modelsDirFile = new File(mfile.getCanonicalPath());
-	} catch (IOException e) {
-	    // TODO Auto-generated catch block
-	    e.printStackTrace();
-	}
-	if (!modelsDirFile.exists()) {
-	    return null;
-	}
-	FileFilter fileFilter = new FileFilter() {
-
-	    public boolean accept(File file) {
-		if (file.isDirectory()) {
-		    return true;
-		}
-
-		return false;
-	    }
-	};
-
-	File[] modelFiles = modelsDirFile.listFiles(fileFilter);
-
-	return modelFiles;
-
-    }
-
-    private void addDataSource(File datasourcedir, 
-	    Map<String, DataSource> datasources) {
-	
-	File dsfile = new File(datasourcedir, "connection.properties");
-	
-	if (!dsfile.exists()) {
-	    return;
-	}
-
-	Properties dsprops = loadProperties(dsfile);
-
-	if (dsprops != null) {
-
-	    DataSource ds = new DataSource(datasourcedir.getName(), "dsgroup", dsprops);
-	    datasources.put(ds.getName(), ds);
-	    TestLogger.log("Loaded datasource " + ds.getName());
-
-	}
-
-    }
-
-    private static Properties loadProperties(File dsfile) {
-	Properties props = null;
-
-	try {
-	    
-	    props = PropertiesUtils.load(dsfile.getAbsolutePath());
-	    return props;
-	    
-	} catch (IOException e) {
-	    throw new TransactionRuntimeException(
-		    "Error loading properties from file '" + dsfile.getAbsolutePath() + "'"
-			    + e.getMessage());
-	}
-    }
-
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java (from rev 2774, trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 2000-2007 MetaMatrix, Inc.
+ * All rights reserved.
+ */
+package org.teiid.test.framework.datasource;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+
+import org.teiid.core.util.PropertiesUtils;
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.TestLogger;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
+
+
+/**
+ * The DataSourceMgr is responsible for loading and managing the datasources
+ * defined by the datasource connection properties file. There's only a need to
+ * load the set of available datasources once for the duration of the entire
+ * test suite. And it will maintain one {@link DataSource} for each
+ * connection.properties file that it finds.
+ * 
+ * @author vanhalbert
+ * 
+ */
+public class DataSourceMgr {
+
+    private static DataSourceMgr _instance = null;
+    
+    /**
+     * Defines the default location where the datasource files will be found.
+     * An override can be specified by setting the property {@link ConfigPropertyNames#OVERRIDE_DATASOURCES_LOC}.
+     */
+    public static final String DEFAULT_DATASOURCES_LOC="./src/main/resources/datasources/";
+    
+    /**
+     * When run from maven, the {@link ConfigPropertyNames#OVERRIDE_DATASOURCES_LOC} will be assigned
+     * to this value because of its a place holder for when a user does set the vm argument.
+     */
+    private static final String UNASSIGNEDDSLOC="${";
+
+    private Map<String, DataSource> allDatasourcesMap = new HashMap<String, DataSource>(); // key
+											   // =
+											   // datasource
+											   // name
+
+    // map of the datasources assigned to with model
+    // because only one VDB (Transactions) is used, then this mapping can live
+    // for the
+    // duration of all tests
+    private Map<String, DataSource> modelToDatasourceMap = new HashMap<String, DataSource>(); // key
+											      // =
+											      // modelname
+    
+    private DataSourceFactory dsfactory = null;
+
+
+    private DataSourceMgr() {
+	
+    }
+
+    public static synchronized DataSourceMgr getInstance() {
+	if (_instance == null) {
+	    _instance = new DataSourceMgr();
+	    try {
+		_instance.loadDataSourceMappings();
+	    } catch (QueryTestFailedException e) {
+		throw new TransactionRuntimeException(e);
+	    } catch (TransactionRuntimeException e) {
+		throw e;
+	    }
+
+	}
+	return _instance;
+    }
+    
+    private static synchronized void reset() {
+	_instance = null;
+    }
+
+    public Map<String, DataSource> getDataSources() {
+	Map<String, DataSource> ds = new HashMap<String, DataSource>(
+		allDatasourcesMap.size());
+	ds.putAll(allDatasourcesMap);
+	return ds;
+    }
+
+    public int numberOfAvailDataSources() {
+	return allDatasourcesMap.size();
+    }
+
+    @SuppressWarnings("deprecation")
+    public DataSource getDataSource(String modelname) {
+	if (modelToDatasourceMap.containsKey(modelname)) {
+	    return modelToDatasourceMap.get(modelname);
+	}
+	
+	try {
+	    DataSource ds = dsfactory.getDatasource( modelname);
+	    
+		if (ds == null) {
+		    printAllDatasources();
+		    
+		    try {
+			Thread.sleep(100000);
+		    } catch (InterruptedException e) {
+		    }
+		   Thread.currentThread().getThreadGroup().stop();
+		   
+		   
+//			throw new QueryTestFailedException(
+//					"Unable to assign a datasource for model "
+//							+ modelname );
+
+		}
+	    modelToDatasourceMap.put(modelname, ds);
+	    return ds;
+	} catch (QueryTestFailedException e) {
+	    throw new TransactionRuntimeException(e);
+	}
+    }
+    
+    private void printAllDatasources() {
+	Iterator<String> it=allDatasourcesMap.keySet().iterator();
+	while(it.hasNext()) {
+	    String key = it.next();
+	    DataSource ds = allDatasourcesMap.get(key);
+	    TestLogger.log("DataSource: " + ds.getName());
+	    
+	}
+
+    }
+
+    
+    public void shutdown() {
+	 TestLogger.log("Shutting down data sources");
+	 
+	if (allDatasourcesMap != null && allDatasourcesMap.size() > 0) {
+		Iterator<String> it=allDatasourcesMap.keySet().iterator();
+		while(it.hasNext()) {
+		    String key = it.next();
+		    DataSource ds = allDatasourcesMap.get(key);
+		    try {
+			ds.shutdown();
+		    } catch (Throwable t) {
+			
+		    }
+		}
+		
+		allDatasourcesMap.clear();
+	}
+	
+	if (modelToDatasourceMap != null || modelToDatasourceMap.size() > 0) {
+		Iterator<String> it=modelToDatasourceMap.keySet().iterator();
+		while(it.hasNext()) {
+		    String key = it.next();
+		    DataSource ds = modelToDatasourceMap.get(key);
+		    try {
+			ds.shutdown();
+		    } catch (Throwable t) {
+			
+		    }
+		}
+		
+		modelToDatasourceMap.clear();
+	}
+	
+	if (dsfactory != null) dsfactory.cleanup();
+	
+	DataSourceMgr.reset();
+	
+    }
+
+    public void setDataSource(String modelName, DataSource ds) {
+	modelToDatasourceMap.put(modelName, ds);
+    }
+
+    private void loadDataSourceMappings() throws QueryTestFailedException {
+	if (ConfigPropertyLoader.getInstance().isDataStoreDisabled()) {
+	    TestLogger.logDebug("DataStore usage has been disabled");
+	    return;
+	}
+
+	String dsloc = ConfigPropertyLoader.getInstance().getProperty(ConfigPropertyNames.OVERRIDE_DATASOURCES_LOC);
+	
+	if (dsloc == null || dsloc.indexOf(UNASSIGNEDDSLOC) > -1) {
+	    dsloc = DEFAULT_DATASOURCES_LOC;
+	    TestLogger.logDebug("Using default datasource loc: " +dsloc);
+	} else {
+	    TestLogger.logDebug("Using override for datasources loc: " + dsloc);
+	}
+	
+	File[] dirs = findAllChildDirectories(dsloc);
+	if (dirs == null || dirs.length == 0) {
+	    throw new TransactionRuntimeException(
+		    "No datasource directories found at location "
+			    + dsloc);
+	}
+	for (int i = 0; i < dirs.length; i++) {
+	    File d = dirs[i];
+
+	    addDataSource(d, allDatasourcesMap);
+
+	}
+
+	if (allDatasourcesMap == null || allDatasourcesMap.isEmpty()) {
+	    throw new TransactionRuntimeException(
+		    "Error: No Datasources were loaded.");
+	} else if (allDatasourcesMap.size() < 2) {
+	    throw new TransactionRuntimeException(
+	    	"Error: Must load 2 Datasources, only 1 was found.");
+ 
+	}
+
+	TestLogger.logDebug("Number of total datasource mappings loaded "
+		+ allDatasourcesMap.size());
+	
+	
+	dsfactory = new DataSourceFactory(ConfigPropertyLoader.getInstance());
+	dsfactory.config(this);
+
+    }
+
+    /**
+     * Returns a <code>File</code> array that will contain all the directories
+     * that exist in the directory
+     * 
+     * @return File[] of directories in the directory
+     */
+    private static File[] findAllChildDirectories(String dir) {
+
+	// Find all files in the specified directory
+	File mfile = new File(dir);
+
+	File modelsDirFile = null;
+	try {
+	    modelsDirFile = new File(mfile.getCanonicalPath());
+	} catch (IOException e) {
+	    // TODO Auto-generated catch block
+	    e.printStackTrace();
+	}
+	if (!modelsDirFile.exists()) {
+	    return null;
+	}
+	FileFilter fileFilter = new FileFilter() {
+
+	    public boolean accept(File file) {
+		if (file.isDirectory()) {
+		    return true;
+		}
+
+		return false;
+	    }
+	};
+
+	File[] modelFiles = modelsDirFile.listFiles(fileFilter);
+
+	return modelFiles;
+
+    }
+
+    private void addDataSource(File datasourcedir, 
+	    Map<String, DataSource> datasources) {
+	
+	File dsfile = new File(datasourcedir, "connection.properties");
+	
+	if (!dsfile.exists()) {
+	    return;
+	}
+
+	Properties dsprops = loadProperties(dsfile);
+
+	if (dsprops != null) {
+
+	    DataSource ds = new DataSource(datasourcedir.getName(), "dsgroup", dsprops);
+	    datasources.put(ds.getName(), ds);
+	    TestLogger.logDebug("Loaded datasource " + ds.getName());
+
+	}
+
+    }
+
+    private static Properties loadProperties(File dsfile) {
+	Properties props = null;
+
+	try {
+	    
+	    props = PropertiesUtils.load(dsfile.getAbsolutePath());
+	    return props;
+	    
+	} catch (IOException e) {
+	    throw new TransactionRuntimeException(
+		    "Error loading properties from file '" + dsfile.getAbsolutePath() + "'"
+			    + e.getMessage());
+	}
+    }
+
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml
===================================================================
--- trunk/test-integration/db/src/main/resources/ctc_tests/ctc.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,303 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project name="ctc" default="main" >
-	
-	
-	<taskdef resource="net/sf/antcontrib/antlib.xml">
-	  <classpath>
-	  	<pathelement path="${maven.runtime.classpath}" />
-	  </classpath>
-	</taskdef>
-	
-	<target name="main" depends="init, is.config.file, set.default.config.file, set.config.file" 
-		if="" unless="" description="create all property files">
-		<echo>PROJECT DIRECTORY: ${proj_dir}</echo>
-		
-		<antcall target="run.all.test" inheritall="true" />
-		<antcall target="run.single.test" inheritall="true" />
-		
-		<available file="${ERROR_FILE}" property="error.flagged"/>
-
-		<fail if="error.flagged" message="One or more ctc tests failed" />
-	
-	</target>
-
-	<target name="init" depends="set.os, set.win, set.linux" >
-		
-		
-		<property name="ERROR_FILE" value="${root_output}/ERROR_FOUND.txt" />
-
-		<available file="${scenario.dir}" type="dir" property="scenario.dir.exist"/>
-		<fail unless="scenario.dir.exist" message="Scenario directory ${scenario.dir} does not exist or was not specified." />
-
-		<available file="${queryset.artifacts.dir}" type="dir" property="queryset.dir.exist"/>
-		<fail unless="queryset.dir.exist" message="QuerySet directory ${queryset.artifacts.dir} does not exist or was not specified." />
-		
-		<condition property="single">
-			<available file="${scenario.dir}/${scenario.file}"  />
-		</condition>
-		
-		<delete file="${ERROR_FILE}"/>
-
-	</target>
-	
-	<target name="set.win"
-		if="WinOS">
-		
-
-		<pathconvert targetos="unix" property="proj_dir" >
-		   		 <map from="\" to="/"/>
-		   		<path location="${proj.dir}"/>
-			 </pathconvert>
-		
-		<property name="root_output" value="${proj_dir}/bulk-query-tests" />
-
-	</target>
-	
-	<target name="set.linux"
-		if="UnixOS">
-		<property name="root_output" value="${proj.dir}/bulk-query-tests" />
-		<property name="proj_dir" value="${proj.dir}" />
-
-	</target>
-	
-	<target name="is.config.file">
-		
-		<available file="${config.file}" type="file" property="config.exist"/>
-
-		<condition property="set.config.default">
-			<not>
-				<isset property="config.exist"/>
-			</not>
-		</condition>
-	
-	</target>
-	
-	<target name="set.default.config.file"
-		if="set.config.default">
-		<property name="use.config.file" value="${proj_dir}/resources/ctc_tests/ctc-test.properties" />
-		<echo>DEFAULT CONFIG: ${use.config.file}</echo>
-	
-	</target>
-	
-	<target name="set.config.file"
-		unless="set.config.default" >
-		<property name="use.config.file" value="${config.file}" />
-		<echo>USE CONFIG: ${use.config.file}</echo>
-	
-	</target>
-
-    <target name="run.all.test"
-    		unless="single" >
-    	<echo>Executing ALL Scenarios</echo>
-    	
-    	<for param="file">
-    	  <path>
-    	    <fileset dir="${scenario.dir}" includes="*.properties"/>
-    	  </path>
-    	  <sequential>
-    	  	<antcall target="exec.scenario" inheritall="true" >
-   				<param name="scenario.file" value="@{file}" />
-    	  		<param name="scenario.dir" value="@{file}" />
-			</antcall>
-	  	
-    	  	<!--
-    		<antcall target="exec.scenario" inheritall="true" >
-    			<param name="scenario.file" value="@{file}" />
-			</antcall>
-	  	-->
-    	  </sequential>
-    	</for>
-    	
-    </target>
-	
-    <target name="run.single.test"
-    		if="single" >
-    	<echo>Executing Scenario ${test.scenario}</echo>
-		<property name="include.what" value="${scenario.dir}/${scenario.file}" />
-
-        <iterate target="run.scenario"/>
-    </target>
-	
-	<target name="exec.scenario" depends="exec.win, exec.linux" >
-		
-	  	 <antcall target="are.there.errors" inheritall="true" />
-
-	</target>
-	
-	<target name="exec.win"
-		if="WinOS">
-		<echo>Scenario property file ${scenario.file}</echo>
-		<echo>Config property file ${use.config.file}</echo>
-		
-			<pathconvert targetos="unix" property="scenario_file" >
-			   		 <map from="\" to="/"/>
-			   		<path location="${scenario.file}"/>
-				 </pathconvert>
-			
-			<pathconvert targetos="unix" property="queryset_artifacts_dir" >
-			   		 <map from="\" to="/"/>
-			   		<path location="${queryset.artifacts.dir}"/>
-				 </pathconvert>
-			
-			<pathconvert targetos="unix" property="vdb_artifacts_dir" >
-			   		 <map from="\" to="/"/>
-			   		<path location="${vdb.artifacts.dir}"/>
-				 </pathconvert>
-			
-			
-			  <java classname="org.teiid.test.client.TestClient" fork="true" >
-			  	<classpath>
-					<pathelement path="${maven.runtime.classpath}" />
-			        <fileset dir="${proj_dir}/lib">
-			          <include name="**/*.jar"/>
-			        </fileset>
-			    </classpath>
-			    <jvmarg value="-Xmx1024m" />
-			  	<jvmarg value="-Dconfig=${use.config.file}" />
-			  	<jvmarg value="-Dscenariofile=${scenario_file}" />
-			  	<jvmarg value="-Dqueryset.artifacts.dir=${queryset_artifacts_dir}" />
-		       	<jvmarg value="-Dquery.scenario.classname=${query.scenario.classname}" />
-				<jvmarg value="-Dusedatasources=${usedatasources}" />
-				<jvmarg value="-Ddatasourceloc=${datasourceloc}" />
-				<jvmarg value="-Dserver.host.name=${server.host.name}" />   
-				<jvmarg value="-Dproj.dir=${proj_dir}" /> 
-			  	
-
-			</java>
-
-	</target>
-	
-	<target name="exec.linux"
-		if="UnixOS">
-		<echo>Scenario property file ${scenario.file}</echo>
-		<echo>Config property file ${use.config.file}</echo>
-		<echo>Query Artifacts ${queryset.artifacts.dir}</echo>
-		<echo>Classpath ${proj_dir}/lib</echo>
-
-<!--
-<pathelement path="${maven.runtime.classpath}" />
--->
-          <java classname="org.teiid.test.client.TestClient" fork="true" >
-          	<classpath>
-        		
-                <fileset dir="${proj_dir}/lib">
-                  <include name="**/*.jar"/>
-                </fileset>
-            </classpath>
-            <jvmarg value="-Xmx1024m" />
-           	<jvmarg value="-Dconfig=${use.config.file}" />
-          	<jvmarg value="-Dscenariofile=${scenario.file}" />
-          	<jvmarg value="-Dqueryset.artifacts.dir=${queryset.artifacts.dir}" />
-        	<jvmarg value="-Dquery.scenario.classname=${query.scenario.classname}" />
-			<jvmarg value="-Dusedatasources=${usedatasources}" />
-			<jvmarg value="-Ddatasourceloc=${datasourceloc}" />   
-			<jvmarg value="-Dserver.host.name=${server.host.name}" />   
-          	<jvmarg value="-Dproj.dir=${proj_dir}" /> 
-          	
-      	  </java>
-		
-		<!--
-		 <jvmarg value="-Dmetamatrix.sockets=true" />
-        	<jvmarg value="-Xdebug" />
-            <jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=y" />
-		
-		-->
-
-	
-	</target>
-	
-	<target name="are.there.errors" >
-		<!-- load the scenario file to get the queryset thats being run -->
-		<loadproperties srcFile="${scenario.file}" />
-		
-		
-		<!-- get the scenario name based on the scenario file, strip the suffix  -->
-		<basename property="scenario.name" file="${scenario.file}"
-		          suffix=".properties"/>
-
-		<echo>Are there any files ${root_output}/${queryset.dir}/output/${scenario.name}</echo>
-		
-	      <path id="output.dir.files">
-	                  <fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
-	                  		<include name="*.txt"/>
-	                  </fileset>
-	        </path>
-		
-		<condition property="has.output">
-			<resourcecount refid="output.dir.files" when="greater" count="0" />
-		</condition>
-		<echo>Is there output ${has.output}</echo>
-
-	      <path id="error.files">
-	                  <fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
-	                  		<include name="ERROR*"/>
-	                  </fileset>
-            		<fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
-            			<include name="*.err"/>
-            		</fileset>
-	        </path>
-		
-		<condition property="error.files.exist">
-			<resourcecount refid="error.files" when="greater" count="0" />
-
-		</condition>
-		
-		<echo>Do Error files exists ${error.files.exist}</echo>
-		
-		<condition property="error.exist">
-			<not>
-				<isset property="has.output"/>
-			</not>
-		</condition>
-		<condition property="error.exist">
-				<isset property="error.files.exist"/>
-		</condition>
-
-		<echo>Is this considered an error ${error.exist}</echo>
-		
-		<antcall target="touch.error.file" inheritall="true" />
-
-	</target>
-
-	<target name="touch.error.file"
-		if="error.exist">
-			<echo>Flag Error - Query Set: ${queryset.dir} Scenario: ${scenario.name} </echo>
-
-		<concat destfile="${ERROR_FILE}" append="true" fixlastline="yes">Query Set: ${queryset.dir} Scenario: ${scenario.name} </concat>
-
-	
-	</target>
-	
-	<target name="set.os" >
-			<condition property="isUnix">
-				<and>
-					<os family="unix"/>
-					<not>
-						<os name="Linux"/>
-					</not>
-					<not>
-						<os name="HP-UX"/>
-					</not>
-				</and>
-			</condition>
-			<condition property="isLinux">
-				<os name="Linux"/>
-			</condition>
-			<condition property="isHP-UX">
-				<os name="HP-UX"/>
-			</condition>
-			<condition property="isWindows">
-				<os family="windows"/>
-			</condition>
-
-			<condition property="UnixOS">
-				<os family="unix"/>
-			</condition>
-			<condition property="WinOS">
-				<os family="windows"/>
-			</condition>
-		</target>
-
-	
-
-</project>		
\ No newline at end of file

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml (from rev 2774, trunk/test-integration/db/src/main/resources/ctc_tests/ctc.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/ctc.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,315 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project name="ctc" default="main" >
+	
+	
+	<taskdef resource="net/sf/antcontrib/antlib.xml">
+	  <classpath>
+	  	<pathelement path="${maven.runtime.classpath}" />
+	  </classpath>
+	</taskdef>
+	
+	<target name="main" depends="init, is.config.file, set.default.config.file, set.config.file" 
+		if="" unless="" description="create all property files">
+		<echo>PROJECT DIRECTORY: ${proj_dir}</echo>
+		
+		<antcall target="run.all.test" inheritall="true" />
+		<antcall target="run.single.test" inheritall="true" />
+		
+		<available file="${ERROR_FILE}" property="error.flagged"/>
+
+		<fail if="error.flagged" message="One or more ctc tests failed" />
+	
+	</target>
+
+	<target name="init" depends="set.os, set.win, set.linux" >
+		
+		
+		<property name="ERROR_FILE" value="${root_output}/ERROR_FOUND.txt" />
+
+		<available file="${scenario.dir}" type="dir" property="scenario.dir.exist"/>
+		<fail unless="scenario.dir.exist" message="Scenario directory ${scenario.dir} does not exist or was not specified." />
+
+		<available file="${queryset.artifacts.dir}" type="dir" property="queryset.dir.exist"/>
+		<fail unless="queryset.dir.exist" message="QuerySet directory ${queryset.artifacts.dir} does not exist or was not specified." />
+		
+		<condition property="single">
+			<available file="${scenario.dir}/${scenario.file}"  />
+		</condition>
+		
+		<delete file="${ERROR_FILE}"/>
+
+	</target>
+	
+	<target name="set.win"
+		if="WinOS">
+		
+
+		<pathconvert targetos="unix" property="proj_dir" >
+		   		 <map from="\" to="/"/>
+		   		<path location="${proj.dir}"/>
+			 </pathconvert>
+		
+		<property name="root_output" value="${output.dir}" />
+
+	</target>
+	
+	<target name="set.linux"
+		if="UnixOS">
+		<property name="root_output" value="${output.dir}" />
+		<property name="proj_dir" value="${proj.dir}" />
+
+	</target>
+	
+	<target name="is.config.file">
+		
+		<available file="${config.file}" type="file" property="config.exist"/>
+
+		<condition property="set.config.default">
+			<not>
+				<isset property="config.exist"/>
+			</not>
+		</condition>
+	
+	</target>
+	
+	<target name="set.default.config.file"
+		if="set.config.default">
+		<property name="use.config.file" value="${proj_dir}/resources/ctc_tests/ctc-test.properties" />
+		<echo>DEFAULT CONFIG: ${use.config.file}</echo>
+	
+	</target>
+	
+	<target name="set.config.file"
+		unless="set.config.default" >
+		<property name="use.config.file" value="${config.file}" />
+		<echo>USE CONFIG: ${use.config.file}</echo>
+	
+	</target>
+
+    <target name="run.all.test"
+    		unless="single" >
+    	<echo>Executing ALL Scenarios</echo>
+    	
+    	<for param="file">
+    	  <path>
+    	    <fileset dir="${scenario.dir}" includes="*.properties"/>
+    	  </path>
+    	  <sequential>
+    	  	<antcall target="exec.scenario" inheritall="true" >
+   				<param name="scenario.file" value="@{file}" />
+    	  		<param name="scenario.dir" value="@{file}" />
+			</antcall>
+	  	
+    	  	<!--
+    		<antcall target="exec.scenario" inheritall="true" >
+    			<param name="scenario.file" value="@{file}" />
+			</antcall>
+	  	-->
+    	  </sequential>
+    	</for>
+    	
+    </target>
+	
+    <target name="run.single.test"
+    		if="single" >
+    	<echo>Executing Scenario ${test.scenario}</echo>
+		<property name="include.what" value="${scenario.dir}/${scenario.file}" />
+
+        <iterate target="run.scenario"/>
+    </target>
+	
+	<target name="exec.scenario" depends="exec.win, exec.linux" >
+		
+	  	 <antcall target="are.there.errors" inheritall="true" />
+
+	</target>
+	
+	<target name="exec.win"
+		if="WinOS">
+		<echo>Scenario property file ${scenario.file}</echo>
+		<echo>Config property file ${use.config.file}</echo>
+		
+			<pathconvert targetos="unix" property="scenario_file" >
+			   		 <map from="\" to="/"/>
+			   		<path location="${scenario.file}"/>
+				 </pathconvert>
+			
+			<pathconvert targetos="unix" property="queryset_artifacts_dir" >
+			   		 <map from="\" to="/"/>
+			   		<path location="${queryset.artifacts.dir}"/>
+				 </pathconvert>
+			
+			<pathconvert targetos="unix" property="vdb_artifacts_dir" >
+			   		 <map from="\" to="/"/>
+			   		<path location="${vdb.artifacts.dir}"/>
+				 </pathconvert>
+				 
+			<pathconvert targetos="unix" property="root.output" >
+			   		 <map from="\" to="/"/>
+			   		<path location="${root_output}"/>
+				 </pathconvert>		 
+			
+			
+			  <java classname="org.teiid.test.client.TestClient" fork="true" >
+			  	<classpath>
+					<pathelement path="${maven.runtime.classpath}" />
+			        <fileset dir="${proj_dir}/lib">
+			          <include name="**/*.jar"/>
+			        </fileset>
+			    </classpath>
+			    <jvmarg value="-Xmx1024m" />
+				<!--
+				<jvmarg value="-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y" />
+				-->
+			  	<jvmarg value="-Dconfig=${use.config.file}" />
+			  	<jvmarg value="-Dscenariofile=${scenario_file}" />
+			  	<jvmarg value="-Dqueryset.artifacts.dir=${queryset_artifacts_dir}" />
+		       	<jvmarg value="-Dquery.scenario.classname=${query.scenario.classname}" />
+				<jvmarg value="-Dusedatasources=${usedatasources}" />
+				<jvmarg value="-Ddatasourceloc=${datasourceloc}" />
+				<jvmarg value="-Dserver.host.name=${server.host.name}" />   
+				<jvmarg value="-Dproj.dir=${proj_dir}" /> 
+			  	<jvmarg value="-Doutput.dir=${root.output}" />
+
+			</java>
+
+	</target>
+	
+	<target name="exec.linux"
+		if="UnixOS">
+		<echo>Scenario property file ${scenario.file}</echo>
+		<echo>Config property file ${use.config.file}</echo>
+		<echo>Query Artifacts ${queryset.artifacts.dir}</echo>
+		<echo>Classpath ${proj_dir}/lib</echo>
+
+<!--
+<pathelement path="${maven.runtime.classpath}" />
+-->
+          <java classname="org.teiid.test.client.TestClient" fork="true" >
+          	<classpath>
+        		
+                <fileset dir="${proj_dir}/lib">
+                  <include name="**/*.jar"/>
+                </fileset>
+            </classpath>
+            <jvmarg value="-Xmx1024m" />
+			<!--
+			<jvmarg value="-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y" />
+			-->
+           	<jvmarg value="-Dconfig=${use.config.file}" />
+          	<jvmarg value="-Dscenariofile=${scenario.file}" />
+          	<jvmarg value="-Dqueryset.artifacts.dir=${queryset.artifacts.dir}" />
+        	<jvmarg value="-Dquery.scenario.classname=${query.scenario.classname}" />
+			<jvmarg value="-Dusedatasources=${usedatasources}" />
+			<jvmarg value="-Ddatasourceloc=${datasourceloc}" />   
+			<jvmarg value="-Dserver.host.name=${server.host.name}" />   
+          	<jvmarg value="-Dproj.dir=${proj_dir}" /> 
+			<jvmarg value="-Doutput.dir=${root_output}" /> 
+          	
+      	  </java>
+		
+		<!--
+		 <jvmarg value="-Dmetamatrix.sockets=true" />
+        	<jvmarg value="-Xdebug" />
+            <jvmarg value="-Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=y" />
+		
+		-->
+
+	
+	</target>
+	
+	<target name="are.there.errors" >
+		<!-- load the scenario file to get the queryset thats being run -->
+		<loadproperties srcFile="${scenario.file}" />
+		
+		
+		<!-- get the scenario name based on the scenario file, strip the suffix  -->
+		<basename property="scenario.name" file="${scenario.file}"
+		          suffix=".properties"/>
+
+		<echo>Are there any files ${root_output}/${queryset.dir}/output/${scenario.name}</echo>
+		
+	      <path id="output.dir.files">
+	                  <fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
+	                  		<include name="*.txt"/>
+	                  </fileset>
+	        </path>
+		
+		<condition property="has.output">
+			<resourcecount refid="output.dir.files" when="greater" count="0" />
+		</condition>
+		<echo>Is there output ${has.output}</echo>
+
+	      <path id="error.files">
+	                  <fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
+	                  		<include name="ERROR*"/>
+	                  </fileset>
+            		<fileset dir="${root_output}/${queryset.dir}/output/${scenario.name}">
+            			<include name="*.err"/>
+            		</fileset>
+	        </path>
+		
+		<condition property="error.files.exist">
+			<resourcecount refid="error.files" when="greater" count="0" />
+
+		</condition>
+		
+		<echo>Do Error files exists ${error.files.exist}</echo>
+		
+		<condition property="error.exist">
+			<not>
+				<isset property="has.output"/>
+			</not>
+		</condition>
+		<condition property="error.exist">
+				<isset property="error.files.exist"/>
+		</condition>
+
+		<echo>Is this considered an error ${error.exist}</echo>
+		
+		<antcall target="touch.error.file" inheritall="true" />
+
+	</target>
+
+	<target name="touch.error.file"
+		if="error.exist">
+			<echo>Flag Error - Query Set: ${queryset.dir} Scenario: ${scenario.name} </echo>
+
+		<concat destfile="${ERROR_FILE}" append="true" fixlastline="yes">Query Set: ${queryset.dir} Scenario: ${scenario.name} </concat>
+
+	
+	</target>
+	
+	<target name="set.os" >
+			<condition property="isUnix">
+				<and>
+					<os family="unix"/>
+					<not>
+						<os name="Linux"/>
+					</not>
+					<not>
+						<os name="HP-UX"/>
+					</not>
+				</and>
+			</condition>
+			<condition property="isLinux">
+				<os name="Linux"/>
+			</condition>
+			<condition property="isHP-UX">
+				<os name="HP-UX"/>
+			</condition>
+			<condition property="isWindows">
+				<os family="windows"/>
+			</condition>
+
+			<condition property="UnixOS">
+				<os family="unix"/>
+			</condition>
+			<condition property="WinOS">
+				<os family="windows"/>
+			</condition>
+		</target>
+
+	
+
+</project>		
\ No newline at end of file

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh
===================================================================
--- trunk/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,155 +0,0 @@
-#!/bin/sh
-
-#  This script will run the client tests 
-
-#============================
-#	REQUIRED PROPERTIES
-#
-
-#============================
-#	OPTIONAL PROPERTIES
-#
-#  (if not set, will default to files within the db project)
-#	-	QUERYSETDIR	-	directory location where the test querties can be found
-#	-	SCENARIODIR	-	directory location where the scenario files found and determine which query sets and vdbs to use, 
-#	-	DATASOURCEDIR	-	root directory location to find the various datasources to use
-#	-	CONFIGFILE	-	specify the configuration file to use (override ctc-test.properties)
-
-######################################################
-#	DEBUGGING OPTION
-#
-#    JBEDSP_DEBUG - uncomment to enable the output of debug messages.
-#                 
-# JBEDSP_DEBUG=true
-#
-
-if [ -z "${QUERYSETDIR}" ] 
-	then
-	
-	QUERYSETDIR='./src/main/resources/ctc_tests/queries'
-	
-fi
-
-if [ -z "${SCENARIODIR}" ] 
-	then
-	
-	SCENARIODIR='./src/main/resources/ctc_tests/scenarios'
-	
-fi
-
-
-if [ -z "${DATASOURCEDIR}" ] 
-	then
-	
-	DATASOURCEDIR='./src/main/resources/datasources'
-fi
-
-echo "Use Datasource directory: ${DATASOURCEDIR}"
-
-#--------------------
-
-# resolve links - $0 may be a softlink
-LOC="$0"
-
-while [ -h "$LOC" ] ; do
-  ls=`ls -ld "$LOC"`
-  link=`expr "$ls" : '.*-> \(.*\)$'`
-  if expr "$link" : '.*/.*' > /dev/null; then
-    LOC="$link"
-  else
-    LOC=`dirname "$LOC"`/"$link"
-  fi
-done
-
-LOCDIR=`dirname "$LOC"`
-PRGDIR=`cd "$LOCDIR"; pwd`
-
-cd "${PRGDIR}"
-
-echo "============================"
-echo "Running tests from ${PRGDIR}"
-echo "============================"
-
-# check if running from the kit
-if [  -f "${PRGDIR}/resources/ctc_tests/ctc.xml" ]; then
-   CTCXML=${PRGDIR}/resources/ctc_tests/ctc.xml
-else
-	CTCXML='./src/main/resources/ctc_tests/ctc.xml'
- 
-fi
-
-
-ANT_ARGS=" -Dscenario.dir=${SCENARIODIR}"
-ANT_ARGS="${ANT_ARGS} -Dqueryset.artifacts.dir=${QUERYSETDIR}"
-#ANT_ARGS="${ANT_ARGS} -Dvdb.artifacts.dir=${vdb.artifacts.dir}"
-ANT_ARGS="${ANT_ARGS} -Dproj.dir=${PRGDIR}"
-
-# default to the ip address used to start the server
-SVRNAME="0.0.0.0"
-
-if [ ! -z "${SERVERNAME}" ] 
-	then
-	
-	SVRNAME=${SERVERNAME}
-
-fi
-
-ANT_ARGS="${ANT_ARGS} -Dserver.host.name=${SVRNAME}"
-
-
-if [ ! -z "${XMLCLZZ}" ] 
-	then
-	
-	ANT_ARGS="${ANT_ARGS} -Dquery.scenario.classname=$XMLCLZZ"
-	
-fi
-
-if [ ! -z "${CONFIGFILE}" ] 
-	then
-	
-	ANT_ARGS="${ANT_ARGS} -Dconfig.file=${CONFIGFILE}"
-	
-fi
-
-if [ ! -z "${PROPFILE}" ] 
-	then
-	
-	ANT_ARGS=" -propertyfile $PROPFILE $ANT_ARGS "
-	
-fi
-
-
-ANT_OPTS="-Xmx512m"
-ANT_HOME=${PRGDIR}/ant
-
-# uncomment for additional debugging info in the logfile
-# turn on debug for additional debugging info in the logfile
-if [ -n "$JBEDSP_DEBUG" ]; then
-	ANT_ARGS="${ANT_ARGS} -verbose"
- fi
- 
-if [ ! -x "${PRGDIR}/log" ]; then
-    echo "Create ${PRGDIR}/log directory"
-	mkdir "${PRGDIR}"/log
-fi
-
-if [ -n "${JAVA_OPTS}" ]; then
-	ANT_OPTS="${JAVA_OPTS} $ANT_OPTS "
-fi
-
-CP="${PRGDIR}:${PRGDIR}/ant/*"
-
-LOGLEVEL=info
-
-echo "ANT BUILDFILE=${CTCXML}"
-echo "ANT_HOME=${ANT_HOME}"
-echo "ANT_ARGS=${ANT_ARGS}"
-echo "CP=$CP"
-
-java -cp "${CP}" -Dant.home="${ANT_HOME}" $ANT_OPTS org.apache.tools.ant.Main $ANT_ARGS -buildfile ${CTCXML}
-
-
-
-
-
-

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh (from rev 2774, trunk/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/main/resources/ctc_tests/runclienttest.sh	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,166 @@
+#!/bin/sh
+
+#  This script will run the client tests 
+
+#============================
+#	REQUIRED PROPERTIES
+#
+
+#============================
+#	OPTIONAL PROPERTIES
+#
+#  (if not set, will default to files within the db project)
+#	-	QUERYSETDIR	-	directory location where the test querties can be found
+#	-	SCENARIODIR	-	directory location where the scenario files found and determine which query sets and vdbs to use, 
+#	-	DATASOURCEDIR	-	root directory location to find the various datasources to use
+#	-	CONFIGFILE	-	specify the configuration file to use (override ctc-test.properties)
+#	-	OUTPUTDIR -    optional, can set the location the reports and generated files will be writtent o
+######################################################
+#	DEBUGGING OPTION
+#
+#    JBEDSP_DEBUG - uncomment to enable the output of debug messages.
+#                 
+# JBEDSP_DEBUG=true
+#
+
+if [ -z "${QUERYSETDIR}" ] 
+	then
+	
+	QUERYSETDIR='./src/main/resources/ctc_tests/queries'
+	
+fi
+
+if [ -z "${SCENARIODIR}" ] 
+	then
+	
+	SCENARIODIR='./src/main/resources/ctc_tests/scenarios'
+	
+fi
+
+
+if [ -z "${DATASOURCEDIR}" ] 
+	then
+	
+	DATASOURCEDIR='./src/main/resources/datasources'
+fi
+
+echo "Use Datasource directory: ${DATASOURCEDIR}"
+
+#--------------------
+
+# resolve links - $0 may be a softlink
+LOC="$0"
+
+while [ -h "$LOC" ] ; do
+  ls=`ls -ld "$LOC"`
+  link=`expr "$ls" : '.*-> \(.*\)$'`
+  if expr "$link" : '.*/.*' > /dev/null; then
+    LOC="$link"
+  else
+    LOC=`dirname "$LOC"`/"$link"
+  fi
+done
+
+LOCDIR=`dirname "$LOC"`
+PRGDIR=`cd "$LOCDIR"; pwd`
+
+cd "${PRGDIR}"
+
+echo "============================"
+echo "Running tests from ${PRGDIR}"
+echo "============================"
+
+# check if running from the kit
+if [  -f "${PRGDIR}/resources/ctc_tests/ctc.xml" ]; then
+   CTCXML=${PRGDIR}/resources/ctc_tests/ctc.xml
+else
+	CTCXML='./src/main/resources/ctc_tests/ctc.xml'
+ 
+fi
+
+
+ANT_ARGS=" -Dscenario.dir=${SCENARIODIR}"
+ANT_ARGS="${ANT_ARGS} -Dqueryset.artifacts.dir=${QUERYSETDIR}"
+#ANT_ARGS="${ANT_ARGS} -Dvdb.artifacts.dir=${vdb.artifacts.dir}"
+ANT_ARGS="${ANT_ARGS} -Dproj.dir=${PRGDIR}"
+
+if [ -z "${OUTPUTDIR}" ] 
+	then
+	
+	OUTPUTDIR=${PRGDIR}
+
+fi
+
+ANT_ARGS="${ANT_ARGS} -Doutput.dir=${OUTPUTDIR}"
+
+# default to the ip address used to start the server
+SVRNAME="0.0.0.0"
+
+if [ ! -z "${SERVERNAME}" ] 
+	then
+	
+	SVRNAME=${SERVERNAME}
+
+fi
+
+ANT_ARGS="${ANT_ARGS} -Dserver.host.name=${SVRNAME}"
+
+
+if [ ! -z "${XMLCLZZ}" ] 
+	then
+	
+	ANT_ARGS="${ANT_ARGS} -Dquery.scenario.classname=$XMLCLZZ"
+	
+fi
+
+if [ ! -z "${CONFIGFILE}" ] 
+	then
+	
+	ANT_ARGS="${ANT_ARGS} -Dconfig.file=${CONFIGFILE}"
+	
+fi
+
+if [ ! -z "${PROPFILE}" ] 
+	then
+	
+	ANT_ARGS=" -propertyfile $PROPFILE $ANT_ARGS "
+	
+fi
+
+
+ANT_OPTS="-Xmx512m"
+ANT_HOME=${PRGDIR}/ant
+
+# uncomment for additional debugging info in the logfile
+# turn on debug for additional debugging info in the logfile
+if [ -n "$JBEDSP_DEBUG" ]; then
+	ANT_ARGS="${ANT_ARGS} -verbose"
+ fi
+ 
+if [ ! -x "${PRGDIR}/log" ]; then
+    echo "Create ${PRGDIR}/log directory"
+	mkdir "${PRGDIR}"/log
+fi
+
+#JAVA_OPTS="$JAVA_OPTS -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y"
+
+if [ -n "${JAVA_OPTS}" ]; then
+	ANT_OPTS="${JAVA_OPTS} $ANT_OPTS "
+fi
+
+CP="${PRGDIR}:${PRGDIR}/ant/*"
+
+LOGLEVEL=info
+
+echo "ANT BUILDFILE=${CTCXML}"
+echo "ANT_HOME=${ANT_HOME}"
+echo "ANT_ARGS=${ANT_ARGS}"
+echo "CP=$CP"
+
+java -cp "${CP}" -Dant.home="${ANT_HOME}" $ANT_OPTS org.apache.tools.ant.Main $ANT_ARGS -buildfile ${CTCXML}
+
+
+
+
+
+

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
===================================================================
--- trunk/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -1,370 +0,0 @@
-package org.teiid.adminapi.jboss;
-
-
-import static junit.framework.Assert.*;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.sql.Connection;
-import java.util.Collection;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.teiid.adminapi.Admin;
-import org.teiid.adminapi.AdminException;
-import org.teiid.adminapi.AdminFactory;
-import org.teiid.adminapi.DataPolicy;
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.PropertyDefinition;
-import org.teiid.adminapi.Request;
-import org.teiid.adminapi.Session;
-import org.teiid.adminapi.Transaction;
-import org.teiid.adminapi.Translator;
-import org.teiid.adminapi.VDB;
-import org.teiid.core.util.UnitTestUtil;
-
- at Ignore
- at SuppressWarnings("nls")
-public class TestConnectorBindings extends BaseConnection {
-	static ServerDatasourceConnection ds;
-	static Admin admin;
-	private static final String VERSION = "-7.0.0-SNAPSHOT"; 
-	
-	@Before
-	public void setUp() throws Exception {
-		//if (!Bootstrap.getInstance().isStarted()) Bootstrap.getInstance().bootstrap();
-		ds = new ServerDatasourceConnection();
-		//admin = AdminProvider.getRemote( "jnp://localhost:1099", "javaduke", "anotherduke");	
-		admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mm://localhost:31443"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		
-		installVDB();
-	}
-	
-	@After
-	public void tearDown() {
-		admin.close();
-	}
-	
-	//@AfterClass
-	public static void end() throws Exception {
-		admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mm://localhost:31443"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		if (vdb != null) {
-			admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		}
-		admin.close();
-	}
-	
-	@Test public void testVDBDeploy() throws Exception {
-		
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		if (vdb != null) {
-			admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		}
-		
-		installVDB();
-		
-		assertNotNull(admin.getVDB("TransactionsRevisited", 1)); //$NON-NLS-1$
-		
-		Set<VDB> vdbs = admin.getVDBs();
-		assertTrue(vdbs.size() >= 1);
-		
-		admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		
-		assertNull(admin.getVDB("TransactionsRevisited", 1)); //$NON-NLS-1$
-	}
-
-	@Test public void testGetVDB() throws Exception {
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1);
-		assertNotNull(vdb); //$NON-NLS-1$
-		
-		assertEquals("TransactionsRevisited", vdb.getName());
-		assertEquals(1, vdb.getVersion());
-		assertEquals("A VDB to test transactions", vdb.getDescription());
-		//assertEquals("sample-value", vdb.getPropertyValue("sample"));
-		assertEquals(VDB.Status.INACTIVE, vdb.getStatus());
-
-		// test model
-		List<Model> models = vdb.getModels();
-		assertEquals(4, models.size());
-		Model model = null;
-		for (Model m:models) {
-			if (m.getName().equals("pm1")) {
-				model = m;
-				break;
-			}
-		}
-		assertNotNull(model);
-		assertEquals(Model.Type.PHYSICAL, model.getModelType());
-		assertEquals("sample-value", model.getPropertyValue("sample"));
-		List<String> sourceNames = model.getSourceNames();
-		assertEquals(1, sourceNames.size());
-		assertEquals("mysql", model.getSourceTranslatorName(sourceNames.get(0)));
-		assertEquals("java:mysql-connector-binding", model.getSourceConnectionJndiName(sourceNames.get(0)));
-		assertTrue(model.isSource());
-		//assertTrue(model.isSupportsMultiSourceBindings());
-		assertTrue(model.isVisible());
-		
-		// test data policies
-		List<DataPolicy> policies = vdb.getDataPolicies();
-		assertEquals(1, policies.size());
-		assertEquals("policy1", policies.get(0).getName());
-		assertEquals("roleOne described", policies.get(0).getDescription());
-		
-		List<DataPolicy.DataPermission> permissions = policies.get(0).getPermissions();
-		assertEquals(2, permissions.size());
-		
-		for(DataPolicy.DataPermission permission: permissions) {
-			if (permission.getResourceName().equals("myTable.T1")) {
-				assertTrue(permission.getAllowRead());
-				assertFalse(permission.getAllowCreate());
-				assertFalse(permission.getAllowDelete());
-				assertFalse(permission.getAllowUpdate());				
-			}
-			else if (permission.getResourceName().equals("myTable.T2")) {
-				assertFalse(permission.getAllowRead());
-				assertFalse(permission.getAllowCreate());
-				assertTrue(permission.getAllowDelete());
-				assertFalse(permission.getAllowUpdate());
-			}
-			else {
-				fail("there are only two types of permissions");
-			}
-		}
-		
-	}
-	
-	
-	@Test public void testSessions() throws Exception{
-		Connection c = ds.getConnection("TransactionsRevisited"); // to create the session
-		Collection<Session> sessions = admin.getSessions();
-		
-		int size = sessions.size();
-		assertTrue( size >= 1);
-		
-		Session found = null;
-		for (Session s: sessions) {
-			if (s.getUserName().equals("admin at teiid-security")) {
-				found = s;
-				break;
-			}
-		}
-		
-		assertNotNull(found);
-		
-		admin.terminateSession(found.getSessionId());
-		
-		sessions = admin.getSessions();
-		assertTrue(sessions.size() == (size-1));
-		c.close();
-	}
-	
-	
-	@Test public void testRequests() throws Exception {
-		Runnable work = new Runnable() {
-			public void run() {
-				for (int i = 0; i < 5; i++) {
-					try {
-						execute(ds, "TransactionsRevisited", "select * from pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-					} catch (Exception e) {
-						e.printStackTrace();
-					}
-				}
-			}
-		};
-		Thread t = new Thread(work);
-		t.start();
-		
-		// can not really stop and take reading here..
-		try {
-			Collection<Request> requests = admin.getRequests();
-			assertTrue(requests.size() >= 0);
-		}finally {
-			t.join();
-		}
-		
-		String sessionId = null;
-		Collection<Session> sessions = admin.getSessions();
-		for (Session s:sessions) {
-			sessionId = s.getSessionId();
-		}		
-		
-		t = new Thread(work);
-		t.start();
-		
-		try {
-			Collection<Request> requests = admin.getRequestsForSession(sessionId);
-			assertTrue(requests.size() >= 0);	
-		} finally {
-			t.join();
-		}
-	}
-	
-	@Test
-	public void testCache() throws Exception {
-		Collection<String> caches = admin.getCacheTypes();
-		assertEquals(3, caches.size());
-		
-		admin.clearCache("CODE_TABLE_CACHE"); //$NON-NLS-1$
-	}
-	
-	@Ignore
-	@Test
-	public void testTransactions() throws Exception {
-		Runnable work = new Runnable() {
-			public void run() {
-				try {
-					for (int i = 0; i < 10; i++) {
-						int v = i+200;
-						execute(ds, "TransactionsRevisited", "insert into vm.g1 (pm1e1, pm1e2, pm2e1, pm2e2) values("+v+",'"+v+"',"+v+",'"+v+"')"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-					}
-					execute(ds, "TransactionsRevisited", "delete from vm.g1 where pm1e1 >= 200"); //$NON-NLS-1$ //$NON-NLS-2$
-				} catch (Exception e) {
-					e.printStackTrace();
-				}
-			}
-		};
-		
-		Thread t = new Thread(work);
-		t.start();
-		Thread.sleep(2000);
-		try {
-			Collection<Transaction> txns = admin.getTransactions();
-			assertTrue(txns.size() >= 0);
-		} finally {
-			t.join();
-		}
-	}
-
-	private static void installVDB() throws AdminException, FileNotFoundException {
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		if (vdb == null) {
-			File f = UnitTestUtil.getTestDataFile("TransactionsRevisited.vdb"); //$NON-NLS-1$
-			FileInputStream fis = new FileInputStream(f);
-			admin.deployVDB(f.getName(), fis);
-			try {
-				fis.close();
-			} catch (IOException e) {
-			}
-		}
-	}
-	
-	@Test
-	public void testTranslatorTemplateProperties() throws Exception {
-		Collection<PropertyDefinition> defs = admin.getTemplatePropertyDefinitions("translator-jdbc"+VERSION); //$NON-NLS-1$
-		for (PropertyDefinition pd:defs) {
-			System.out.println(pd.getName()+":"+pd.getPropertyTypeClassName()+":"+pd.getDefaultValue());
-			if (pd.getName().equals("ExtensionTranslationClassName")) { //$NON-NLS-1$
-				assertEquals("Extension SQL Translation Class", pd.getDisplayName()); //$NON-NLS-1$
-				assertEquals(false, pd.isAdvanced());
-				assertEquals(true, pd.isRequired());
-				assertEquals(false, pd.isMasked());
-				assertEquals(true, pd.isModifiable());
-				
-				assertEquals(12, pd.getAllowedValues().size());
-				System.out.println(pd.getAllowedValues());
-			}
-		}
-	}
-	
-	@Test
-	public void testGetTemplate() throws Exception {
-		Translator translator = admin.getTranslator("oracle");
-		for (String key:translator.getProperties().stringPropertyNames()) {
-			System.out.println(key+"="+translator.getPropertyValue(key));
-		}
-		assertEquals("org.teiid.translator.jdbc.oracle.OracleSQLTranslator", translator.getPropertyValue("ExtensionTranslationClassName")); //$NON-NLS-1$
-		assertEquals(false, translator.getPropertyValue("XaCapable"));
-	}
-	
-	@Test public void testAssignConnectorBinding() throws Exception {
-		admin.assignToModel("TransactionsRevisited", 1, "pm1", "mysql", "mysql", "jndi:FOO"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-		
-		boolean checked = false;
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		List<Model> models = vdb.getModels();
-		for (Model model:models) {
-			if (model.getName().equals("pm1")) { //$NON-NLS-1$
-				List<String> sources = model.getSourceNames();
-				for (String source:sources) {
-					if (source.equals("mysql")) { //$NON-NLS-1$
-						assertEquals("jndi:FOO", model.getSourceConnectionJndiName(source)); //$NON-NLS-1$
-						checked = true;
-					}
-				}
-			}
-		}
-		
-		assertTrue("Test not veryfied", checked); //$NON-NLS-1$
-	}
-	
-	
-	@Test public void testAddRoleNames() throws Exception {
-		installVDB();
-		admin.addDataRoleMapping("TransactionsRevisited", 1, "policy1", "managers"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-		
-		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		List<DataPolicy> policies = vdb.getDataPolicies();
-		assertTrue (!policies.isEmpty());
-		for (DataPolicy policy:policies) {
-			if (policy.getName().equals("policy1")) { //$NON-NLS-1$
-				List<String> sources = policy.getMappedRoleNames();
-				assertTrue(sources.contains("managers"));
-			}
-		}
-		
-		// remove the role
-		admin.removeDataRoleMapping("TransactionsRevisited", 1, "policy1", "managers");
-		
-		vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
-		policies = vdb.getDataPolicies();
-		assertTrue (!policies.isEmpty());
-		
-		for (DataPolicy policy:policies) {
-			if (policy.getName().equals("policy1")) { //$NON-NLS-1$
-				List<String> sources = policy.getMappedRoleNames();
-				assertFalse(sources.contains("managers"));
-			}
-		}		
-		
-		// remove non-existent role name
-		admin.removeDataRoleMapping("TransactionsRevisited", 1, "policy1", "FOO");
-	}	
-	
-	@Test
-	public void testCreateDataSource() throws Exception {
-		
-		Properties p = new Properties();
-		p.setProperty("DatabaseName", "txntest");
-		p.setProperty("PortNumber", "3306");
-		p.setProperty("ServerName", "localhost");
-		p.setProperty("addtional-ds-properties", "foo=bar, t= x");
-		p.setProperty("user-name", "rareddy");
-		p.setProperty("password", "mm");
-		p.setProperty("xa-datasource-class", "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
-		
-		admin.createDataSource("test-mysql","connector-jdbc-xa", p);	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	@Test
-	public void testCreateDriverSource() throws Exception {
-		
-		Properties p = new Properties();
-		p.setProperty("connection-url", "jdbc:mysql://localhost:3306/txntest");
-		p.setProperty("addtional-connection-properties", "foo=bar, t= x");
-		p.setProperty("user-name", "rareddy");
-		p.setProperty("password", "mm");
-		p.setProperty("driver-class", "com.mysql.jdbc.Driver");
-		
-		admin.createDataSource("test-mysql-driver","connector-jdbc", p);	 //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-}

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java (from rev 2774, trunk/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java	2010-12-14 21:32:47 UTC (rev 2778)
@@ -0,0 +1,387 @@
+package org.teiid.adminapi.jboss;
+
+
+import static junit.framework.Assert.*;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.sql.Connection;
+import java.util.Collection;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminException;
+import org.teiid.adminapi.AdminFactory;
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.PropertyDefinition;
+import org.teiid.adminapi.Request;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.Transaction;
+import org.teiid.adminapi.Translator;
+import org.teiid.adminapi.VDB;
+import org.teiid.adminapi.VDB.ConnectionType;
+import org.teiid.core.util.UnitTestUtil;
+
+ at Ignore
+ at SuppressWarnings("nls")
+public class TestConnectorBindings extends BaseConnection {
+	static ServerDatasourceConnection ds;
+	static Admin admin;
+	private static final String VERSION = "-7.0.0-SNAPSHOT"; 
+	
+	@Before
+	public void setUp() throws Exception {
+		//if (!Bootstrap.getInstance().isStarted()) Bootstrap.getInstance().bootstrap();
+		ds = new ServerDatasourceConnection();
+		//admin = AdminProvider.getRemote( "jnp://localhost:1099", "javaduke", "anotherduke");	
+		admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mms://127.0.0.1:31443"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		
+		installVDB();
+	}
+	
+	@After
+	public void tearDown() {
+		admin.close();
+	}
+	
+	//@AfterClass
+	public static void end() throws Exception {
+		admin = AdminFactory.getInstance().createAdmin("admin", "admin".toCharArray(), "mm://localhost:31443"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		if (vdb != null) {
+			admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		}
+		admin.close();
+	}
+	
+	@Test public void testVDBDeploy() throws Exception {
+		
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		if (vdb != null) {
+			admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		}
+		
+		installVDB();
+		
+		assertNotNull(admin.getVDB("TransactionsRevisited", 1)); //$NON-NLS-1$
+		
+		Set<VDB> vdbs = admin.getVDBs();
+		assertTrue(vdbs.size() >= 1);
+		
+		admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		
+		assertNull(admin.getVDB("TransactionsRevisited", 1)); //$NON-NLS-1$
+	}
+	
+	@Test
+	public void testChangeConnectionType() throws Exception {
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1);
+		assertNotNull(vdb); //$NON-NLS-1$
+		
+		ConnectionType ct = vdb.getConnectionType();
+		assertEquals(ConnectionType.BY_VERSION, ct);
+		
+		admin.changeVDBConnectionType("TransactionsRevisited", 1, ConnectionType.ANY);
+		
+		vdb = admin.getVDB("TransactionsRevisited", 1);
+		
+		ct = vdb.getConnectionType();
+		assertEquals(ConnectionType.ANY, ct);		
+	}
+
+	@Test public void testGetVDB() throws Exception {
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1);
+		assertNotNull(vdb); //$NON-NLS-1$
+		
+		assertEquals("TransactionsRevisited", vdb.getName());
+		assertEquals(1, vdb.getVersion());
+		assertEquals("A VDB to test transactions", vdb.getDescription());
+		//assertEquals("sample-value", vdb.getPropertyValue("sample"));
+		assertEquals(VDB.Status.INACTIVE, vdb.getStatus());
+
+		// test model
+		List<Model> models = vdb.getModels();
+		assertEquals(4, models.size());
+		Model model = null;
+		for (Model m:models) {
+			if (m.getName().equals("pm1")) {
+				model = m;
+				break;
+			}
+		}
+		assertNotNull(model);
+		assertEquals(Model.Type.PHYSICAL, model.getModelType());
+		assertEquals("sample-value", model.getPropertyValue("sample"));
+		List<String> sourceNames = model.getSourceNames();
+		assertEquals(1, sourceNames.size());
+		assertEquals("mysql", model.getSourceTranslatorName(sourceNames.get(0)));
+		assertEquals("java:mysql-connector-binding", model.getSourceConnectionJndiName(sourceNames.get(0)));
+		assertTrue(model.isSource());
+		//assertTrue(model.isSupportsMultiSourceBindings());
+		assertTrue(model.isVisible());
+		
+		// test data policies
+		List<DataPolicy> policies = vdb.getDataPolicies();
+		assertEquals(1, policies.size());
+		assertEquals("policy1", policies.get(0).getName());
+		assertEquals("roleOne described", policies.get(0).getDescription());
+		
+		List<DataPolicy.DataPermission> permissions = policies.get(0).getPermissions();
+		assertEquals(2, permissions.size());
+		
+		for(DataPolicy.DataPermission permission: permissions) {
+			if (permission.getResourceName().equals("myTable.T1")) {
+				assertTrue(permission.getAllowRead());
+				assertFalse(permission.getAllowCreate());
+				assertFalse(permission.getAllowDelete());
+				assertFalse(permission.getAllowUpdate());				
+			}
+			else if (permission.getResourceName().equals("myTable.T2")) {
+				assertFalse(permission.getAllowRead());
+				assertFalse(permission.getAllowCreate());
+				assertTrue(permission.getAllowDelete());
+				assertFalse(permission.getAllowUpdate());
+			}
+			else {
+				fail("there are only two types of permissions");
+			}
+		}
+		
+	}
+	
+	
+	@Test public void testSessions() throws Exception{
+		Connection c = ds.getConnection("TransactionsRevisited"); // to create the session
+		Collection<Session> sessions = admin.getSessions();
+		
+		int size = sessions.size();
+		assertTrue( size >= 1);
+		
+		Session found = null;
+		for (Session s: sessions) {
+			if (s.getUserName().equals("admin at teiid-security")) {
+				found = s;
+				break;
+			}
+		}
+		
+		assertNotNull(found);
+		
+		admin.terminateSession(found.getSessionId());
+		
+		sessions = admin.getSessions();
+		assertTrue(sessions.size() == (size-1));
+		c.close();
+	}
+	
+	
+	@Test public void testRequests() throws Exception {
+		Runnable work = new Runnable() {
+			public void run() {
+				for (int i = 0; i < 5; i++) {
+					try {
+						execute(ds, "TransactionsRevisited", "select * from pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+					} catch (Exception e) {
+						e.printStackTrace();
+					}
+				}
+			}
+		};
+		Thread t = new Thread(work);
+		t.start();
+		
+		// can not really stop and take reading here..
+		try {
+			Collection<Request> requests = admin.getRequests();
+			assertTrue(requests.size() >= 0);
+		}finally {
+			t.join();
+		}
+		
+		String sessionId = null;
+		Collection<Session> sessions = admin.getSessions();
+		for (Session s:sessions) {
+			sessionId = s.getSessionId();
+		}		
+		
+		t = new Thread(work);
+		t.start();
+		
+		try {
+			Collection<Request> requests = admin.getRequestsForSession(sessionId);
+			assertTrue(requests.size() >= 0);	
+		} finally {
+			t.join();
+		}
+	}
+	
+	@Test
+	public void testCache() throws Exception {
+		Collection<String> caches = admin.getCacheTypes();
+		assertEquals(3, caches.size());
+		
+		admin.clearCache("CODE_TABLE_CACHE"); //$NON-NLS-1$
+	}
+	
+	@Ignore
+	@Test
+	public void testTransactions() throws Exception {
+		Runnable work = new Runnable() {
+			public void run() {
+				try {
+					for (int i = 0; i < 10; i++) {
+						int v = i+200;
+						execute(ds, "TransactionsRevisited", "insert into vm.g1 (pm1e1, pm1e2, pm2e1, pm2e2) values("+v+",'"+v+"',"+v+",'"+v+"')"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					}
+					execute(ds, "TransactionsRevisited", "delete from vm.g1 where pm1e1 >= 200"); //$NON-NLS-1$ //$NON-NLS-2$
+				} catch (Exception e) {
+					e.printStackTrace();
+				}
+			}
+		};
+		
+		Thread t = new Thread(work);
+		t.start();
+		Thread.sleep(2000);
+		try {
+			Collection<Transaction> txns = admin.getTransactions();
+			assertTrue(txns.size() >= 0);
+		} finally {
+			t.join();
+		}
+	}
+
+	private static void installVDB() throws AdminException, FileNotFoundException {
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		if (vdb == null) {
+			File f = UnitTestUtil.getTestDataFile("TransactionsRevisited.vdb"); //$NON-NLS-1$
+			FileInputStream fis = new FileInputStream(f);
+			admin.deployVDB(f.getName(), fis);
+			try {
+				fis.close();
+			} catch (IOException e) {
+			}
+		}
+	}
+	
+	@Test
+	public void testTranslatorTemplateProperties() throws Exception {
+		Collection<PropertyDefinition> defs = admin.getTemplatePropertyDefinitions("translator-jdbc"+VERSION); //$NON-NLS-1$
+		for (PropertyDefinition pd:defs) {
+			System.out.println(pd.getName()+":"+pd.getPropertyTypeClassName()+":"+pd.getDefaultValue());
+			if (pd.getName().equals("ExtensionTranslationClassName")) { //$NON-NLS-1$
+				assertEquals("Extension SQL Translation Class", pd.getDisplayName()); //$NON-NLS-1$
+				assertEquals(false, pd.isAdvanced());
+				assertEquals(true, pd.isRequired());
+				assertEquals(false, pd.isMasked());
+				assertEquals(true, pd.isModifiable());
+				
+				assertEquals(12, pd.getAllowedValues().size());
+				System.out.println(pd.getAllowedValues());
+			}
+		}
+	}
+	
+	@Test
+	public void testGetTemplate() throws Exception {
+		Translator translator = admin.getTranslator("oracle");
+		for (String key:translator.getProperties().stringPropertyNames()) {
+			System.out.println(key+"="+translator.getPropertyValue(key));
+		}
+		assertEquals("org.teiid.translator.jdbc.oracle.OracleSQLTranslator", translator.getPropertyValue("ExtensionTranslationClassName")); //$NON-NLS-1$
+		assertEquals(false, translator.getPropertyValue("XaCapable"));
+	}
+	
+	@Test public void testAssignConnectorBinding() throws Exception {
+		admin.assignToModel("TransactionsRevisited", 1, "pm1", "mysql", "mysql", "jndi:FOO"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+		
+		boolean checked = false;
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		List<Model> models = vdb.getModels();
+		for (Model model:models) {
+			if (model.getName().equals("pm1")) { //$NON-NLS-1$
+				List<String> sources = model.getSourceNames();
+				for (String source:sources) {
+					if (source.equals("mysql")) { //$NON-NLS-1$
+						assertEquals("jndi:FOO", model.getSourceConnectionJndiName(source)); //$NON-NLS-1$
+						checked = true;
+					}
+				}
+			}
+		}
+		
+		assertTrue("Test not veryfied", checked); //$NON-NLS-1$
+	}
+	
+	
+	@Test public void testAddRoleNames() throws Exception {
+		installVDB();
+		admin.addDataRoleMapping("TransactionsRevisited", 1, "policy1", "managers"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		
+		VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		List<DataPolicy> policies = vdb.getDataPolicies();
+		assertTrue (!policies.isEmpty());
+		for (DataPolicy policy:policies) {
+			if (policy.getName().equals("policy1")) { //$NON-NLS-1$
+				List<String> sources = policy.getMappedRoleNames();
+				assertTrue(sources.contains("managers"));
+			}
+		}
+		
+		// remove the role
+		admin.removeDataRoleMapping("TransactionsRevisited", 1, "policy1", "managers");
+		
+		vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
+		policies = vdb.getDataPolicies();
+		assertTrue (!policies.isEmpty());
+		
+		for (DataPolicy policy:policies) {
+			if (policy.getName().equals("policy1")) { //$NON-NLS-1$
+				List<String> sources = policy.getMappedRoleNames();
+				assertFalse(sources.contains("managers"));
+			}
+		}		
+		
+		// remove non-existent role name
+		admin.removeDataRoleMapping("TransactionsRevisited", 1, "policy1", "FOO");
+	}	
+	
+	@Test
+	public void testCreateDataSource() throws Exception {
+		
+		Properties p = new Properties();
+		p.setProperty("DatabaseName", "txntest");
+		p.setProperty("PortNumber", "3306");
+		p.setProperty("ServerName", "localhost");
+		p.setProperty("addtional-ds-properties", "foo=bar, t= x");
+		p.setProperty("user-name", "rareddy");
+		p.setProperty("password", "mm");
+		p.setProperty("xa-datasource-class", "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
+		
+		admin.createDataSource("test-mysql","connector-jdbc-xa", p);	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+	@Test
+	public void testCreateDriverSource() throws Exception {
+		
+		Properties p = new Properties();
+		p.setProperty("connection-url", "jdbc:mysql://localhost:3306/txntest");
+		p.setProperty("addtional-connection-properties", "foo=bar, t= x");
+		p.setProperty("user-name", "rareddy");
+		p.setProperty("password", "mm");
+		p.setProperty("driver-class", "com.mysql.jdbc.Driver");
+		
+		admin.createDataSource("test-mysql-driver","connector-jdbc", p);	 //$NON-NLS-1$ //$NON-NLS-2$
+	}
+	
+}

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/resources/TransactionsRevisited.vdb
===================================================================
(Binary files differ)

Copied: tags/teiid-parent-7.3.0.Alpha1/test-integration/db/src/test/resources/TransactionsRevisited.vdb (from rev 2774, trunk/test-integration/db/src/test/resources/TransactionsRevisited.vdb)
===================================================================
(Binary files differ)

Deleted: tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml
===================================================================
--- trunk/test-integration/pom.xml	2010-12-06 18:06:30 UTC (rev 2760)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1-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.Alpha1/test-integration/pom.xml (from rev 2777, trunk/test-integration/pom.xml)
===================================================================
--- tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml	                        (rev 0)
+++ tags/teiid-parent-7.3.0.Alpha1/test-integration/pom.xml	2010-12-14 21:32:47 UTC (rev 2778)
@@ -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.Alpha1</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