teiid SVN: r2106 - trunk/connectors.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-07 16:25:05 -0400 (Fri, 07 May 2010)
New Revision: 2106
Removed:
trunk/connectors/connector-jdbc/
trunk/connectors/connector-loopback/
Modified:
trunk/connectors/pom.xml
Log:
TEIID-1075, TEIID-1077, TEIID-1078, TEIID-1079, TEIID-1080, TEIID-1081: Translation layer changes.
Modified: trunk/connectors/pom.xml
===================================================================
--- trunk/connectors/pom.xml 2010-05-07 20:22:28 UTC (rev 2105)
+++ trunk/connectors/pom.xml 2010-05-07 20:25:05 UTC (rev 2106)
@@ -75,16 +75,25 @@
</dependencies>
<modules>
- <module>connector-jdbc</module>
- <module>connector-loopback</module>
+ <module>translator-jdbc</module>
+ <module>translator-ldap</module>
+
+ <module>translator-loopback</module>
+ <module>translator-text</module>
+ <module>translator-salesforce</module>
+
<module>connector-text</module>
+ <module>connector-salesforce</module>
<module>connector-ldap</module>
- <module>connector-salesforce</module>
<module>salesforce-api</module>
+
<module>sandbox</module>
+
+ <!--
<module>connector-xml</module>
<module>connector-xml-file</module>
<module>connector-xml-soap</module>
<module>connector-xml-http</module>
+ -->
</modules>
-</project>
\ No newline at end of file
+</project>
13 years, 11 months
teiid SVN: r2105 - trunk/connectors/sandbox.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-07 16:22:28 -0400 (Fri, 07 May 2010)
New Revision: 2105
Removed:
trunk/connectors/sandbox/connector-yahoo/
Modified:
trunk/connectors/sandbox/pom.xml
Log:
TEIID-1075, TEIID-1077, TEIID-1078, TEIID-1079, TEIID-1080, TEIID-1081: Translation layer changes.
Modified: trunk/connectors/sandbox/pom.xml
===================================================================
--- trunk/connectors/sandbox/pom.xml 2010-05-07 20:11:50 UTC (rev 2104)
+++ trunk/connectors/sandbox/pom.xml 2010-05-07 20:22:28 UTC (rev 2105)
@@ -12,6 +12,6 @@
<name>Sandbox</name>
<description>Experimental connectors in progress</description>
<modules>
- <module>connector-yahoo</module>
+ <module>translator-yahoo</module>
</modules>
-</project>
\ No newline at end of file
+</project>
13 years, 11 months
teiid SVN: r2104 - in trunk/connectors: connector-ldap/src/test/java/com/metamatrix and 36 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-07 16:11:50 -0400 (Fri, 07 May 2010)
New Revision: 2104
Added:
trunk/connectors/connector-text/src/test/java/org/
trunk/connectors/connector-text/src/test/java/org/teiid/
trunk/connectors/connector-text/src/test/java/org/teiid/resource/
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeConnection.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeMetadataFactory.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCExecutionFactory.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCProcedureExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCUpdateExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TranslationHelper.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestSQLConversionVisitor.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/h2/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/
Removed:
trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/
trunk/connectors/connector-ldap/src/test/java/com/metamatrix/connector/
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/
trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/execution/visitors/
trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/test/util/
trunk/connectors/connector-salesforce/src/test/resources/documents/
trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/
trunk/connectors/sandbox/translator-yahoo/src/main/java/com/metamatrix/connector/
trunk/connectors/sandbox/translator-yahoo/src/test/java/com/metamatrix/connector/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/
trunk/connectors/translator-jdbc/src/main/rar/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeConnection.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.class
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/extension/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/
trunk/connectors/translator-loopback/src/main/java/com/metamatrix/connector/
trunk/connectors/translator-loopback/src/test/java/com/metamatrix/connector/
trunk/connectors/translator-text/src/test/java/org/teiid/resource/adapter/text/
trunk/connectors/translator-text/src/test/resources/EmpData.txt
trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt
trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt
trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt
Modified:
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestMultiFileTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestRowHeaderTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnection.java
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnector.java
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/Util.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestEscapeSyntaxModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestExtractFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestLocateFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestModFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access/TestAccessSQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2ConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbySQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/h2/TestH2Translator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQL5Translator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLeftOrRightFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLog10FunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestSubstringFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseSQLConversionVisitor.java
Log:
TEIID-1075, TEIID-1077, TEIID-1078, TEIID-1079, TEIID-1080, TEIID-1081: Translation layer changes.
Copied: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text (from rev 2103, trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text)
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestMultiFileTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestMultiFileTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestMultiFileTextSynchExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import java.util.ArrayList;
import java.util.HashSet;
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestRowHeaderTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestRowHeaderTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestRowHeaderTextSynchExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import junit.framework.TestCase;
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnection.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnection.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import java.util.Map;
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnector.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextConnector.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/TestTextSynchExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import java.util.ArrayList;
import java.util.List;
Modified: trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/Util.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/Util.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/connector-text/src/test/java/org/teiid/resource/cci/text/Util.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import java.io.File;
import java.util.List;
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeConnection.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeConnection.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,55 +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.jdbc;
-
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import com.metamatrix.core.util.SimpleMock;
-
-/**
- * FakeConnection for unit testing
- */
-public class FakeConnection {
-
- boolean closed;
- boolean fail;
-
- /* (non-Javadoc)
- * @see java.sql.Connection#createStatement()
- */
- public Statement createStatement() throws SQLException {
- if (fail) {
- throw new SQLException();
- }
- return SimpleMock.createSimpleMock(Statement.class);
- }
-
- /* (non-Javadoc)
- * @see java.sql.Connection#isClosed()
- */
- public boolean isClosed() {
- return closed;
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,66 +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.jdbc;
-
-import static org.junit.Assert.assertEquals;
-import junit.framework.Assert;
-
-import org.mockito.Mockito;
-import org.teiid.connector.language.Command;
-import org.teiid.resource.ConnectorException;
-import org.teiid.resource.cci.ExecutionContext;
-import org.teiid.translator.jdbc.TranslatedCommand;
-import org.teiid.translator.jdbc.Translator;
-
-import com.metamatrix.cdk.api.TranslationUtility;
-import com.metamatrix.cdk.unittest.FakeTranslationFactory;
-
-public class FakeMetadataFactory {
-
- public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
- public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
-
- public static Command helpTranslate(String vdbFileName, String sql) {
- TranslationUtility util = null;
- if (PARTS_VDB.equals(vdbFileName)) {
- util = new TranslationUtility(FakeMetadataFactory.class.getResource(vdbFileName));
- } else if (BQT_VDB.equals(vdbFileName)){
- util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
- } else {
- Assert.fail("unknown vdb"); //$NON-NLS-1$
- }
- return util.parseCommand(sql);
- }
-
- public static void helpTestVisitor(String vdb, String input, String expectedOutput, Translator translator) throws ConnectorException {
- // Convert from sql to objects
- Command obj = helpTranslate(vdb, input);
-
- TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
- tc.translateCommand(obj);
-
- // Check stuff
- assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,44 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.Translator;
-import org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator;
-public class TestJDBCExecutionFactory {
-
- @Test public void testGetExtensionTranslationClassDefault() throws Exception {
- JDBCExecutionFactory mcf = new JDBCExecutionFactory();
- assertSame(Translator.class, mcf.getTranslator().getClass());
- }
-
- @Test public void testGetExtensionTranslationClass() throws Exception {
- JDBCExecutionFactory mcf = new JDBCExecutionFactory();
- mcf.setExtensionTranslationClassName(SQLServerSQLTranslator.class.getName());
- assertSame(SQLServerSQLTranslator.class, mcf.getTranslator().getClass());
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,77 +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.jdbc;
-
-import static org.junit.Assert.assertEquals;
-
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.Types;
-import java.util.Arrays;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.connector.language.Command;
-import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
-import org.teiid.resource.adapter.jdbc.JDBCProcedureExecution;
-import org.teiid.resource.cci.ExecutionContext;
-import org.teiid.translator.jdbc.Translator;
-
-public class TestJDBCProcedureExecution {
-
- @Test public void testProcedureExecution() throws Exception {
- Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "exec pm2.spTest8a()"); //$NON-NLS-1$
- Connection connection = Mockito.mock(Connection.class);
- CallableStatement cs = Mockito.mock(CallableStatement.class);
- Mockito.stub(cs.getUpdateCount()).toReturn(-1);
- Mockito.stub(cs.getInt(1)).toReturn(5);
- Mockito.stub(connection.prepareCall("{ call spTest8a(?)}")).toReturn(cs); //$NON-NLS-1$
- Translator sqlTranslator = new Translator();
-
- JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
- Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
-
- JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
- procedureExecution.execute();
- assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
- Mockito.verify(cs, Mockito.times(1)).registerOutParameter(1, Types.INTEGER);
- }
- @Test public void testProcedureExecution1() throws Exception {
- Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "exec pm2.spTest8(1)"); //$NON-NLS-1$
- Connection connection = Mockito.mock(Connection.class);
- CallableStatement cs = Mockito.mock(CallableStatement.class);
- Mockito.stub(cs.getUpdateCount()).toReturn(-1);
- Mockito.stub(cs.getInt(2)).toReturn(5);
- Mockito.stub(connection.prepareCall("{ call spTest8(?,?)}")).toReturn(cs); //$NON-NLS-1$
- Translator sqlTranslator = new Translator();
-
- JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
- Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
-
- JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
- procedureExecution.execute();
- assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
- Mockito.verify(cs, Mockito.times(1)).registerOutParameter(2, Types.INTEGER);
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,65 +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.jdbc;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.util.Arrays;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.ExpressionValueSource;
-import org.teiid.connector.language.Insert;
-import org.teiid.connector.language.Literal;
-import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
-import org.teiid.resource.adapter.jdbc.JDBCUpdateExecution;
-import org.teiid.resource.cci.ExecutionContext;
-import org.teiid.translator.jdbc.Translator;
-
-public class TestJDBCUpdateExecution {
-
- @Test public void testBulkUpdate() throws Exception {
- Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (IntKey, IntNum) values (1, 2)"); //$NON-NLS-1$
- Literal value = ((Literal)((ExpressionValueSource)((Insert)command).getValueSource()).getValues().get(0));
- Literal value1 = ((Literal)((ExpressionValueSource)((Insert)command).getValueSource()).getValues().get(1));
- value.setMultiValued(true);
- value.setBindValue(true);
- value.setValue(Arrays.asList(1, 2));
- value1.setMultiValued(true);
- value1.setBindValue(true);
- value1.setValue(Arrays.asList(2, 3));
- Connection connection = Mockito.mock(Connection.class);
- PreparedStatement p = Mockito.mock(PreparedStatement.class);
- Mockito.stub(p.executeBatch()).toReturn(new int [] {1, 1});
- Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey, IntNum) VALUES (?, ?)")).toReturn(p); //$NON-NLS-1$
-
- JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
- Mockito.stub(config.getTranslator()).toReturn(new Translator());
-
- JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, Mockito.mock(ExecutionContext.class), config, config.getTranslator());
- updateExecution.execute();
- Mockito.verify(p, Mockito.times(2)).addBatch();
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.class
===================================================================
(Binary files differ)
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -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.connector.jdbc;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.IOException;
-import java.util.Collection;
-
-import junit.framework.Assert;
-
-import org.mockito.Mockito;
-import org.teiid.connector.language.Command;
-import org.teiid.resource.ConnectorException;
-import org.teiid.resource.cci.ExecutionContext;
-import org.teiid.translator.jdbc.TranslatedCommand;
-import org.teiid.translator.jdbc.Translator;
-
-import com.metamatrix.cdk.api.TranslationUtility;
-import com.metamatrix.cdk.unittest.FakeTranslationFactory;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.metamatrix.query.function.metadata.FunctionMetadataReader;
-import com.metamatrix.query.function.metadata.FunctionMethod;
-
-public class TranslationHelper {
-
- public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
- public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
-
- public static Command helpTranslate(String vdbFileName, String sql) {
- return helpTranslate(vdbFileName, null, sql);
- }
-
- public static Command helpTranslate(String vdbFileName, String udf, String sql) {
- TranslationUtility util = null;
- if (PARTS_VDB.equals(vdbFileName)) {
- util = new TranslationUtility(TranslationHelper.class.getResource(vdbFileName));
- } else if (BQT_VDB.equals(vdbFileName)){
- util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
- } else {
- Assert.fail("unknown vdb"); //$NON-NLS-1$
- }
-
- if (udf != null) {
- try {
- Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
- util.setUDF(methods);
- } catch (IOException e) {
- throw new MetaMatrixRuntimeException("failed to load UDF"); //$NON-NLS-1$
- }
- }
- return util.parseCommand(sql);
- }
-
- public static void helpTestVisitor(String vdb, String input, String expectedOutput, Translator translator) throws ConnectorException {
- helpTestVisitor(vdb,null,input, expectedOutput, translator);
- }
-
- public static void helpTestVisitor(String vdb, String udf, String input, String expectedOutput, Translator translator) throws ConnectorException {
- // Convert from sql to objects
- Command obj = helpTranslate(vdb, udf, input);
-
- helpTestVisitor(expectedOutput, translator, obj);
- }
-
- public static void helpTestVisitor(String expectedOutput,
- Translator translator, Command obj) throws ConnectorException {
- TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
- tc.translateCommand(obj);
- assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
- }
-
-}
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeConnection.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeConnection.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeConnection.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeConnection.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import com.metamatrix.core.util.SimpleMock;
+
+/**
+ * FakeConnection for unit testing
+ */
+public class FakeConnection {
+
+ boolean closed;
+ boolean fail;
+
+ /* (non-Javadoc)
+ * @see java.sql.Connection#createStatement()
+ */
+ public Statement createStatement() throws SQLException {
+ if (fail) {
+ throw new SQLException();
+ }
+ return SimpleMock.createSimpleMock(Statement.class);
+ }
+
+ /* (non-Javadoc)
+ * @see java.sql.Connection#isClosed()
+ */
+ public boolean isClosed() {
+ return closed;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeConnection.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeMetadataFactory.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeMetadataFactory.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeMetadataFactory.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,66 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import static org.junit.Assert.assertEquals;
+import junit.framework.Assert;
+
+import org.mockito.Mockito;
+import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+import com.metamatrix.cdk.api.TranslationUtility;
+import com.metamatrix.cdk.unittest.FakeTranslationFactory;
+
+public class FakeMetadataFactory {
+
+ public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
+ public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
+
+ public static Command helpTranslate(String vdbFileName, String sql) {
+ TranslationUtility util = null;
+ if (PARTS_VDB.equals(vdbFileName)) {
+ util = new TranslationUtility(FakeMetadataFactory.class.getResource(vdbFileName));
+ } else if (BQT_VDB.equals(vdbFileName)){
+ util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
+ } else {
+ Assert.fail("unknown vdb"); //$NON-NLS-1$
+ }
+ return util.parseCommand(sql);
+ }
+
+ public static void helpTestVisitor(String vdb, String input, String expectedOutput, Translator translator) throws ConnectorException {
+ // Convert from sql to objects
+ Command obj = helpTranslate(vdb, input);
+
+ TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
+ tc.translateCommand(obj);
+
+ // Check stuff
+ assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/FakeMetadataFactory.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCExecutionFactory.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCExecutionFactory.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,44 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator;
+public class TestJDBCExecutionFactory {
+
+ @Test public void testGetExtensionTranslationClassDefault() throws Exception {
+ JDBCExecutionFactory mcf = new JDBCExecutionFactory();
+ assertSame(Translator.class, mcf.getTranslator().getClass());
+ }
+
+ @Test public void testGetExtensionTranslationClass() throws Exception {
+ JDBCExecutionFactory mcf = new JDBCExecutionFactory();
+ mcf.setExtensionTranslationClassName(SQLServerSQLTranslator.class.getName());
+ assertSame(SQLServerSQLTranslator.class, mcf.getTranslator().getClass());
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCExecutionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCProcedureExecution.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCProcedureExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCProcedureExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,77 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import static org.junit.Assert.assertEquals;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.Types;
+import java.util.Arrays;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.connector.language.Command;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.JDBCProcedureExecution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.Translator;
+
+public class TestJDBCProcedureExecution {
+
+ @Test public void testProcedureExecution() throws Exception {
+ Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "exec pm2.spTest8a()"); //$NON-NLS-1$
+ Connection connection = Mockito.mock(Connection.class);
+ CallableStatement cs = Mockito.mock(CallableStatement.class);
+ Mockito.stub(cs.getUpdateCount()).toReturn(-1);
+ Mockito.stub(cs.getInt(1)).toReturn(5);
+ Mockito.stub(connection.prepareCall("{ call spTest8a(?)}")).toReturn(cs); //$NON-NLS-1$
+ Translator sqlTranslator = new Translator();
+
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
+ Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
+
+ JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
+ procedureExecution.execute();
+ assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
+ Mockito.verify(cs, Mockito.times(1)).registerOutParameter(1, Types.INTEGER);
+ }
+ @Test public void testProcedureExecution1() throws Exception {
+ Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "exec pm2.spTest8(1)"); //$NON-NLS-1$
+ Connection connection = Mockito.mock(Connection.class);
+ CallableStatement cs = Mockito.mock(CallableStatement.class);
+ Mockito.stub(cs.getUpdateCount()).toReturn(-1);
+ Mockito.stub(cs.getInt(2)).toReturn(5);
+ Mockito.stub(connection.prepareCall("{ call spTest8(?,?)}")).toReturn(cs); //$NON-NLS-1$
+ Translator sqlTranslator = new Translator();
+
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
+ Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
+
+ JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
+ procedureExecution.execute();
+ assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
+ Mockito.verify(cs, Mockito.times(1)).registerOutParameter(2, Types.INTEGER);
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCProcedureExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCUpdateExecution.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCUpdateExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCUpdateExecution.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.util.Arrays;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.ExpressionValueSource;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.language.Literal;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.JDBCUpdateExecution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.Translator;
+
+public class TestJDBCUpdateExecution {
+
+ @Test public void testBulkUpdate() throws Exception {
+ Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "insert into BQT1.SmallA (IntKey, IntNum) values (1, 2)"); //$NON-NLS-1$
+ Literal value = ((Literal)((ExpressionValueSource)((Insert)command).getValueSource()).getValues().get(0));
+ Literal value1 = ((Literal)((ExpressionValueSource)((Insert)command).getValueSource()).getValues().get(1));
+ value.setMultiValued(true);
+ value.setBindValue(true);
+ value.setValue(Arrays.asList(1, 2));
+ value1.setMultiValued(true);
+ value1.setBindValue(true);
+ value1.setValue(Arrays.asList(2, 3));
+ Connection connection = Mockito.mock(Connection.class);
+ PreparedStatement p = Mockito.mock(PreparedStatement.class);
+ Mockito.stub(p.executeBatch()).toReturn(new int [] {1, 1});
+ Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey, IntNum) VALUES (?, ?)")).toReturn(p); //$NON-NLS-1$
+
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
+ Mockito.stub(config.getTranslator()).toReturn(new Translator());
+
+ JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, Mockito.mock(ExecutionContext.class), config, config.getTranslator());
+ updateExecution.execute();
+ Mockito.verify(p, Mockito.times(2)).addBatch();
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TestJDBCUpdateExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TranslationHelper.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TranslationHelper.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TranslationHelper.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import junit.framework.Assert;
+
+import org.mockito.Mockito;
+import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+import com.metamatrix.cdk.api.TranslationUtility;
+import com.metamatrix.cdk.unittest.FakeTranslationFactory;
+import com.metamatrix.core.MetaMatrixRuntimeException;
+import com.metamatrix.query.function.metadata.FunctionMetadataReader;
+import com.metamatrix.query.function.metadata.FunctionMethod;
+
+public class TranslationHelper {
+
+ public static final String PARTS_VDB = "/PartsSupplier.vdb"; //$NON-NLS-1$
+ public static final String BQT_VDB = "/bqt.vdb"; //$NON-NLS-1$
+
+ public static Command helpTranslate(String vdbFileName, String sql) {
+ return helpTranslate(vdbFileName, null, sql);
+ }
+
+ public static Command helpTranslate(String vdbFileName, String udf, String sql) {
+ TranslationUtility util = null;
+ if (PARTS_VDB.equals(vdbFileName)) {
+ util = new TranslationUtility(TranslationHelper.class.getResource(vdbFileName));
+ } else if (BQT_VDB.equals(vdbFileName)){
+ util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
+ } else {
+ Assert.fail("unknown vdb"); //$NON-NLS-1$
+ }
+
+ if (udf != null) {
+ try {
+ Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
+ util.setUDF(methods);
+ } catch (IOException e) {
+ throw new MetaMatrixRuntimeException("failed to load UDF"); //$NON-NLS-1$
+ }
+ }
+ return util.parseCommand(sql);
+ }
+
+ public static void helpTestVisitor(String vdb, String input, String expectedOutput, Translator translator) throws ConnectorException {
+ helpTestVisitor(vdb,null,input, expectedOutput, translator);
+ }
+
+ public static void helpTestVisitor(String vdb, String udf, String input, String expectedOutput, Translator translator) throws ConnectorException {
+ // Convert from sql to objects
+ Command obj = helpTranslate(vdb, udf, input);
+
+ helpTestVisitor(expectedOutput, translator, obj);
+ }
+
+ public static void helpTestVisitor(String expectedOutput,
+ Translator translator, Command obj) throws ConnectorException {
+ TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
+ tc.translateCommand(obj);
+ assertEquals("Did not get correct sql", expectedOutput, tc.getSql()); //$NON-NLS-1$
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/resource/adapter/jdbc/TranslationHelper.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestEscapeSyntaxModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestEscapeSyntaxModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestEscapeSyntaxModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.translator;
+package org.teiid.translator.jdbc;
import java.sql.Timestamp;
import java.util.Arrays;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestExtractFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestExtractFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestExtractFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.translator;
+package org.teiid.translator.jdbc;
import java.sql.Timestamp;
import java.util.Arrays;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestLocateFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestLocateFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestLocateFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.translator;
+package org.teiid.translator.jdbc;
import static org.junit.Assert.assertEquals;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestModFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestModFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestModFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.translator;
+package org.teiid.translator.jdbc;
import java.math.BigDecimal;
import java.math.BigInteger;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestSQLConversionVisitor.java (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/extension/TestSQLConversionVisitor.java)
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestSQLConversionVisitor.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestSQLConversionVisitor.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -0,0 +1,451 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.dqp.internal.datamgr.impl.ExecutionContextImpl;
+import org.teiid.dqp.internal.datamgr.language.TestDeleteImpl;
+import org.teiid.dqp.internal.datamgr.language.TestInsertImpl;
+import org.teiid.dqp.internal.datamgr.language.TestProcedureImpl;
+import org.teiid.dqp.internal.datamgr.language.TestQueryImpl;
+import org.teiid.dqp.internal.datamgr.language.TestUpdateImpl;
+import org.teiid.dqp.internal.datamgr.language.TstLanguageBridgeFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
+
+/**
+ */
+public class TestSQLConversionVisitor {
+
+ public static final ExecutionContext context = new ExecutionContextImpl("VDB", //$NON-NLS-1$
+ 1,
+ "Payload", //$NON-NLS-1$
+ "ConnectionID", //$NON-NLS-1$
+ "Connector", //$NON-NLS-1$
+ "RequestID", //$NON-NLS-1$
+ "PartID", //$NON-NLS-1$
+ "ExecCount"); //$NON-NLS-1$
+
+ private static Translator TRANSLATOR;
+
+ @BeforeClass public static void oneTimeSetup() throws ConnectorException {
+ TRANSLATOR = new Translator();
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
+ env.setTrimStrings(true);
+ TRANSLATOR.initialize(env);
+ }
+
+ public String getTestVDB() {
+ return TranslationHelper.PARTS_VDB;
+ }
+
+ public void helpTestVisitor(String vdb, String input, String expectedOutput) {
+ helpTestVisitor(vdb, input, expectedOutput, false);
+ }
+
+ public void helpTestVisitor(String vdb, String input, String expectedOutput, boolean usePreparedStatement) {
+ Translator trans = new Translator();
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
+ if (usePreparedStatement) {
+ env.setUseBindVariables(true);
+ }
+ try {
+ trans.initialize(env);
+ TranslationHelper.helpTestVisitor(vdb, input, expectedOutput, trans);
+ } catch (ConnectorException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static final RuntimeMetadata metadata = TstLanguageBridgeFactory.metadataFactory;
+
+ private String getStringWithContext(LanguageObject obj) throws ConnectorException {
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
+ env.setUseCommentsInSourceQuery(true);
+ Translator trans = new Translator();
+ trans.initialize(env);
+ SQLConversionVisitor visitor = trans.getSQLConversionVisitor();
+ visitor.setExecutionContext(context);
+ visitor.append(obj);
+ return visitor.toString();
+ }
+
+ @Test public void testSimple() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testAliasInSelect() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name as x from parts", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME AS x FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testAliasedGroup() {
+ helpTestVisitor(getTestVDB(),
+ "select y.part_name from parts y", //$NON-NLS-1$
+ "SELECT y.PART_NAME FROM PARTS AS y"); //$NON-NLS-1$
+ }
+
+ @Test public void testAliasedGroupAndElement() {
+ helpTestVisitor(getTestVDB(),
+ "select y.part_name AS z from parts y", //$NON-NLS-1$
+ "SELECT y.PART_NAME AS z FROM PARTS AS y"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralString() {
+ helpTestVisitor(getTestVDB(),
+ "select 'x' from parts", //$NON-NLS-1$
+ "SELECT 'x' FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralInteger() {
+ helpTestVisitor(getTestVDB(),
+ "select 5 from parts", //$NON-NLS-1$
+ "SELECT 5 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralFloat() {
+ helpTestVisitor(getTestVDB(),
+ "select 5.2 from parts", //$NON-NLS-1$
+ "SELECT 5.2 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralLowFloat() {
+ helpTestVisitor(getTestVDB(),
+ "select 0.012 from parts", //$NON-NLS-1$
+ "SELECT 0.012 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralLowFloat2() {
+ helpTestVisitor(getTestVDB(),
+ "select 0.00012 from parts", //$NON-NLS-1$
+ "SELECT 0.00012 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralHighFloat() {
+ helpTestVisitor(getTestVDB(),
+ "select 12345.123 from parts", //$NON-NLS-1$
+ "SELECT 12345.123 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralHighFloat2() {
+ helpTestVisitor(getTestVDB(),
+ "select 1234567890.1234567 from parts", //$NON-NLS-1$
+ "SELECT 1234567890.1234567 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralBoolean() {
+ helpTestVisitor(getTestVDB(),
+ "select {b'true'}, {b'false'} from parts", //$NON-NLS-1$
+ "SELECT 1, 0 FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralDate() {
+ helpTestVisitor(getTestVDB(),
+ "select {d '2003-12-31'} from parts", //$NON-NLS-1$
+ "SELECT {d '2003-12-31'} FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralTime() {
+ helpTestVisitor(getTestVDB(),
+ "select {t '23:59:59'} from parts", //$NON-NLS-1$
+ "SELECT {t '23:59:59'} FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralNull() {
+ helpTestVisitor(getTestVDB(),
+ "select null from parts", //$NON-NLS-1$
+ "SELECT NULL FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testLiteralTimestamp() {
+ helpTestVisitor(getTestVDB(),
+ "select {ts '2003-12-31 23:59:59.123'} from parts", //$NON-NLS-1$
+ "SELECT {ts '2003-12-31 23:59:59.123'} FROM PARTS"); //$NON-NLS-1$
+ }
+
+ @Test public void testSQL89Join() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p, supplier_parts s where p.part_id = s.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM PARTS AS p, SUPPLIER_PARTS AS s WHERE p.PART_ID = s.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testSQL92Join() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p join supplier_parts s on p.part_id = s.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM PARTS AS p INNER JOIN SUPPLIER_PARTS AS s ON p.PART_ID = s.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testSelfJoin() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p join parts p2 on p.part_id = p2.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM PARTS AS p INNER JOIN PARTS AS p2 ON p.PART_ID = p2.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testRightOuterJoin() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p right join supplier_parts s on p.part_id = s.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM SUPPLIER_PARTS AS s LEFT OUTER JOIN PARTS AS p ON p.PART_ID = s.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testLeftOuterJoin() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p left join supplier_parts s on p.part_id = s.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM PARTS AS p LEFT OUTER JOIN SUPPLIER_PARTS AS s ON p.PART_ID = s.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testFullOuterJoin() {
+ helpTestVisitor(getTestVDB(),
+ "select p.part_name from parts p full join supplier_parts s on p.part_id = s.part_id", //$NON-NLS-1$
+ "SELECT p.PART_NAME FROM PARTS AS p FULL OUTER JOIN SUPPLIER_PARTS AS s ON p.PART_ID = s.PART_ID"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare1() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id = 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare2() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id <> 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID <> 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare3() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id < 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID < 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare4() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id <= 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID <= 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare5() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id > 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID > 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testCompare6() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id >= 'x'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID >= 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testIn1() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id in ('x')", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID = 'x'"); //$NON-NLS-1$
+ }
+
+ @Test public void testIn2() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id in ('x', 'y')", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID IN ('x', 'y')"); //$NON-NLS-1$
+ }
+
+ @Test public void testIn3() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id not in ('x', 'y')", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID NOT IN ('x', 'y')"); //$NON-NLS-1$
+ }
+
+ @Test public void testIsNull1() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id is null", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID IS NULL"); //$NON-NLS-1$
+ }
+
+ @Test public void testIsNull2() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id is not null", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID IS NOT NULL"); //$NON-NLS-1$
+ }
+
+ @Test public void testInsertNull() {
+ helpTestVisitor(getTestVDB(),
+ "insert into parts (part_id, part_name, part_color, part_weight) values ('a', null, 'c', 'd')", //$NON-NLS-1$
+ "INSERT INTO PARTS (PART_ID, PART_NAME, PART_COLOR, PART_WEIGHT) VALUES ('a', NULL, 'c', 'd')"); //$NON-NLS-1$
+ }
+
+ @Test public void testUpdateNull() {
+ helpTestVisitor(getTestVDB(),
+ "update parts set part_weight = null where part_color = 'b'", //$NON-NLS-1$
+ "UPDATE PARTS SET PART_WEIGHT = NULL WHERE PARTS.PART_COLOR = 'b'"); //$NON-NLS-1$
+ }
+
+ @Test public void testUpdateWhereNull() {
+ helpTestVisitor(getTestVDB(),
+ "update parts set part_weight = 'a' where part_weight = null", //$NON-NLS-1$
+ "UPDATE PARTS SET PART_WEIGHT = 'a' WHERE NULL <> NULL"); //$NON-NLS-1$
+ }
+
+ @Test public void testPreparedStatementCreationWithUpdate() {
+ helpTestVisitor(getTestVDB(),
+ "update parts set part_weight = 'a' where part_weight < 5", //$NON-NLS-1$
+ "UPDATE PARTS SET PART_WEIGHT = ? WHERE PARTS.PART_WEIGHT < ?", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testPreparedStatementCreationWithInsert() {
+ helpTestVisitor(getTestVDB(),
+ "insert into parts (part_weight) values (5)", //$NON-NLS-1$
+ "INSERT INTO PARTS (PART_WEIGHT) VALUES (?)", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testPreparedStatementCreationWithSelect() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_id not in ('x', 'y') and part_weight < 6", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_ID NOT IN (?, ?) AND PARTS.PART_WEIGHT < ?", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testPreparedStatementCreationWithLike() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where part_name like '%foo'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_NAME LIKE ?", //$NON-NLS-1$
+ true);
+ }
+
+ /**
+ * ideally this should not happen, but to be on the safe side
+ * only the right side should get replaced
+ */
+ public void defer_testPreparedStatementCreationWithLeftConstant() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where 'x' = 'y'", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE 1 = ?", //$NON-NLS-1$
+ true);
+ }
+
+ /**
+ * In the future, functions can be made smarter about which of their literal arguments
+ * either are (or are not) eligible to be bind variables
+ */
+ @Test public void testPreparedStatementCreationWithFunction() {
+ helpTestVisitor(getTestVDB(),
+ "select part_name from parts where concat(part_name, 'x') = concat('y', part_weight)", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE concat(PARTS.PART_NAME, 'x') = concat('y', PARTS.PART_WEIGHT)", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testPreparedStatementCreationWithCase() {
+ helpTestVisitor(getTestVDB(),
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_WEIGHT = CASE WHEN PARTS.PART_NAME='a' THEN 'b' ELSE 'c' END", //$NON-NLS-1$
+ "SELECT PARTS.PART_NAME FROM PARTS WHERE PARTS.PART_WEIGHT = CASE WHEN PARTS.PART_NAME = ? THEN 'b' ELSE 'c' END", //$NON-NLS-1$
+ true);
+ }
+
+ @Test public void testVisitIDeleteWithComment() throws Exception {
+ String expected = "DELETE /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ FROM g1 WHERE 100 >= 200 AND 500 < 600"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestDeleteImpl.example()));
+ }
+
+ @Test public void testVisitIInsertWithComment() throws Exception {
+ String expected = "INSERT /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ INTO g1 (e1, e2, e3, e4) VALUES (1, 2, 3, 4)"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestInsertImpl.example("g1"))); //$NON-NLS-1$
+ }
+
+ @Test public void testVisitISelectWithComment() throws Exception {
+ String expected = "SELECT /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ g1.e1, g1.e2, g1.e3, g1.e4 FROM g1, g2 AS myAlias, g3, g4 WHERE 100 >= 200 AND 500 < 600 GROUP BY g1.e1, g1.e2, g1.e3, g1.e4 HAVING 100 >= 200 AND 500 < 600 ORDER BY e1, e2 DESC, e3, e4 DESC"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestQueryImpl.example(false)));
+ expected = "SELECT /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ DISTINCT g1.e1, g1.e2, g1.e3, g1.e4 FROM g1, g2 AS myAlias, g3, g4 WHERE 100 >= 200 AND 500 < 600 GROUP BY g1.e1, g1.e2, g1.e3, g1.e4 HAVING 100 >= 200 AND 500 < 600 ORDER BY e1, e2 DESC, e3, e4 DESC"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestQueryImpl.example(true)));
+ }
+
+ @Test public void testVisitIUpdateWithComment() throws Exception {
+ String expected = "UPDATE /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ g1 SET e1 = 1, e2 = 1, e3 = 1, e4 = 1 WHERE 1 = 1"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestUpdateImpl.example()));
+ }
+
+ @Test public void testVisitIProcedureWithComment() throws Exception {
+ String expected = "{ /*teiid sessionid:ConnectionID, requestid:RequestID.PartID*/ call sq3(?,?)}"; //$NON-NLS-1$
+ assertEquals(expected, getStringWithContext(TestProcedureImpl.example()));
+ }
+
+ @Test public void testTrimStrings() throws Exception {
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, "select stringkey from bqt1.smalla", "SELECT rtrim(SmallA.StringKey) FROM SmallA", TRANSLATOR); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Test public void testNestedSetQuery() throws Exception {
+ String input = "select part_id id FROM parts UNION ALL (select part_name FROM parts UNION select part_id FROM parts)"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS UNION ALL (SELECT PARTS.PART_NAME FROM PARTS UNION SELECT rtrim(PARTS.PART_ID) FROM PARTS)"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testNestedSetQuery1() throws Exception {
+ String input = "select part_id id FROM parts UNION (select part_name FROM parts EXCEPT select part_id FROM parts)"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS UNION (SELECT PARTS.PART_NAME FROM PARTS EXCEPT SELECT rtrim(PARTS.PART_ID) FROM PARTS)"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testNestedSetQuery2() throws Exception {
+ String input = "select part_id id FROM parts UNION select part_name FROM parts EXCEPT select part_id FROM parts"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS UNION SELECT PARTS.PART_NAME FROM PARTS EXCEPT SELECT rtrim(PARTS.PART_ID) FROM PARTS"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testNestedSetQuery3() throws Exception {
+ String input = "select part_id id FROM parts UNION (select part_name FROM parts Union ALL select part_id FROM parts)"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS UNION SELECT PARTS.PART_NAME FROM PARTS UNION SELECT rtrim(PARTS.PART_ID) FROM PARTS"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
+
+ @Test public void testOrderByUnrelated() throws Exception {
+ String input = "select part_id id FROM parts order by part_name"; //$NON-NLS-1$
+ String output = "SELECT rtrim(PARTS.PART_ID) AS id FROM PARTS ORDER BY PARTS.PART_NAME"; //$NON-NLS-1$
+
+ TranslationHelper.helpTestVisitor(TranslationHelper.PARTS_VDB,
+ input,
+ output, TRANSLATOR);
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TestSQLConversionVisitor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access/TestAccessSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access/TestAccessSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access/TestAccessSQLTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.access;
+package org.teiid.translator.jdbc.access;
import junit.framework.TestCase;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2 (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2ConvertModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2ConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2ConvertModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.db2;
+package org.teiid.translator.jdbc.db2;
import java.math.BigDecimal;
import java.math.BigInteger;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2SqlTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,17 +20,17 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.db2;
+package org.teiid.translator.jdbc.db2;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.connector.language.Command;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.resource.cci.ExecutionContext;
import org.teiid.translator.jdbc.TranslatedCommand;
import org.teiid.translator.jdbc.db2.DB2SQLTranslator;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbyCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.derby;
+package org.teiid.translator.jdbc.derby;
import static org.junit.Assert.*;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbySQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbySQLTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,14 +20,14 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.derby;
+package org.teiid.translator.jdbc.derby;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.derby.DerbySQLTranslator;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/h2 (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/h2/TestH2Translator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2/TestH2Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/h2/TestH2Translator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,13 +20,13 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.h2;
+package org.teiid.translator.jdbc.h2;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.h2.H2Translator;
public class TestH2Translator {
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQL5Translator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQL5Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQL5Translator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,13 +20,13 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.mysql;
+package org.teiid.translator.jdbc.mysql;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.mysql.MySQL5Translator;
/**
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/TestMySQLTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,14 +20,14 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.mysql;
+package org.teiid.translator.jdbc.mysql;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.mysql.MySQLTranslator;
/**
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import java.sql.Timestamp;
import java.util.Arrays;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLeftOrRightFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLeftOrRightFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLeftOrRightFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import java.util.Arrays;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLog10FunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLog10FunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestLog10FunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import java.util.Arrays;
import java.util.List;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import java.sql.Timestamp;
import java.util.Arrays;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleConvertModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleConvertModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import static org.junit.Assert.assertEquals;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import static org.junit.Assert.assertEquals;
@@ -28,7 +28,6 @@
import org.junit.Before;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.connector.language.Command;
import org.teiid.connector.metadata.runtime.Column;
import org.teiid.connector.metadata.runtime.MetadataStore;
@@ -40,6 +39,7 @@
import org.teiid.metadata.TransformationMetadata;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.resource.cci.ExecutionContext;
import org.teiid.translator.jdbc.TranslatedCommand;
import org.teiid.translator.jdbc.Translator;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestSubstringFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestSubstringFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestSubstringFunctionModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
import java.util.Arrays;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/TestPostgreSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,13 +20,13 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.postgresql;
+package org.teiid.translator.jdbc.postgresql;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.postgresql.PostgreSQLTranslator;
public class TestPostgreSQLTranslator {
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,13 +20,12 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.sqlserver;
+package org.teiid.translator.jdbc.sqlserver;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.connector.language.Command;
import org.teiid.connector.metadata.runtime.Column;
import org.teiid.connector.metadata.runtime.MetadataStore;
@@ -36,6 +35,7 @@
import org.teiid.metadata.TransformationMetadata;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator;
import com.metamatrix.cdk.api.TranslationUtility;
Copied: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase (from rev 2103, trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase)
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseConvertModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseConvertModifier.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,7 +20,7 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.sybase;
+package org.teiid.translator.jdbc.sybase;
import static org.junit.Assert.assertEquals;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseSQLConversionVisitor.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseSQLConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/TestSybaseSQLConversionVisitor.java 2010-05-07 20:11:50 UTC (rev 2104)
@@ -20,17 +20,17 @@
* 02110-1301 USA.
*/
-package org.teiid.connector.jdbc.sybase;
+package org.teiid.translator.jdbc.sybase;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.connector.language.Command;
import org.teiid.resource.ConnectorException;
import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.TranslationHelper;
import org.teiid.resource.cci.ExecutionContext;
import org.teiid.translator.jdbc.TranslatedCommand;
import org.teiid.translator.jdbc.sybase.SybaseSQLTranslator;
Deleted: trunk/connectors/translator-text/src/test/resources/EmpData.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/EmpData.txt 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-text/src/test/resources/EmpData.txt 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,51 +0,0 @@
-LastName,FirstName,MiddleName,EmpId,Department,AnnualSalary,Title,HomePhone,Manager,Street,City,State,Zip
-Kisselburg,Abbiegale,Tikvica ,9000059,G,64000,MGMT WannaBe,670-270-7947,9000073,123 State St.,New York,NY,10001
-Glore,Diodie,Vojvoda ,9000060,G,71000,Associate,480-650-9750,9000073,127 State St.,Los Angeles,CA,10005
-Dawson,Pinckney,Ostoja ,9000061,G,71000,Associate,110-400-3600,9000073,135 State St.,Detroit,MI,10013
-Waldrip,Trixie,Curic ,9000062,G,57000,Newbie,820-210-7045,9000073,136 State St.,Albany,NY,10014
-Kitchen,Zilpha,Buic ,9000063,G,60000,MGMT WannaBe,660-390-3785,9000073,138 State St.,Trenton,NJ,10016
-Wakeman,Gerard,Vlahovic ,9000064,G,78000,Newbie,700-190-5880,9000073,130 State St.,Jefferson City,MO,10008
-Rafferty,Dock,Korda ,9000065,G,70000,Newbie,400-190-6192,9000073,128 State St.,Sacramento,CA,10006
-Kersavage,Zelda,Mjesecevic ,9000066,G,56000,MGMT WannaBe,802-930-1482,9000073,137 State St.,Montpelier,VT,10015
-Zummer,Gerda,Milan ,9000067,G,69000,Newbie,920-100-9701,9000073,131 State St.,Bangor,ME,10009
-Davies,Allwyne,Radic ,9000068,G,61000,Associate,470-820-6096,9000073,126 State St.,Montgomery,AL,10004
-Deanford,Abe,Skrabalo ,9000069,G,67000,Associate,907-660-8233,9000073,124 State St.,Juneau,AK,10002
-Garcia,Orsal,Ucovic ,9000070,ML,79000,CFO,480-490-7710,9000075,150 State St.,Phoenix,AZ,10028
-Zook,Orson,Bendevis ,9000071,G,71000,Newbie,350-260-8654,9000073,133 State St.,Boston,MA,10011
-Rainier,Adelaid,Marinovic ,9000072,G,67000,Newbie,316-550-3499,9000073,125 State St.,Topeka,KS,10003
-Nealon,General,,9000073,G,77000,COO,203-420-3113,9000075,129 State St.,Hartford,CT,10007
-Garahana,Jarrod,Cvjetkovic ,9000074,G,66000,Associate,620-430-1782,9000073,132 State St.,New York,NY,10010
-Neely,Petronella,Goravica ,9000075,G,80000,CEO,230-320-6330,,134 State St.,Los Angeles,CA,10012
-Gamble,Johney,Kordic ,9000123,TM,74000,Associate,330-200-8319,9000132,162 State St.,Detroit,MI,10040
-Gertanovich,Orthell,Tvrdisa ,9000124,TM,63000,Associate,600-410-3667,9000132,165 State St.,Albany,NY,10043
-Kenyon,Jim,Radovanovic ,9000125,TM,80000,MGMT WannaBe,800-510-7741,9000132,161 State St.,Trenton,NJ,10039
-Gerber,Tristan,Rogec ,9000126,TM,57000,Associate,120-990-7278,9000132,169 State St.,Jefferson City,MO,10047
-Gibb,Jaromy,Kristic ,9000127,TM,69000,Associate,270-390-9549,9000132,160 State St.,Sacramento,CA,10038
-Rader,Allissa,Radicevic ,9000128,TM,59000,Newbie,750-420-2128,9000132,157 State St.,Montpelier,VT,10035
-Kammerer,Dilbert,Capor ,9000129,TM,70000,Associate,700-280-3808,9000132,159 State St.,Bangor,ME,10037
-Knippers,Tuesday,Balic ,9000130,TM,68000,MGMT WannaBe,960-140-1045,9000132,170 State St.,Montgomery,AL,10048
-Zumwalt,Patrycia,Srezovic ,9000131,TM,72000,Newbie,210-400-7920,9000132,167 State St.,Juneau,AK,10045
-Needham,Katlyn,Metkovic ,9000132,TM,76000,Goon,380-210-1611,9000070,163 State St.,Phoenix,AZ,10041
-Keefer,Almedia,,9000133,TM,61000,MGMT WannaBe,850-640-3038,9000132,158 State St.,Boston,MA,10036
-Rampton,Orman,Cavelis ,9000134,TM,76000,Newbie,950-930-1038,9000132,164 State St.,Topeka,KS,10042
-Krepps,Paul,Skobelj ,9000135,TM,64000,MGMT WannaBe,430-500-8830,9000132,168 State St.,Hartford,CT,10046
-Deans,Zeno,Jozovic ,9000136,TM,79000,Associate,830-190-9156,9000132,172 State St.,New York,NY,10050
-Zarafonetis,Parazetti,Roncevic ,9000137,TM,73000,Newbie,710-890-2886,9000132,166 State St.,Los Angeles,CA,10044
-Davis,Tyler,Vukic ,9000138,TM,80000,Associate,540-420-5160,9000132,171 State St.,Detroit,MI,10049
-Randolph,Orwin,Rasica ,9010233,ML,44000,Newbie,200-870-4749,9000070,151 State St.,Albany,NY,10029
-Ramsey,Orran,Slade ,9010234,ML,42000,Newbie,500-830-2947,9000070,149 State St.,Trenton,NJ,10027
-Wagonlander,Blondeena,Djano ,9010235,ML,41000,Newbie,780-760-9188,9000070,141 State St.,Jefferson City,MO,10019
-Wadsworth,Alice,Hasan ,9010236,ML,40000,Newbie,230-360-1247,9000070,140 State St.,Sacramento,CA,10018
-Nolen,Parnell,Buconic ,9010237,ML,47000,Newbie,620-300-7125,9000070,152 State St.,Montpelier,VT,10030
-Glidewell,Xoe,Bagovic ,9010238,ML,45000,Associate,850-850-5647,9000070,156 State St.,Bangor,ME,10034
-Zutter,Adam,Hendic ,9010239,ML,48000,Newbie,890-300-9999,9000070,139 State St.,Montgomery,AL,10017
-Gale,Turwayne,Dalmatin ,9010240,ML,36000,Associate,600-290-9758,9000070,154 State St.,Juneau,AK,10032
-Krikwood,Javin,Vidak ,9010241,ML,42000,MGMT WannaBe,380-280-5100,9000070,146 State St.,Phoenix,AZ,10024
-Giggs,Philbert,Vidak ,9010242,ML,52000,Associate,620-270-6404,9000070,153 State St.,Boston,MA,10031
-Danford,Garnett,Brigovic ,9010243,ML,39000,Associate,880-160-7833,9000070,145 State St.,Topeka,KS,10023
-Nash,Xavier,Semes ,9010244,ML,53000,MGMT WannaBe,800-550-5917,9000070,155 State St.,Hartford,CT,10033
-Kasparek,Gallard,Jelic ,9010245,ML,47000,Associate,590-460-5850,9000070,144 State St.,New York,NY,10022
-Kernodle,Dextor,Bupic ,9010246,ML,55000,MGMT WannaBe,440-750-1427,9000070,142 State St.,Los Angeles,CA,10020
-Neighbors,Karron,Stuk ,9010247,ML,40000,Newbie,430-790-9550,9000070,147 State St.,Detroit,MI,10025
-Gilbertson,Doil,Radic ,9010248,ML,51000,Associate,870-510-5367,9000070,143 State St.,Albany,NY,10021
-Neilsen,Katheleen,,9010249,ML,36000,Newbie,550-200-5470,9000070,148 State St.,Trenton,NJ,10026
Deleted: trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,4 +0,0 @@
-Employees.EmpTable.location = src/test/resources/EmpData.txt
-Employees.EmpTable.qualifier = "
-Employees.EmpTable.delimiter = ,
-Employees.EmpTable.skipHeaderLines = 1
Deleted: trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,2 +0,0 @@
-"1", "2003-03-25", "Blind"
-"2","1998-04-29", "Antipop"
\ No newline at end of file
Deleted: trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt 2010-05-07 16:24:50 UTC (rev 2103)
+++ trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt 2010-05-07 20:11:50 UTC (rev 2104)
@@ -1,6 +0,0 @@
-text.library.location = src/test/resources/libraryDelimited.txt
-text.library.qualifier = "
-text.library.delimiter = ,
-text.library2.location = src/test/resources/libraryDelimited2.txt
-text.library2.qualifier = "
-text.library2.delimiter = ,
13 years, 11 months
teiid SVN: r2103 - in trunk: build/assembly/jboss-container and 280 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-07 12:24:50 -0400 (Fri, 07 May 2010)
New Revision: 2103
Added:
trunk/build/kits/jboss-container/deploy/teiid/connectors/
trunk/build/kits/jboss-container/deploy/teiid/connectors/access-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/db2-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/derby-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/h2-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/hsql-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/ldap-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/loopback-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/mysql-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/oracle-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/postgresql-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/salesforce-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/sqlserver-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/sybase-translator.xml
trunk/build/kits/jboss-container/deploy/teiid/connectors/text-translator.xml
trunk/client/src/main/java/org/teiid/adminapi/Translator.java
trunk/client/src/main/java/org/teiid/adminapi/impl/TranslatorMetaData.java
trunk/client/src/test/java/org/teiid/adminapi/impl/TestTranslatorMetadata.java
trunk/connector-api/src/main/java/org/teiid/logging/AuditMessage.java
trunk/connector-api/src/main/java/org/teiid/logging/CommandLogMessage.java
trunk/connector-api/src/main/java/org/teiid/logging/JavaLogWriter.java
trunk/connector-api/src/main/java/org/teiid/logging/LogConstants.java
trunk/connector-api/src/main/java/org/teiid/logging/LogListener.java
trunk/connector-api/src/main/java/org/teiid/logging/LogManager.java
trunk/connector-api/src/main/java/org/teiid/logging/LogMessage.java
trunk/connector-api/src/main/java/org/teiid/logging/MessageLevel.java
trunk/connector-api/src/main/java/org/teiid/resource/
trunk/connector-api/src/main/java/org/teiid/resource/ConnectorException.java
trunk/connector-api/src/main/java/org/teiid/resource/adapter/
trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicConnectorCapabilities.java
trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecution.java
trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecutionFactory.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/
trunk/connector-api/src/main/java/org/teiid/resource/cci/CacheScope.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/ConnectorCapabilities.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/DataNotAvailableException.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/Execution.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionContext.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionFactory.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/MetadataProvider.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/ProcedureExecution.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/ResultSetExecution.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/SourceSystemFunctions.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/TranslatorProperty.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacility.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacilityImpl.java
trunk/connector-api/src/main/java/org/teiid/resource/cci/UpdateExecution.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/
trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnection.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnectionFactory.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnection.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnectionFactory.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicResourceAdapter.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionContext.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionRequestInfoWrapper.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnection.java
trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnectionFactory.java
trunk/connector-api/src/test/java/org/teiid/connector/TestBasicExecutionFactory.java
trunk/connector-api/src/test/java/org/teiid/logging/
trunk/connector-api/src/test/java/org/teiid/logging/TestLogManager.java
trunk/connectors/connector-ldap/src/main/java/org/
trunk/connectors/connector-ldap/src/main/java/org/teiid/
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectionImpl.java
trunk/connectors/connector-ldap/src/main/resources/org/
trunk/connectors/connector-ldap/src/main/resources/org/teiid/
trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/
trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/
trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/
trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/i18n.properties
trunk/connectors/connector-ldap/src/test/java/org/
trunk/connectors/connector-ldap/src/test/java/org/teiid/
trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/
trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/
trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/
trunk/connectors/connector-salesforce/src/main/java/org/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesForceManagedConnectionFactory.java
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesforceConnectionImpl.java
trunk/connectors/connector-text/src/main/java/org/
trunk/connectors/connector-text/src/main/java/org/teiid/
trunk/connectors/connector-text/src/main/java/org/teiid/resource/
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionFactory.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionImpl.java
trunk/connectors/connector-text/src/main/resources/org/
trunk/connectors/connector-text/src/main/resources/org/teiid/
trunk/connectors/connector-text/src/main/resources/org/teiid/resource/
trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/
trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/text/
trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/text/i18n.properties
trunk/connectors/sandbox/translator-yahoo/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/TickerCollectorVisitor.java
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooCapabilities.java
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecution.java
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecutionFactory.java
trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooPlugin.java
trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/yahoo/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/yahoo/i18n.properties
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/yahoo/
trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/yahoo/TestYahooTranslation.java
trunk/connectors/translator-jdbc/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCBaseExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionException.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionFactory.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCMetdataProcessor.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCProcedureExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCQueryExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCUpdateExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/SimpleCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ConvertModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ExtractFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/LocateFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/Translator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2Capabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2SQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbySQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Capabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Translator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/AddDiffModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mm/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mm/MMCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/BitFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Capabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Translator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/ConcatFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/DayWeekQuarterFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/LeftOrRightFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/Log10FunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/MonthOrDayNameFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/SequeLinkOracleCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/LocateFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SubstringFunctionModifier.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseSQLTranslator.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataCapabilities.java
trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml
trunk/connectors/translator-jdbc/src/main/resources/META-INF/
trunk/connectors/translator-jdbc/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/
trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/jdbc/
trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/jdbc/i18n.properties
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java
trunk/connectors/translator-ldap/
trunk/connectors/translator-ldap/pom.xml
trunk/connectors/translator-ldap/src/
trunk/connectors/translator-ldap/src/main/
trunk/connectors/translator-ldap/src/main/java/
trunk/connectors/translator-ldap/src/main/java/org/
trunk/connectors/translator-ldap/src/main/java/org/teiid/
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/IQueryToLdapSearchParser.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnection.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorCapabilities.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorConstants.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPExecutionFactory.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPPlugin.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSearchDetails.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSyncQueryExecution.java
trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPUpdateExecution.java
trunk/connectors/translator-ldap/src/main/resources/
trunk/connectors/translator-ldap/src/main/resources/META-INF/
trunk/connectors/translator-ldap/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-ldap/src/main/resources/org/
trunk/connectors/translator-ldap/src/main/resources/org/teiid/
trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/
trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/
trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/ldap/
trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/ldap/i18n.properties
trunk/connectors/translator-ldap/src/test/
trunk/connectors/translator-ldap/src/test/java/
trunk/connectors/translator-ldap/src/test/java/org/
trunk/connectors/translator-ldap/src/test/java/org/teiid/
trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/
trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/
trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/ldap/
trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/ldap/TestIQueryToLdapSearchParser.java
trunk/connectors/translator-ldap/src/test/resources/
trunk/connectors/translator-loopback/
trunk/connectors/translator-loopback/src/main/java/org/
trunk/connectors/translator-loopback/src/main/java/org/teiid/
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackCapabilities.java
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecution.java
trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecutionFactory.java
trunk/connectors/translator-loopback/src/main/resources/META-INF/
trunk/connectors/translator-loopback/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-loopback/src/test/java/org/
trunk/connectors/translator-loopback/src/test/java/org/teiid/
trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/
trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/
trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/
trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoobackAsynch.java
trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoopbackExecution.java
trunk/connectors/translator-salesforce/
trunk/connectors/translator-salesforce/pom.xml
trunk/connectors/translator-salesforce/src/
trunk/connectors/translator-salesforce/src/main/
trunk/connectors/translator-salesforce/src/main/java/
trunk/connectors/translator-salesforce/src/main/java/org/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Constants.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Messages.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/MetadataProcessor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/NameUtil.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Relationship.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/RelationshipImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceExecutionFactory.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForcePlugin.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceCapabilities.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnection.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Util.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/AbstractUpdateExecution.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DataPayload.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeleteExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedObject.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedResult.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetDeletedExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetUpdatedExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/InsertExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParent.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParentImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/QueryExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/SalesforceProcedureExecution.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdateExecutionImpl.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdatedResult.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/CriteriaVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/DeleteVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/ICriteriaVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/IQueryProvidingVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/InsertVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/JoinQueryVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/SelectVisitor.java
trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/UpdateVisitor.java
trunk/connectors/translator-salesforce/src/main/resources/
trunk/connectors/translator-salesforce/src/main/resources/META-INF/
trunk/connectors/translator-salesforce/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-salesforce/src/main/resources/org/
trunk/connectors/translator-salesforce/src/main/resources/org/teiid/
trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/
trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/
trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/salesforce/
trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/salesforce/i18n.properties
trunk/connectors/translator-salesforce/src/test/
trunk/connectors/translator-salesforce/src/test/java/
trunk/connectors/translator-salesforce/src/test/java/org/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/visitors/
trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/visitors/TestVisitors.java
trunk/connectors/translator-salesforce/src/test/resources/
trunk/connectors/translator-salesforce/src/test/resources/documents/
trunk/connectors/translator-text/
trunk/connectors/translator-text/pom.xml
trunk/connectors/translator-text/src/
trunk/connectors/translator-text/src/main/
trunk/connectors/translator-text/src/main/java/
trunk/connectors/translator-text/src/main/java/org/
trunk/connectors/translator-text/src/main/java/org/teiid/
trunk/connectors/translator-text/src/main/java/org/teiid/resource/
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/StringToDateTranslator.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextCapabilities.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextConnection.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextDescriptorPropertyNames.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextExecutionFactory.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextPlugin.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextSynchExecution.java
trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextUtil.java
trunk/connectors/translator-text/src/main/resources/
trunk/connectors/translator-text/src/main/resources/META-INF/
trunk/connectors/translator-text/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-text/src/main/resources/org/
trunk/connectors/translator-text/src/main/resources/org/teiid/
trunk/connectors/translator-text/src/main/resources/org/teiid/resource/
trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/
trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/text/
trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/text/i18n.properties
trunk/connectors/translator-text/src/test/
trunk/connectors/translator-text/src/test/java/
trunk/connectors/translator-text/src/test/java/org/
trunk/connectors/translator-text/src/test/java/org/teiid/
trunk/connectors/translator-text/src/test/java/org/teiid/resource/
trunk/connectors/translator-text/src/test/java/org/teiid/resource/adapter/
trunk/connectors/translator-text/src/test/java/org/teiid/resource/adapter/text/
trunk/connectors/translator-text/src/test/resources/
trunk/connectors/translator-text/src/test/resources/EmpData.txt
trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt
trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt
trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/TranslatorRepository.java
trunk/runtime/src/main/java/org/teiid/deployers/ExtendedPropertyMetadata.java
trunk/runtime/src/main/java/org/teiid/deployers/ManagedPropertyUtil.java
trunk/runtime/src/main/java/org/teiid/deployers/TranslatorDeployer.java
trunk/runtime/src/main/java/org/teiid/deployers/TranslatorParserDeployer.java
trunk/runtime/src/main/java/org/teiid/deployers/TranslatorPropertyUtil.java
trunk/runtime/src/main/java/org/teiid/templates/
trunk/runtime/src/main/java/org/teiid/templates/TranslatorDeploymentTemplate.java
trunk/runtime/src/main/java/org/teiid/templates/TranslatorMetadataICF.java
trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfo.java
trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfoFactory.java
trunk/runtime/src/test/java/org/teiid/deployers/TestExtendedPropertyMetadata.java
trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java
Removed:
trunk/client/src/main/java/org/teiid/adminapi/ConnectionFactory.java
trunk/client/src/main/java/org/teiid/adminapi/ConnectionPoolStatistics.java
trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionFactoryMetaData.java
trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionPoolStatisticsMetadata.java
trunk/connector-api/src/main/java/org/teiid/connector/api/CacheScope.java
trunk/connector-api/src/main/java/org/teiid/connector/api/Connection.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectionContext.java
trunk/connector-api/src/main/java/org/teiid/connector/api/Connector.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorCapabilities.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorEnvironment.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorException.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorLogger.java
trunk/connector-api/src/main/java/org/teiid/connector/api/DataNotAvailableException.java
trunk/connector-api/src/main/java/org/teiid/connector/api/Execution.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ExecutionContext.java
trunk/connector-api/src/main/java/org/teiid/connector/api/MetadataProvider.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ProcedureExecution.java
trunk/connector-api/src/main/java/org/teiid/connector/api/ResultSetExecution.java
trunk/connector-api/src/main/java/org/teiid/connector/api/TypeFacility.java
trunk/connector-api/src/main/java/org/teiid/connector/api/UpdateExecution.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnection.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnector.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnectorCapabilities.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicExecution.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnection.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnectionFactory.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicResourceAdapter.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/ConnectionRequestInfoWrapper.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/DefaultConnectorLogger.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/TypeFacilityImpl.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnection.java
trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnector.java
trunk/connector-api/src/main/java/org/teiid/logging/api/
trunk/connector-api/src/test/java/org/teiid/connector/TestWrappedConnector.java
trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/IQueryToLdapSearchParser.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnection.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnector.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorCapabilities.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorConstants.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSearchDetails.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSyncQueryExecution.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPUpdateExecution.java
trunk/connectors/connector-ldap/src/main/resources/com/
trunk/connectors/connector-ldap/src/test/java/com/metamatrix/connector/ldap/
trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestIQueryToLdapSearchParser.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Connector.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Constants.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Messages.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/MetadataProcessor.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/NameUtil.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Relationship.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/RelationshipImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForceManagedConnectionFactory.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForcePlugin.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesforceCapabilities.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Util.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/SalesforceConnection.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/impl/
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/AbstractUpdateExecution.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DataPayload.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeleteExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedObject.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedResult.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetDeletedExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetUpdatedExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/InsertExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParent.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParentImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/QueryExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/SalesforceProcedureExecution.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdateExecutionImpl.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdatedResult.java
trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/visitors/
trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/ConnectionImpl.java
trunk/connectors/connector-salesforce/src/main/resources/com/
trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/execution/visitors/TestVisitors.java
trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/StringToDateTranslator.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextCapabilities.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnection.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnector.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPropertyNames.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextSynchExecution.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextUtil.java
trunk/connectors/connector-text/src/main/resources/com/
trunk/connectors/sandbox/translator-yahoo/src/main/java/com/metamatrix/connector/yahoo/
trunk/connectors/sandbox/translator-yahoo/src/main/rar/
trunk/connectors/sandbox/translator-yahoo/src/main/resources/com/
trunk/connectors/sandbox/translator-yahoo/src/test/java/com/metamatrix/connector/yahoo/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCBaseExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCConnector.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCExecutionException.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCManagedConnectionFactory.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCPlugin.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCProcedureExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCQueryExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCSourceConnection.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCUpdateExecution.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/SimpleCapabilities.java
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/access/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/db2/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/derby/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/h2/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/hsql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/informix/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/mm/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/mysql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/oracle/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/postgresql/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/sqlserver/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/sybase/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/teiid/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/teradata/
trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/translator/
trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml
trunk/connectors/translator-jdbc/src/main/resources/org/teiid/connector/
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCManagedConnectionFactory.java
trunk/connectors/translator-loopback/src/main/java/com/metamatrix/connector/loopback/
trunk/connectors/translator-loopback/src/main/rar/
trunk/connectors/translator-loopback/src/test/java/com/metamatrix/connector/loopback/
trunk/engine/src/main/java/com/metamatrix/common/log/JavaLogWriter.java
trunk/engine/src/main/java/com/metamatrix/common/log/LogConstants.java
trunk/engine/src/main/java/com/metamatrix/common/log/LogListener.java
trunk/engine/src/main/java/com/metamatrix/common/log/LogManager.java
trunk/engine/src/main/java/com/metamatrix/common/log/LogMessage.java
trunk/engine/src/main/java/com/metamatrix/common/log/MessageLevel.java
trunk/engine/src/test/java/com/metamatrix/common/log/TestLogManager.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeployer.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeploymentGroup.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryParserDeployer.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryMetadataGroup.java
trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ExtendedPropertyMetadata.java
trunk/jboss-integration/src/test/java/org/teiid/templates/connector/TestExtendedPropertyMetadata.java
trunk/metadata/src/test/java/com/metamatrix/cdk/api/SysLogger.java
Modified:
trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
trunk/build/assembly/jboss-container/dist.xml
trunk/build/kits/jboss-container/deploy/teiid/teiid-connector-templates-jboss-beans.xml
trunk/build/kits/jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml
trunk/client/src/main/java/org/teiid/adminapi/Admin.java
trunk/client/src/main/java/org/teiid/adminapi/Model.java
trunk/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java
trunk/client/src/main/java/org/teiid/adminapi/impl/SourceMappingMetadata.java
trunk/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java
trunk/client/src/main/resources/vdb-deployer.xsd
trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
trunk/connector-api/src/main/java/org/teiid/connector/language/Condition.java
trunk/connector-api/src/main/java/org/teiid/connector/language/LanguageFactory.java
trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/BaseColumn.java
trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/MetadataFactory.java
trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/RuntimeMetadata.java
trunk/connectors/connector-ldap/pom.xml
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPManagedConnectionFactory.java
trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPPlugin.java
trunk/connectors/connector-ldap/src/main/rar/META-INF/ra.xml
trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestLDAPConnection.java
trunk/connectors/connector-salesforce/pom.xml
trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml
trunk/connectors/connector-text/pom.xml
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextManagedConnectionFactory.java
trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPlugin.java
trunk/connectors/connector-text/src/main/rar/META-INF/ra.xml
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestMultiFileTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestRowHeaderTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnection.java
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnector.java
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextSynchExecution.java
trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/Util.java
trunk/connectors/sandbox/translator-yahoo/pom.xml
trunk/connectors/translator-jdbc/pom.xml
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access/TestAccessSQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2ConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2SqlTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbyCapabilities.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbySQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/extension/TestSQLConversionVisitor.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2/TestH2Translator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQL5Translator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLeftOrRightFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLog10FunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestSubstringFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/TestPostgreSQLTranslator.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/TestSqlServerConversionVisitor.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseConvertModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseSQLConversionVisitor.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestEscapeSyntaxModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestExtractFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestLocateFunctionModifier.java
trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestModFunctionModifier.java
trunk/connectors/translator-loopback/pom.xml
trunk/engine/src/main/java/com/metamatrix/common/buffer/TupleBuffer.java
trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java
trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java
trunk/engine/src/main/java/com/metamatrix/query/analysis/AnalysisRecord.java
trunk/engine/src/main/java/com/metamatrix/query/function/FunctionTree.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/capabilities/BasicSourceCapabilities.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CapabilitiesUtil.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCopyCriteria.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePlanJoins.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/XMLPlanner.java
trunk/engine/src/main/java/com/metamatrix/query/processor/QueryProcessor.java
trunk/engine/src/main/java/com/metamatrix/query/processor/proc/AssignmentInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ErrorInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/proc/IfInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java
trunk/engine/src/main/java/com/metamatrix/query/processor/relational/PlanExecutionNode.java
trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNode.java
trunk/engine/src/main/java/com/metamatrix/query/processor/relational/SortUtility.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AbortProcessingInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddCommentInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddNodeInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndBlockInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndDocumentInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecSqlInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecStagingTableInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/IfInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/InitializeDocumentInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveCursorInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveDocInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/RelationalPlanExecutor.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/SAXDocumentInProgress.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/WhileInstruction.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLPlan.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLProcessorEnvironment.java
trunk/engine/src/main/java/com/metamatrix/query/resolver/QueryResolver.java
trunk/engine/src/main/java/com/metamatrix/query/resolver/command/UpdateProcedureResolver.java
trunk/engine/src/main/java/org/teiid/dqp/internal/cache/DQPContextCache.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/CapabilitiesConverter.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWork.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWorkItem.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ExecutionContextImpl.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ProcedureBatchHandler.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/language/LanguageBridgeFactory.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/metadata/RuntimeMetadataImpl.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/CodeTableCache.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/StatsCapturingWorkManager.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
trunk/engine/src/main/resources/com/metamatrix/dqp/i18n.properties
trunk/engine/src/test/java/com/metamatrix/dqp/service/AutoGenDataService.java
trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionTree.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinOptimization.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinPushdownRestrictions.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestSubqueryPushdown.java
trunk/engine/src/test/java/com/metamatrix/query/processor/FakeDataManager.java
trunk/engine/src/test/java/com/metamatrix/query/sql/visitor/TestExpressionMappingVisitor.java
trunk/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeConnector.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeExecutionContextImpl.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeProcedureExecution.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManager.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorWorkItem.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestTypeFacilityImpl.java
trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryDeployer.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/VDBMetaDataInstanceClassFactory.java
trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorDeploymentTemplate.java
trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorTemplateInfo.java
trunk/jboss-integration/src/main/java/org/teiid/templates/connector/RaXmlPropertyConverter.java
trunk/jboss-integration/src/main/java/org/teiid/templates/connector/XaJdbcConnectorTemplateInfo.java
trunk/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java
trunk/runtime/pom.xml
trunk/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
trunk/runtime/src/main/java/org/teiid/deployers/VDBStatusChecker.java
trunk/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java
trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java
trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java
trunk/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java
trunk/runtime/src/main/java/org/teiid/transport/ServerWorkItem.java
trunk/runtime/src/main/java/org/teiid/transport/SocketClientInstance.java
trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java
trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties
trunk/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/MockConnector.java
trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java
trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
trunk/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java
trunk/test-integration/pom.xml
Log:
TEIID-1075, TEIID-1077, TEIID-1078, TEIID-1079, TEIID-1080, TEIID-1081: Translation layer changes.
Modified: trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
===================================================================
--- trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -40,12 +40,12 @@
import org.teiid.adminapi.AdminException;
import org.teiid.adminapi.AdminFactory;
import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.ConnectionFactory;
import org.teiid.adminapi.ProcessObject;
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.adminshell.Help.Doc;
@@ -112,13 +112,12 @@
p = props;
}
- @Doc(text = "Add a ConnectionFactory")
- public static ConnectionFactory addConnectionFactory(
+ @Doc(text = "Add a Translator")
+ public static Translator addTranslator(
@Doc(text = "deployed name") String deployedName,
@Doc(text = "type name") String typeName,
Properties properties) throws AdminException {
- return getAdmin()
- .addConnectionFactory(deployedName, typeName, properties);
+ return getAdmin().addTranslator(deployedName, typeName, properties);
}
@Doc(text = "Adds a role to the specified policy")
@@ -130,16 +129,16 @@
getAdmin().addRoleToDataPolicy(vdbName, vdbVersion, policyName, role);
}
- @Doc(text = "Assign a ConnectionFactory to a source Model")
- public static void assignConnectionFactoryToModel(
+ @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 = "source name") String sourceName,
+ @Doc(text = "translator name") String translatorName,
@Doc(text = "jndi name") String jndiName)
throws AdminException {
- getAdmin().assignConnectionFactoryToModel(vdbName, vdbVersion, modelName,
- sourceName, jndiName);
+ getAdmin().assignToModel(vdbName, vdbVersion, modelName, sourceName, translatorName, jndiName);
}
@Doc(text = "Cancel a request")
@@ -156,19 +155,13 @@
getAdmin().clearCache(cacheType);
}
- @Doc(text = "Delete a ConnectionFactory")
- public static void deleteConnectionFactory(
+ @Doc(text = "Delete a Translator")
+ public static void deleteTranslator(
@Doc(text = "deployed name") String deployedName)
throws AdminException {
- getAdmin().deleteConnectionFactory(deployedName);
+ getAdmin().deleteTranslator(deployedName);
}
- @Doc(text = "Delete a Connector")
- public static void deleteConnector(
- @Doc(text = "name") String name) throws AdminException {
- getAdmin().deleteConnector(name);
- }
-
@Doc(text = "Delete a VDB")
public static void deleteVDB(
@Doc(text = "vdb name") String vdbName,
@@ -181,35 +174,28 @@
return getAdmin().getCacheTypes();
}
- @Doc(text = "Get all ConnectionFactory instances")
- public static Collection<ConnectionFactory> getConnectionFactories()
+ @Doc(text = "Get all translator instances")
+ public static Collection<Translator> getTranslators()
throws AdminException {
- return getAdmin().getConnectionFactories();
+ return getAdmin().getTranslators();
}
- @Doc(text = "Get all ConnectionFactory instances in the VDB")
- public static Collection<ConnectionFactory> getConnectionFactoriesInVDB(
- @Doc(text = "vdb name") String vdbName,
- @Doc(text = "vdb version") int vdbVersion) throws AdminException {
- return getAdmin().getConnectionFactoriesInVDB(vdbName, vdbVersion);
- }
-
@Doc(text = "Get the specified ConnectionFactory")
- public static ConnectionFactory getConnectionFactory(
+ public static Translator getTranslator(
@Doc(text = "deployed name") String deployedName)
throws AdminException {
- return getAdmin().getConnectionFactory(deployedName);
+ return getAdmin().getTranslator(deployedName);
}
- @Doc(text = "Get all connector name Strings")
- public static Set<String> getConnectorNames() throws AdminException {
- return getAdmin().getConnectorTemplateNames();
+ @Doc(text = "Get all translator name Strings")
+ public static Set<String> getTranslatorTemplateNames() throws AdminException {
+ return getAdmin().getTranslatorTemplateNames();
}
- @Doc(text = "Get all PropertyDefinition instances for the given connector")
- public static Collection<PropertyDefinition> getConnectorPropertyDefinitions(
- @Doc(text = "connector name") String connectorName) throws AdminException {
- return getAdmin().getConnectorTemplatePropertyDefinitions(connectorName);
+ @Doc(text = "Get all PropertyDefinitions for the given translator template")
+ public static Collection<PropertyDefinition> getTranslatorTemplatePropertyDefinitions(
+ @Doc(text = "template name") String templateName) throws AdminException {
+ return getAdmin().getTranslatorTemplatePropertyDefinitions(templateName);
}
@Doc(text = "Get the ProcessObject instances for the given identifier")
@@ -270,13 +256,12 @@
.removeRoleFromDataPolicy(vdbName, vdbVersion, policyName, role);
}
- @Doc(text = "Set a ConnectionFactory property")
- public static void setConnectionFactoryProperty(
+ @Doc(text = "Set a Translator property")
+ public static void setTranslatorProperty(
@Doc(text = "deployed name") String deployedName,
@Doc(text = "propery name") String propertyName,
@Doc(text = "value") String propertyValue) throws AdminException {
- getAdmin().setConnectionFactoryProperty(deployedName, propertyName,
- propertyValue);
+ getAdmin().setTranslatorProperty(deployedName, propertyName,propertyValue);
}
@Doc(text = "Set a runtime property")
@@ -287,20 +272,6 @@
getAdmin().setRuntimeProperty(propertyName, propertyValue);
}
- @Doc(text = "Start a ConnectionFactory")
- public static void startConnectionFactory(
- @Doc(text = "deployed name") String deployedName)
- throws AdminException {
- getAdmin().startConnectionFactory(deployedName);
- }
-
- @Doc(text = "Stop a ConnectionFactory")
- public static void stopConnectionFactory(
- @Doc(text = "deployed name") String deployedName)
- throws AdminException {
- getAdmin().stopConnectionFactory(deployedName);
- }
-
@Doc(text = "Terminate a session and associated requests")
public static void terminateSession(
@Doc(text = "session id") String sessionId) throws AdminException {
@@ -323,12 +294,11 @@
getAdmin().mergeVDBs(sourceVDBName, sourceVDBVersion, targetVDBName, targetVDBVersion);
}
- @Doc(text = "Checks if a ConnectionFactory exists")
- public static boolean hasConnectionFactory(
- @Doc(text = "deployed name") String factoryName) throws AdminException {
- Collection<ConnectionFactory> bindings = getAdmin().getConnectionFactories();
+ @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 (ConnectionFactory binding:bindings) {
+ for (Translator binding:bindings) {
if (binding.getName().equals(factoryName)) {
return true;
}
@@ -336,19 +306,6 @@
return false;
}
- @Doc(text = "Checks if a Connector exists")
- public static boolean hasConnector(
- @Doc(text = "type name") String typeName) throws AdminException {
- Collection<String> types = getAdmin().getConnectorTemplateNames();
-
- for (String type:types) {
- if (type.equals(typeName)) {
- return true;
- }
- }
- return false;
- }
-
@Doc(text = "Checks if a VDB exists")
public static boolean hasVDB(
@Doc(text = "vdb name") String vdbName) throws AdminException {
@@ -390,21 +347,6 @@
ObjectConverterUtil.write(contents, fileName);
}
- @Doc(text = "Add a connector from a RAR file")
- public static void addConnector(
- @Doc(text = "name of the Connector") String name,
- @Doc(text = "RAR file name") String rarFile) throws FileNotFoundException, AdminException {
- FileInputStream fis = new FileInputStream(new File(rarFile));
- try {
- getAdmin().addConnector(name, fis);
- } finally {
- try {
- fis.close();
- } catch (IOException e) {
- }
- }
- }
-
@Doc(text = "Export a VDB to file")
public static void exportVDB(
@Doc(text = "vdb name") String vdbName,
Modified: trunk/build/assembly/jboss-container/dist.xml
===================================================================
--- trunk/build/assembly/jboss-container/dist.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/build/assembly/jboss-container/dist.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -70,14 +70,19 @@
<includeSubModules>true</includeSubModules>
<includes>
- <include>org.jboss.teiid.connectors:connector-jdbc:rar</include>
- <include>org.jboss.teiid.connectors:connector-loopback:rar</include>
+ <include>org.jboss.teiid.connectors:translator-jdbc</include>
+ <include>org.jboss.teiid.connectors:translator-loopback</include>
+ <include>org.jboss.teiid.connectors:translator-text</include>
<include>org.jboss.teiid.connectors:connector-text:rar</include>
+ <include>org.jboss.teiid.connectors:translator-ldap</include>
<include>org.jboss.teiid.connectors:connector-ldap:rar</include>
+ <include>org.jboss.teiid.connectors:translator-salesforce</include>
<include>org.jboss.teiid.connectors:connector-salesforce:rar</include>
+ <!--
<include>org.jboss.teiid.connectors:connector-xml-http:rar</include>
<include>org.jboss.teiid.connectors:connector-xml-file:rar</include>
<include>org.jboss.teiid.connectors:connector-xml-soap:rar</include>
+ -->
</includes>
<binaries>
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/access-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/access-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/access-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.access.AccessSQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/access-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/db2-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/db2-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/db2-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.db2.DB2SQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/db2-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/derby-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/derby-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/derby-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.derby.DerbySQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/derby-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/h2-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/h2-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/h2-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.h2.H2Translator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/h2-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/hsql-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/hsql-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/hsql-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.hsql.HsqlTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/hsql-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/ldap-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/ldap-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/ldap-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.ldap.LDAPExecutionFactory</execution-factory-class>
+ <translator-property name="SearchDefaultBaseDN" value="" />
+ <translator-property name="SearchDefaultScope" value="SUBTREE_SCOPE"/>
+ <translator-property name="RestrictToObjectClass" value="false"/>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/ldap-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/loopback-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/loopback-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/loopback-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.loopback.LoopbackExecutionFactory</execution-factory-class>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/loopback-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/mysql-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/mysql-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/mysql-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.mysql.MySQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/mysql-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/oracle-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/oracle-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/oracle-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.oracle.OracleSQLTranslator"/>
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/oracle-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/postgresql-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/postgresql-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/postgresql-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.postgresql.PostgreSQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/postgresql-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/salesforce-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/salesforce-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/salesforce-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.salesforce.SalesForceExecutionFactory</execution-factory-class>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/salesforce-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/sqlserver-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/sqlserver-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/sqlserver-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/sqlserver-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/sybase-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/sybase-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/sybase-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</execution-factory-class>
+ <translator-property name="ExtensionTranslationClassName" value="org.teiid.translator.jdbc.sybase.SybaseSQLTranslator" />
+ <xa-capable>true</xa-capable>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/sybase-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/text-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/text-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/text-translator.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator>
+ <execution-factory-class>org.teiid.resource.adapter.text.TextExecutionFactory</execution-factory-class>
+</translator>
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/text-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/build/kits/jboss-container/deploy/teiid/teiid-connector-templates-jboss-beans.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/teiid-connector-templates-jboss-beans.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/build/kits/jboss-container/deploy/teiid/teiid-connector-templates-jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
+ <!--
<bean name="connector-jdbc-xa-${project.version}" class="org.teiid.templates.connector.XaJdbcConnectorTemplate">
<property name="info"><inject bean="connector-jdbc-xa-templateinfo"/></property>
</bean>
@@ -15,7 +15,8 @@
</constructor>
<property name="rarName">connector-jdbc-${project.version}.rar</property>
</bean>
-
+ -->
+
<bean name="connector-ldap-${project.version}" class="org.teiid.templates.connector.ConnectorDeploymentTemplate">
<property name="info"><inject bean="connector-ldap-templateinfo"/></property>
<property name="targetTemplate"><inject bean="NoTxConnectionFactoryTemplate"/></property>
@@ -31,21 +32,6 @@
<property name="rarName">connector-ldap-${project.version}.rar</property>
</bean>
- <bean name="connector-loopback-${project.version}" class="org.teiid.templates.connector.ConnectorDeploymentTemplate">
- <property name="info"><inject bean="connector-loopback-templateinfo"/></property>
- <property name="targetTemplate"><inject bean="NoTxConnectionFactoryTemplate"/></property>
- </bean>
- <bean name="connector-loopback-templateinfo" class="org.teiid.templates.connector.ConnectorTemplateInfo">
- <constructor factoryMethod="createTemplateInfo">
- <factory bean="DSDeploymentTemplateInfoFactory"/>
- <parameter class="java.lang.Class">org.teiid.templates.connector.ConnectorTemplateInfo</parameter>
- <parameter class="java.lang.Class">org.jboss.resource.metadata.mcf.NoTxConnectionFactoryDeploymentMetaData</parameter>
- <parameter class="java.lang.String">connector-loopback-${project.version}</parameter>
- <parameter class="java.lang.String">Teiid Loopback Connector</parameter>
- </constructor>
- <property name="rarName">connector-loopback-${project.version}.rar</property>
- </bean>
-
<bean name="connector-salesforce-${project.version}" class="org.teiid.templates.connector.ConnectorDeploymentTemplate">
<property name="info"><inject bean="connector-salesforce-templateinfo"/></property>
<property name="targetTemplate"><inject bean="NoTxConnectionFactoryTemplate"/></property>
@@ -76,6 +62,7 @@
<property name="rarName">connector-text-${project.version}.rar</property>
</bean>
+ <!--
<bean name="connector-xmlsource-file-${project.version}" class="org.teiid.templates.connector.ConnectorDeploymentTemplate">
<property name="info"><inject bean="connector-xmlsource-file-templateinfo"/></property>
<property name="targetTemplate"><inject bean="NoTxConnectionFactoryTemplate"/></property>
@@ -120,5 +107,6 @@
</constructor>
<property name="rarName">connector-xml-http-${project.version}.rar</property>
</bean>
+ -->
</deployment>
Modified: trunk/build/kits/jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml
===================================================================
--- trunk/build/kits/jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/build/kits/jboss-container/deployers/teiid.deployer/teiid-deployer-jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -44,12 +44,11 @@
<property name="VDBRepository"><inject bean="VDBRepository"/></property>
<property name="contextCache"><inject bean="ContextCache"/></property>
<property name="objectSerializer"><inject bean="ObjectSerializer"/></property>
- <property name="connectorManagerRepository"><inject bean="ConnectorManagerRepository"/></property>
+ <property name="connectorManagerRepository"><inject bean="ConnectorManagerRepository"/></property>
+ <property name="translatorRepository"><inject bean="translatorRepository"/></property>
<depends>SystemVDBDeployer</depends>
</bean>
-
-
<bean name="SystemVDBDeployer" class="org.teiid.deployers.SystemVDBDeployer">
<property name="VDBRepository"><inject bean="VDBRepository"/></property>
</bean>
@@ -57,27 +56,29 @@
<bean name="ConnectionFactoryDeployer" class="org.teiid.jboss.deployers.ConnectionFactoryDeployer">
<property name="connectorManagerRepository"><inject bean="ConnectorManagerRepository"/></property>
<property name="VDBStatusChecker"><inject bean="VDBStatusChecker"/></property>
- <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
</bean>
- <bean name="AutoConnectionFactoryDeployer" class="org.teiid.jboss.deployers.AutoConnectionFactoryDeployer">
- <property name="connectorManagerRepository"><inject bean="ConnectorManagerRepository"/></property>
+ <bean name="translatorRepository" class="org.teiid.dqp.internal.datamgr.impl.TranslatorRepository"/>
+
+ <bean name="TranslatorParserDeployer" class="org.teiid.deployers.TranslatorParserDeployer"/>
+ <bean name="TranslatorDeployer" class="org.teiid.deployers.TranslatorDeployer">
+ <property name="translatorRepository"><inject bean="translatorRepository"/></property>
<property name="VDBStatusChecker"><inject bean="VDBStatusChecker"/></property>
- <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
</bean>
-
+
<bean name="VDBStatusChecker" class="org.teiid.deployers.VDBStatusChecker">
<property name="VDBRepository"><inject bean="VDBRepository"/></property>
+ <property name="connectorManagerRepository"><inject bean="ConnectorManagerRepository"/></property>
</bean>
- <bean name="AutoConnectionFactoryParserDeployer" class="org.teiid.jboss.deployers.AutoConnectionFactoryParserDeployer">
- </bean>
-
<!-- Persistence class for the VDB deployment file -->
<bean name="VDBMetadataComponentMapper" class="org.teiid.jboss.deployers.VDBMetadataComponentMapper">
<constructor><parameter><inject bean="PersistenceFactory" /></parameter></constructor>
</bean>
+ <!-- used for the translators -->
+ <bean name="TranslatorDeploymentTemplateInfoFactory" class="org.teiid.templates.TranslatorTemplateInfoFactory"/>
+
<!-- JBOSS Cache -->
<!-- Uncomment for JBoss Cache -->
<!--
Modified: trunk/client/src/main/java/org/teiid/adminapi/Admin.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/Admin.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/Admin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -32,16 +32,17 @@
public enum Cache {CODE_TABLE_CACHE,PREPARED_PLAN_CACHE, QUERY_SERVICE_RESULT_SET_CACHE};
/**
- * Assign a {@link ConnectionFactory} to a {@link VDB}'s Model
+ * 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 jndiName JNDI names to which the source name needs to map to
+ * @param translatorName
+ * @param dsName data source name that can found in the JNDI map.
* @throws AdminException
*/
- void assignConnectionFactoryToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String jndiName) throws AdminException;
+ void assignToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String translatorName, String dsName) throws AdminException;
/**
* Set/update the property for the Connection Factory identified by the given deployed name.
@@ -50,43 +51,26 @@
* @param propertyValue
* @throws AdminException
*/
- void setConnectionFactoryProperty(String deployedName, String propertyName, String propertyValue) throws AdminException;
+ void setTranslatorProperty(String deployedName, String propertyName, String propertyValue) throws AdminException;
/**
- * Add Connector, will import RAR from a file
+ * Deploy a {@link Translator} to Configuration
*
- * @param name of the Connector to add
- * @param rar RAR file
- * @throws AdminException
- */
- void addConnector(String name, InputStream rar) throws AdminException;
-
- /**
- * Delete Connector
- *
- * @param name String name of the Connector to delete
- * @throws AdminException
- */
- void deleteConnector(String name) throws AdminException;
-
- /**
- * Deploy a {@link ConnectionFactory} to Configuration
- *
- * @param deployedName Connection Factory name that will be added to Configuration
- * @param typeName Connector type name.
+ * @param deployedName Translator name that will be added to Configuration
+ * @param templateName template name
* @param properties Name & Value pair need to deploy the Connection Factory
* @throws AdminException
*/
- ConnectionFactory addConnectionFactory(String deployedName, String typeName, Properties properties) throws AdminException;
+ Translator addTranslator(String deployedName, String templateName, Properties properties) throws AdminException;
/**
- * Delete the {@link ConnectionFactory} from the Configuration
+ * Delete the {@link Translator} from the Configuration
*
* @param deployedName - deployed name of the connection factory
* @throws AdminException
*/
- void deleteConnectionFactory(String deployedName) throws AdminException;
+ void deleteTranslator(String deployedName) throws AdminException;
/**
* Deploy a {@link VDB} file.
@@ -125,12 +109,12 @@
void setRuntimeProperty(String propertyName, String propertyValue) throws AdminException;
/**
- * Get the Connector Template available in the configuration.
+ * Get the translator templates available in the configuration.
*
* @return Set of connector template names.
* @throws AdminException
*/
- Set<String> getConnectorTemplateNames() throws AdminException;
+ Set<String> getTranslatorTemplateNames() throws AdminException;
/**
* Get the VDBs that currently deployed in the system
@@ -151,31 +135,22 @@
VDB getVDB(String vdbName, int vbdVersion) throws AdminException;
/**
- * Get the Connection Factories that are available in the configuration
+ * Get the translators that are available in the configuration
*
- * @return Collection of {@link ConnectionFactory}
+ * @return Collection of {@link Translator}
* @throws AdminException
*/
- Collection<ConnectionFactory> getConnectionFactories() throws AdminException;
+ Collection<Translator> getTranslators() throws AdminException;
/**
- * Get the Connection Factory by the given the deployed name.
- * @param deployedName - name of the deployed Connection Factory
- * @return null if not found a Connection Factory by the given name
+ * Get the translator by the given the deployed name.
+ * @param deployedName - name of the deployed translator
+ * @return null if not found
* @throws AdminException
*/
- ConnectionFactory getConnectionFactory(String deployedName) throws AdminException;
+ Translator getTranslator(String deployedName) throws AdminException;
/**
- * Get all the Connection Factories for the given VDB identifier pattern
- * @param vdbName - Name of the VDB
- * @param vdbVersion - version of the VDB
- * @return Collection of {@link ConnectionFactory}
- * @throws AdminException
- */
- Collection<ConnectionFactory> getConnectionFactoriesInVDB(String vdbName, int vdbVersion) throws AdminException;
-
- /**
* Get the Work Manager stats that correspond to the specified identifier pattern.
*
* @param identifier - an identifier for the queues {@link QueueWorkerPool}.
@@ -184,9 +159,6 @@
*/
WorkerPoolStatistics getWorkManagerStats(String identifier) throws AdminException;
-
-
-
/**
* Get the Caches that correspond to the specified identifier pattern
* @return Collection of {@link String}
@@ -222,7 +194,7 @@
* @return
* @throws AdminException
*/
- Collection<PropertyDefinition> getConnectorTemplatePropertyDefinitions(String templateName) throws AdminException;
+ Collection<PropertyDefinition> getTranslatorTemplatePropertyDefinitions(String templateName) throws AdminException;
/**
@@ -244,24 +216,7 @@
*/
Collection<ProcessObject> getProcesses(String processIdentifier) throws AdminException;
-
/**
- * Start Connection Factory
- *
- @param deployedName - name of the deployed Connection Factory
- * @throws AdminException
- */
- void startConnectionFactory(String deployedName) throws AdminException;
-
- /**
- * Stop Connection Factory
- *
- * @param deployedName - name of the deployed Connection Factory
- * @throws AdminException
- */
- void stopConnectionFactory(String deployedName) throws AdminException;
-
- /**
* Clear the cache or caches specified by the cacheIdentifier.
* @param cacheType Cache Type
* No wild cards currently supported, must be explicit
Deleted: trunk/client/src/main/java/org/teiid/adminapi/ConnectionFactory.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/ConnectionFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/ConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,48 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.adminapi;
-
-
-/**
- * Represents a connector binding (the instance of a connector type) in the Teiid system.
- */
-public interface ConnectionFactory extends AdminObject {
-
- /**
- * Get the identifier for this connector binding's RAR file name
- * @return Name of the RAR file used to create this binding
- */
- String getRARFileName();
-
- /**
- * Get the JNDI Name of this connector
- * @return
- */
- String getJNDIName();
-
- /**
- * Get the template name for the Connection Factory
- * @return
- */
- String getTemplateName();
-}
Deleted: trunk/client/src/main/java/org/teiid/adminapi/ConnectionPoolStatistics.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/ConnectionPoolStatistics.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/ConnectionPoolStatistics.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,83 +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.Serializable;
-
-
-/**
- * This object holds the statistics for a ConnectionPool that is being utilized by a Connector.
- * As per how many available connections
- * processed etc.
- */
-public interface ConnectionPoolStatistics extends AdminObject, Serializable {
-
- /**
- * The maximum number of connections that are available
- * @return
- */
- long getAvailableConnectionCount();
-
- /**
- * The number of connections that are currently in the pool
- * @return
- */
- int getConnectionCount();
-
- /**
- * The number of connections that have been created since the connector was last started
- * @return
- */
- int getConnectionCreatedCount();
-
- /**
- * The number of connections that have been destroyed since the connector was last started
- * @return
- */
- int getConnectionDestroyedCount();
-
-
- /**
- * The number of connections that are currently in use
- * @return
- */
- long getInUseConnectionCount();
-
- /**
- * The most connections that have been simultaneously in use since this connector was started
- * @return
- */
- long getMaxConnectionsInUseCount();
-
- /**
- * Max size
- * @return
- */
- int getMaxSize();
-
- /**
- * Min Size
- * @return
- */
- int getMinSize();
-}
Modified: trunk/client/src/main/java/org/teiid/adminapi/Model.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/Model.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/Model.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -79,5 +79,13 @@
* @param sourceName - name of the source
* @return null if none configured.
*/
- String getSourceJndiName(String sourceName);
+ String getSourceConnectionJndiName(String sourceName);
+
+
+ /**
+ * Get the configured translator name for the given source
+ * @param sourceName
+ * @return
+ */
+ String getSourceTranslatorName(String sourceName);
}
\ No newline at end of file
Added: trunk/client/src/main/java/org/teiid/adminapi/Translator.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/Translator.java (rev 0)
+++ trunk/client/src/main/java/org/teiid/adminapi/Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+
+public interface Translator extends AdminObject{
+
+ public String getExecutionFactoryClass();
+
+ public String getCapabilitiesClass();
+
+ public boolean isImmutable();
+
+ public boolean isExceptionOnMaxRows();
+
+ public int getMaxResultRows();
+
+ public boolean isXaCapable();
+
+ public String getOverrideCapabilitiesFile();
+
+ public void setOverrideCapabilitiesFile(String propsFile);
+}
Property changes on: trunk/client/src/main/java/org/teiid/adminapi/Translator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionFactoryMetaData.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionFactoryMetaData.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionFactoryMetaData.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.adminapi.impl;
-
-import java.util.List;
-
-import org.jboss.managed.api.annotation.ManagementComponent;
-import org.jboss.managed.api.annotation.ManagementObject;
-import org.jboss.managed.api.annotation.ManagementObjectID;
-import org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.adminapi.ConnectionFactory;
-
-@ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="connection-factory"))
-public class ConnectionFactoryMetaData extends AdminObjectImpl implements ConnectionFactory {
-
- private static final String TEMPLATE_NAME = "template-name"; //$NON-NLS-1$
- private static final long serialVersionUID = -4865836616882247016L;
- private transient Object type;
- private String rarFileName;
- private String jndiName;
-
- @ManagementProperty(description="Connector Binding Name")
- @ManagementObjectID(type="cf-name")
- public String getName() {
- return super.getName();
- }
-
- @Override
- @ManagementProperty(description="RAR file name")
- public String getRARFileName() {
- return this.rarFileName;
- }
-
- public void setRARFileName(String name) {
- this.rarFileName = name;
- }
-
- @Override
- @ManagementProperty(description="JNDI name")
- public String getJNDIName() {
- return this.jndiName;
- }
-
- public void setJNDIName(String name) {
- this.jndiName = name;
- }
-
- public void setComponentType(Object type) {
- this.type = type;
- }
-
- public Object getComponentType() {
- return this.type;
- }
-
- @Override
- @ManagementProperty(description="Template name for this connector")
- public String getTemplateName() {
- return getPropertyValue(TEMPLATE_NAME);
- }
-
- public void setTemplateName(String templateName) {
- addProperty(TEMPLATE_NAME, templateName);
- }
-
- @Override
- @ManagementProperty(description = "Connection Factory Properties", managed=true)
- public List<PropertyMetadata> getJAXBProperties(){
- return super.getJAXBProperties();
- }
-
- public String toString() {
- return getName();
- }
-}
Deleted: trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionPoolStatisticsMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionPoolStatisticsMetadata.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/ConnectionPoolStatisticsMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,133 +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 org.jboss.managed.api.annotation.ManagementProperty;
-import org.teiid.adminapi.ConnectionPoolStatistics;
-
-public class ConnectionPoolStatisticsMetadata extends AdminObjectImpl implements ConnectionPoolStatistics {
-
- private static final long serialVersionUID = 4420845831075045579L;
- private long availableConnectionCount;
- private int connectionCount;
- private int connectionCreatedCount;
- private int connectionDestroyedCount;
- private long inUseConnectionCount;
- private long maxConnectionsInUseCount;
- private int maxSize;
- private int minSize;
-
-
- @Override
- @ManagementProperty(description="The maximum number of connections that are available", readOnly=true)
- public long getAvailableConnectionCount() {
- return availableConnectionCount;
- }
-
- @Override
- @ManagementProperty(description="The number of connections that are currently in the pool", readOnly=true)
- public int getConnectionCount() {
- return connectionCount;
- }
-
- @Override
- @ManagementProperty(description="The number of connections that have been created since the connector was last started", readOnly=true)
- public int getConnectionCreatedCount() {
- return connectionCreatedCount;
- }
-
- @Override
- @ManagementProperty(description="The number of connections that have been destroyed since the connector was last started", readOnly=true)
- public int getConnectionDestroyedCount() {
- return connectionDestroyedCount;
- }
-
- @Override
- @ManagementProperty(description="The number of connections that are currently in use", readOnly=true)
- public long getInUseConnectionCount() {
- return inUseConnectionCount;
- }
-
- @Override
- @ManagementProperty(description="The most connections that have been simultaneously in use since this connector was started", readOnly=true)
- public long getMaxConnectionsInUseCount() {
- return maxConnectionsInUseCount;
- }
-
- @Override
- @ManagementProperty(description="Max configured size", readOnly=true)
- public int getMaxSize() {
- return maxSize;
- }
-
- @Override
- @ManagementProperty(description="Min Configured Size", readOnly=true)
- public int getMinSize() {
- return minSize;
- }
-
- public void setMaxSize(int maxSize) {
- this.maxSize = maxSize;
- }
-
- public void setAvailableConnectionCount(long availableConnectionCount) {
- this.availableConnectionCount = availableConnectionCount;
- }
-
- public void setConnectionCount(int connectionCount) {
- this.connectionCount = connectionCount;
- }
-
- public void setConnectionCreatedCount(int connectionCreatedCount) {
- this.connectionCreatedCount = connectionCreatedCount;
- }
-
- public void setConnectionDestroyedCount(int connectionDestroyedCount) {
- this.connectionDestroyedCount = connectionDestroyedCount;
- }
-
- public void setInUseConnectionCount(long inUseConnectionCount) {
- this.inUseConnectionCount = inUseConnectionCount;
- }
-
- public void setMaxConnectionsInUseCount(long maxConnectionsInUseCount) {
- this.maxConnectionsInUseCount = maxConnectionsInUseCount;
- }
-
- public void setMinSize(int minSize) {
- this.minSize = minSize;
- }
-
- public String toString() {
- StringBuilder str = new StringBuilder();
- str.append("ConnectionPoolStatisticsMetadata:"); //$NON-NLS-1$
- str.append(" availableConnectionCount = " + availableConnectionCount); //$NON-NLS-1$
- str.append("; connectionCount = " + connectionCount); //$NON-NLS-1$
- str.append("; connectionCreatedCount = " + connectionCreatedCount); //$NON-NLS-1$
- str.append("; connectionDestroyedCount = " + connectionDestroyedCount); //$NON-NLS-1$
- str.append("; inUseConnectionCount = " + inUseConnectionCount); //$NON-NLS-1$
- str.append("; maxConnectionsInUseCount = " + maxConnectionsInUseCount); //$NON-NLS-1$
- str.append("; maxSize = " + maxSize); //$NON-NLS-1$
- str.append("; minSize = " + minSize); //$NON-NLS-1$
- return str.toString();
- }
-}
Modified: trunk/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/ModelMetaData.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -173,7 +173,7 @@
public void setSourceMappings(List<SourceMappingMetadata> sources){
for (SourceMappingMetadata source: sources) {
- addSourceMapping(source.getName(), source.getJndiName());
+ addSourceMapping(source.getName(), source.getTranslatorName(), source.getConnectionJndiName());
}
}
@@ -183,17 +183,26 @@
}
@Override
- public String getSourceJndiName(String sourceName) {
+ public String getSourceConnectionJndiName(String sourceName) {
SourceMappingMetadata s = this.sources.getMap().get(sourceName);
if (s == null) {
return null;
}
- return s.getJndiName();
+ return s.getConnectionJndiName();
}
- public void addSourceMapping(String name, String jndiName) {
- this.sources.getMap().put(name, new SourceMappingMetadata(name, jndiName));
+ @Override
+ public String getSourceTranslatorName(String sourceName) {
+ SourceMappingMetadata s = this.sources.getMap().get(sourceName);
+ if (s == null) {
+ return null;
+ }
+ return s.getTranslatorName();
}
+
+ public void addSourceMapping(String name, String translatorName, String connJndiName) {
+ this.sources.getMap().put(name, new SourceMappingMetadata(name, translatorName, connJndiName));
+ }
@ManagementProperty(description = "Model Validity Errors", readOnly=true, managed=true)
public List<ValidationError> getErrors(){
@@ -229,9 +238,12 @@
@XmlAttribute(name = "severity", required = true)
protected String severity;
-
- public ValidationError() {};
+ @XmlAttribute(name = "path")
+ protected String path;
+
+ public ValidationError() {};
+
public ValidationError(String severity, String msg) {
this.severity = severity;
this.value = msg;
@@ -253,6 +265,15 @@
public void setSeverity(String severity) {
this.severity = severity;
- }
+ }
+
+ @ManagementProperty (description="Path")
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
}
}
Modified: trunk/client/src/main/java/org/teiid/adminapi/impl/SourceMappingMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/SourceMappingMetadata.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/SourceMappingMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -44,15 +44,18 @@
@XmlAttribute(name = "name", required = true)
private String name;
- @XmlAttribute(name = "jndi-name")
+ @XmlAttribute(name = "connection-jndi-name")
private String jndiName;
+ @XmlAttribute(name = "translator-name",required = true)
+ private String translatorName;
- public SourceMappingMetadata() {}
+ public SourceMappingMetadata() {}
- public SourceMappingMetadata(String name, String jndiName) {
+ public SourceMappingMetadata(String name, String translatorName, String connJndiName) {
this.name = name;
- this.jndiName = jndiName;
+ this.translatorName = translatorName;
+ this.jndiName = connJndiName;
}
@ManagementProperty (description="Source Name")
@@ -66,7 +69,7 @@
}
@ManagementProperty (description="JNDI Name of the resource to assosiate with Source name")
- public String getJndiName() {
+ public String getConnectionJndiName() {
// this default could be controlled if needed.
if (this.jndiName == null) {
return "java:"+name; //$NON-NLS-1$
@@ -74,11 +77,20 @@
return jndiName;
}
- public void setJndiName(String jndiName) {
+ public void setConnectionJndiName(String jndiName) {
this.jndiName = jndiName;
}
+ @ManagementProperty (description="Translator Name")
+ public String getTranslatorName() {
+ return translatorName;
+ }
+
+ public void setTranslatorName(String translatorName) {
+ this.translatorName = translatorName;
+ }
+
public String toString() {
- return getName()+":"+getJndiName(); //$NON-NLS-1$
+ return getName()+"/"+getTranslatorName()+"/"+getConnectionJndiName(); //$NON-NLS-1$ //$NON-NLS-2$
}
}
\ No newline at end of file
Added: trunk/client/src/main/java/org/teiid/adminapi/impl/TranslatorMetaData.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/TranslatorMetaData.java (rev 0)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/TranslatorMetaData.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,156 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.jboss.managed.api.annotation.ManagementComponent;
+import org.jboss.managed.api.annotation.ManagementObject;
+import org.jboss.managed.api.annotation.ManagementObjectID;
+import org.jboss.managed.api.annotation.ManagementProperties;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.adminapi.Translator;
+
+@ManagementObject(componentType=@ManagementComponent(type="teiid",subtype="translator"), properties=ManagementProperties.EXPLICIT)
+(a)XmlAccessorType(XmlAccessType.NONE)
+@XmlRootElement(name = "translator")
+public class TranslatorMetaData extends AdminObjectImpl implements Translator, Serializable {
+
+ private static final long serialVersionUID = 1680003620274793056L;
+ public static final String EXECUTION_FACTORY_CLASS = "execution-factory-class"; //$NON-NLS-1$
+ public static final String CAPBILITIES_CLASS = "capabilities-class"; //$NON-NLS-1$
+ public static final String IMMUTABLE = "immutable"; //$NON-NLS-1$
+ public static final String EXCEPTION_ON_MAX_ROWS = "exception-on-max-rows"; //$NON-NLS-1$
+ public static final String MAX_RESULT_ROWS = "max-result-rows"; //$NON-NLS-1$
+ public static final String XA_CAPABLE = "xa-capable"; //$NON-NLS-1$
+ public static final String OVERRIDE_CAPABILITIES_FILE = "override-capabilities-file"; //$NON-NLS-1$
+
+ // objects are used to keep the jaxb putting verbose xml elements when they are not defined.
+ private String executionFactoryClass;
+ private String capabilitiesClass;
+ private boolean immutable = false;
+ private boolean exceptionOnMaxRows = false;
+ private int maxResultRows = -1;
+ private boolean xaCapable = false;
+ private String overrideCapabilitiesFile;
+
+ @Override
+ @ManagementProperty(name="name", description="Name of the Translator", mandatory = true)
+ @ManagementObjectID(type="translator")
+ public String getName() {
+ return super.getName();
+ }
+
+ @Override
+ @ManagementProperty(name=EXECUTION_FACTORY_CLASS, description="Connector Class", mandatory = true)
+ public String getExecutionFactoryClass() {
+ return executionFactoryClass;
+ }
+
+ @XmlElement(name = EXECUTION_FACTORY_CLASS)
+ public void setExecutionFactoryClass(String arg0) {
+ this.executionFactoryClass = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=CAPBILITIES_CLASS, description="The class to use to provide the Connector Capabilities")
+ public String getCapabilitiesClass() {
+ return capabilitiesClass;
+ }
+
+ @XmlElement(name = CAPBILITIES_CLASS)
+ public void setCapabilitiesClass(String arg0) {
+ this.capabilitiesClass = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=IMMUTABLE, description="Is Immutable, True if the source never changes.",mandatory=true, defaultValue="false")
+ public boolean isImmutable() {
+ return immutable;
+ }
+
+ @XmlElement(name = IMMUTABLE)
+ public void setImmutable(boolean arg0) {
+ this.immutable = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=EXCEPTION_ON_MAX_ROWS, description="Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",mandatory=true)
+ public boolean isExceptionOnMaxRows() {
+ return exceptionOnMaxRows;
+ }
+
+ @XmlElement(name = EXCEPTION_ON_MAX_ROWS)
+ public void setExceptionOnMaxRows(boolean arg0) {
+ this.exceptionOnMaxRows = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=MAX_RESULT_ROWS, description="Maximum Result Rows allowed", mandatory=true)
+ public int getMaxResultRows() {
+ return maxResultRows;
+ }
+
+ @XmlElement(name = MAX_RESULT_ROWS)
+ public void setMaxResultRows(int arg0) {
+ this.maxResultRows = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=XA_CAPABLE, description="True, if this connector supports XA Transactions")
+ public boolean isXaCapable() {
+ return xaCapable;
+ }
+
+ @XmlElement(name=XA_CAPABLE)
+ public void setXaCapable(boolean arg0) {
+ this.xaCapable = arg0;
+ }
+
+ @Override
+ @ManagementProperty(name=OVERRIDE_CAPABILITIES_FILE, description="Property file that defines the override capability properties")
+ public String getOverrideCapabilitiesFile() {
+ return this.overrideCapabilitiesFile;
+ }
+
+ @XmlElement(name = OVERRIDE_CAPABILITIES_FILE)
+ public void setOverrideCapabilitiesFile(String propsFile) {
+ this.overrideCapabilitiesFile = propsFile;
+ }
+
+ @Override
+ @XmlElement(name = "translator-property", type = PropertyMetadata.class)
+ @ManagementProperty(description = "Translator Properties", managed=true)
+ public List<PropertyMetadata> getJAXBProperties(){
+ return super.getJAXBProperties();
+ }
+
+ public String toString() {
+ return getName();
+ }
+}
Property changes on: trunk/client/src/main/java/org/teiid/adminapi/impl/TranslatorMetaData.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/VDBMetaData.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -198,7 +198,7 @@
return false;
}
for (String sourceName:resourceNames) {
- if (m.getSourceJndiName(sourceName) == null) {
+ if (m.getSourceConnectionJndiName(sourceName) == null) {
return false;
}
}
Modified: trunk/client/src/main/resources/vdb-deployer.xsd
===================================================================
--- trunk/client/src/main/resources/vdb-deployer.xsd 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/main/resources/vdb-deployer.xsd 2010-05-07 16:24:50 UTC (rev 2103)
@@ -16,7 +16,8 @@
<xs:element name="source" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
- <xs:attribute name="jndi-name" type="xs:string"/>
+ <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">
Added: trunk/client/src/test/java/org/teiid/adminapi/impl/TestTranslatorMetadata.java
===================================================================
--- trunk/client/src/test/java/org/teiid/adminapi/impl/TestTranslatorMetadata.java (rev 0)
+++ trunk/client/src/test/java/org/teiid/adminapi/impl/TestTranslatorMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,52 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.StringWriter;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+
+import org.junit.Test;
+
+@SuppressWarnings("nls")
+public class TestTranslatorMetadata {
+
+ @Test
+ public void testFormat() throws Exception {
+ TranslatorMetaData tm = new TranslatorMetaData();
+
+ tm.setExecutionFactoryClass("org.teiid.resource.adapter.jdbc.JDBCExecutionFactory");
+ tm.setXaCapable(true);
+ tm.setName("Oracle");
+ tm.addProperty("ExtensionTranslationClassName", "org.teiid.translator.jdbc.oracle.OracleSQLTranslator");
+
+ JAXBContext jc = JAXBContext.newInstance(new Class<?>[] {TranslatorMetaData.class});
+ Marshaller marshell = jc.createMarshaller();
+ marshell.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
+
+ StringWriter sw = new StringWriter();
+ marshell.marshal(tm, sw);
+
+ System.out.println(sw.toString());
+ }
+}
Property changes on: trunk/client/src/test/java/org/teiid/adminapi/impl/TestTranslatorMetadata.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java
===================================================================
--- trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/client/src/test/java/org/teiid/adminapi/impl/TestVDBMetaData.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -54,7 +54,7 @@
ModelMetaData modelOne = new ModelMetaData();
modelOne.setName("model-one"); //$NON-NLS-1$
- modelOne.addSourceMapping("s1", "java:mybinding"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
@@ -66,8 +66,8 @@
ModelMetaData modelTwo = new ModelMetaData();
modelTwo.setName("model-two"); //$NON-NLS-1$
- modelTwo.addSourceMapping("s1", "java:binding-one"); //$NON-NLS-1$ //$NON-NLS-2$
- modelTwo.addSourceMapping("s2", "java:binding-two"); //$NON-NLS-1$ //$NON-NLS-2$
+ 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$
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/CacheScope.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/CacheScope.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/CacheScope.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,46 +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.api;
-
-import java.io.Serializable;
-
-/**
- * Cache Scope
- *
- * REQUEST - Items placed in this scope are retained until the end of the top level request. The items to be placed
- * does not need to implement {@link Serializable}, however recommended. These items are not replicated across the cluster.
- * SERVICE - Items from this scope are available to the identified connector
- *
- * All the items placed in the below scopes must be {@link Serializable}, as they are replicated across cluster.
- *
- * SESSION - Items placed in the scope retained until the particular User's session of top level request is alive.
- * VDB - Items placed with this scope retained until the life of the VDB;
- *
- * GLOBAL - Items placed in this will available to all until the Query Service is recycled.
- */
-public enum CacheScope {
- REQUEST,
- SERVICE,
- SESSION,
- VDB,
- GLOBAL;
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/Connection.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/Connection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/Connection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,79 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.connector.api;
-
-import javax.resource.spi.LocalTransaction;
-import javax.transaction.xa.XAResource;
-
-import org.teiid.connector.language.Command;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-/**
- * <p>Represents a connection to this connector. A connection will be obtained
- * from the connector for every query that is executed, then closed after the query has completed.
- * </p>
- */
-public interface Connection {
-
- /**
- * Get the capabilities of this connector. The capabilities affect what kinds of
- * queries (and other commands) will be sent to the connector.
- * @return Connector capabilities, may return null if the Connector returns globally scoped capabilities {@link Connector#getCapabilities()}
- */
- ConnectorCapabilities getCapabilities() throws ConnectorException;
-
- /**
- * Create an execution object for the specified command
- * @param command the command
- * @param executionContext Provides information about the context that this command is
- * executing within, such as the identifiers for the command being executed
- * @param metadata Access to runtime metadata if needed to translate the command
- * @return An execution object that can use to execute the command
- */
- Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata ) throws ConnectorException;
-
- /**
- * Release the connection. This will be called when system has completed
- * using the connection for an execution.
- */
- void close() throws ConnectorException;
-
- /**
- * Called to determine whether the connection is open
- * @return true if open, false if there is a source error.
- */
- boolean isAlive() throws ConnectorException;
-
- /**
- * Get the local transaction for the connector.
- * @return null if local transactions are not supported
- */
- LocalTransaction getLocalTransaction() throws ConnectorException;
-
- /**
- * If Connector supports participating in XA Connections, return the XAResurce associated with this connection.
- * @return null if not supported
- */
- XAResource getXAResource() throws ConnectorException;
-}
-
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectionContext.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectionContext.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectionContext.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,44 +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.api;
-
-import javax.security.auth.Subject;
-
-/**
- * Thread local class to access the Subject in the Connector code. This is set just before the
- * connector connection is created.
- */
-public class ConnectionContext {
- private static ThreadLocal<Subject> SUBJECT = new ThreadLocal<Subject>() {
- protected Subject initialValue() {
- return null;
- }
- };
-
- public static Subject getSubject() {
- return SUBJECT.get();
- }
-
- public static void setSubject(Subject subject) {
- SUBJECT.set(subject);
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/Connector.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/Connector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/Connector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,70 +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.api;
-
-import javax.security.auth.Subject;
-
-
-/**
- * <p>The primary entry point for a Connector. This interface should be implemented
- * by the connector writer.</p>
- *
- * <p>The JCA Container will instantiate the implementation of this class. Once the class has been
- * instantiated, the {@link #initialize(ConnectorEnvironment)} method will be called
- * with all necessary connector properties. </p>
- */
-public interface Connector {
-
- /**
- * Initialize the connector with supplied configuration
- * @param config
- */
- void initialize(ConnectorEnvironment config) throws ConnectorException;
-
- /**
- * Obtain a connection with the connector. The connection typically is associated
- * with a particular security context. The connection is assumed to be pooled by container
- * if pooling is necessary - the connection will be closed when execution has completed against it.
- *
- * If you need to authenticate/authorize and need to get access to {{@link Subject}, then use
- * {@link ConnectionContext}
- *
- * @return A Connection, created by the Connector
- * @throws ConnectorException If an error occurred obtaining a connection
- */
- Connection getConnection() throws ConnectorException;
-
- /**
- * Get the capabilities of this connector. The capabilities affect what kinds of
- * queries (and other commands) will be sent to the connector.
- * @return ConnectorCapabilities, may return null if the Connector provides User scoped capabilities {@link Connection#getCapabilities()}
- */
- ConnectorCapabilities getCapabilities() throws ConnectorException;
-
- /**
- * Get the ConnectorEnvironment that this connector is initialized with.
- * @return
- * @throws ConnectorException
- */
- ConnectorEnvironment getConnectorEnvironment();
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorCapabilities.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorCapabilities.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.api;
-
-import java.util.List;
-
-import org.teiid.connector.language.BatchedUpdates;
-import org.teiid.connector.language.SetQuery;
-
-
-/**
- * Allows a connector to specify the capabilities that a connector
- * supports.
- */
-public interface ConnectorCapabilities {
-
- public enum SupportedJoinCriteria {
- /**
- * Indicates that any supported criteria is allowed.
- */
- ANY,
- /**
- * Indicates that any simple comparison of elements is allowed.
- */
- THETA,
- /**
- * Indicates that only equality predicates of elements are allowed.
- */
- EQUI,
- /**
- * Indicates that only equality predicates between
- * exactly one primary and foreign key is allowed per join.
- */
- KEY
- }
-
- /**
- * Support indicates connector can accept queries with SELECT DISTINCT
- * @since 3.1 SP2
- */
- boolean supportsSelectDistinct();
-
- /**
- * Support indicates connector can accept expressions other than element
- * symbols in the SELECT clause. Specific supports for the expression
- * type are still checked.
- * @since 6.1.0
- */
- boolean supportsSelectExpression();
-
- /**
- * Support indicates connector can accept groups with aliases
- * @since 3.1 SP2
- */
- boolean supportsAliasedGroup();
-
- /**
- * Get the supported join criteria. A null return value will be treated
- * as {@link SupportedJoinCriteria#ANY}
- * @since 6.1.0
- */
- SupportedJoinCriteria getSupportedJoinCriteria();
-
- /**
- * Support indicates connector can accept inner or cross joins
- * @since 6.1.0
- */
- boolean supportsInnerJoins();
-
- /**
- * Support indicates connector can accept self-joins where a
- * group is joined to itself with aliases. Connector must also support
- * {@link #supportsAliasedGroup()}.
- * @since 3.1 SP2
- */
- boolean supportsSelfJoins();
-
- /**
- * Support indicates connector can accept left outer joins
- * @since 3.1 SP2
- */
- boolean supportsOuterJoins();
-
- /**
- * Support indicates connector can accept full outer joins
- * @since 3.1 SP2
- */
- boolean supportsFullOuterJoins();
-
- /**
- * Support indicates connector can accept inline views (subqueries
- * in the FROM clause).
- * @since 4.1
- */
- boolean supportsInlineViews();
-
- /**
- * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
- * <br>NOT CURRENTLY USED - between is rewritten as compound compare criteria
- * @since 4.0
- */
- boolean supportsBetweenCriteria();
-
- /**
- * Support indicates connector accepts criteria of form (element = constant)
- * @since 3.1 SP2
- */
- boolean supportsCompareCriteriaEquals();
-
- /**
- * Support indicates connector accepts criteria of form (element <=|>= constant)
- * <br>The query engine will may pushdown queries containing < or > if NOT is also
- * supported.
- * @since 3.1 SP2
- */
- boolean supportsCompareCriteriaOrdered();
-
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant)
- * @since 3.1 SP2
- */
- boolean supportsLikeCriteria();
-
- /**
- * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char)
- * @since 3.1 SP2
- */
- boolean supportsLikeCriteriaEscapeCharacter();
-
- /**
- * Support indicates connector accepts criteria of form (element IN set)
- * @since 3.1 SP2
- */
- boolean supportsInCriteria();
-
- /**
- * Support indicates connector accepts IN criteria with a subquery on the right side
- * @since 4.0
- */
- boolean supportsInCriteriaSubquery();
-
- /**
- * Support indicates connector accepts criteria of form (element IS NULL)
- * @since 3.1 SP2
- */
- boolean supportsIsNullCriteria();
-
- /**
- * Support indicates connector accepts logical criteria connected by OR
- * @since 3.1 SP2
- */
- boolean supportsOrCriteria();
-
- /**
- * Support indicates connector accepts logical criteria NOT
- * @since 3.1 SP2
- */
- boolean supportsNotCriteria();
-
- /**
- * Support indicates connector accepts the EXISTS criteria
- * @since 4.0
- */
- boolean supportsExistsCriteria();
-
- /**
- * Support indicates connector accepts the quantified comparison criteria that
- * use SOME
- * @since 4.0
- */
- boolean supportsQuantifiedCompareCriteriaSome();
-
- /**
- * Support indicates connector accepts the quantified comparison criteria that
- * use ALL
- * @since 4.0
- */
- boolean supportsQuantifiedCompareCriteriaAll();
-
- /**
- * Support indicates connector accepts ORDER BY clause, including multiple elements
- * and ascending and descending sorts.
- * @since 3.1 SP2
- */
- boolean supportsOrderBy();
-
- /**
- * Support indicates connector accepts ORDER BY clause with columns not from the select
- * @since 6.2
- * @return
- */
- boolean supportsOrderByUnrelated();
-
- /**
- * Whether the source supports an explicit GROUP BY clause
- * @since 6.1
- */
- boolean supportsGroupBy();
-
- /**
- * Whether the source supports the HAVING clause
- * @since 6.1
- */
- boolean supportsHaving();
-
- /**
- * Support indicates connector can accept the SUM aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesSum();
-
- /**
- * Support indicates connector can accept the AVG aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesAvg();
-
- /**
- * Support indicates connector can accept the MIN aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesMin();
-
- /**
- * Support indicates connector can accept the MAX aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesMax();
-
- /**
- * Support indicates connector can accept the COUNT aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesCount();
-
- /**
- * Support indicates connector can accept the COUNT(*) aggregate function
- * @since 3.1 SP2
- */
- boolean supportsAggregatesCountStar();
-
- /**
- * Support indicates connector can accept DISTINCT within aggregate functions
- * @since 3.1 SP2
- */
- boolean supportsAggregatesDistinct();
-
- /**
- * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and
- * HAVING clauses
- * @since 4.0
- */
- boolean supportsScalarSubqueries();
-
- /**
- * Support indicates connector can accept correlated subqueries wherever subqueries
- * are accepted
- * @since 4.0
- */
- boolean supportsCorrelatedSubqueries();
-
- /**
- * Support indicates connector can accept queries with non-searched
- * CASE <expression> WHEN <expression> ... END
- * <br>NOT CURRENTLY USED - case is pushed down as searched case
- * @since 4.0
- */
- boolean supportsCaseExpressions();
-
- /**
- * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
- * @since 4.0
- */
- boolean supportsSearchedCaseExpressions();
-
- /**
- * Support indicates that the connector supports the UNION of two queries.
- * @since 4.2
- */
- boolean supportsUnions();
-
- /**
- * Support indicates that the connector supports an ORDER BY on a SetQuery.
- * @since 5.6
- */
- boolean supportsSetQueryOrderBy();
-
- /**
- * Support indicates that the connector supports the INTERSECT of two queries.
- * @since 5.6
- */
- boolean supportsIntersect();
-
- /**
- * Support indicates that the connector supports the EXCEPT of two queries.
- * @since 5.6
- */
- boolean supportsExcept();
-
- /**
- * Get list of all supported function names. Arithmetic functions have names like
- * "+".
- * @since 3.1 SP3
- */
- List<String> getSupportedFunctions();
-
- /**
- * Get the integer value representing the number of values allowed in an IN criteria
- * in the WHERE clause of a query
- * @since 5.0
- */
- int getMaxInCriteriaSize();
-
- /**
- * <p>Support indicates that the connector supports functions in GROUP BY, such as:
- * <code>SELECT dayofmonth(theDate), COUNT(*) FROM table GROUP BY dayofmonth(theDate)</code></p>
- *
- * <br>NOT CURRENTLY USED - group by expressions create an inline view for pushdown
- * @since 5.0
- */
- boolean supportsFunctionsInGroupBy();
-
- /**
- * Gets whether the connector can limit the number of rows returned by a query.
- * @since 5.0 SP1
- */
- boolean supportsRowLimit();
-
- /**
- * Gets whether the connector supports a SQL clause (similar to the LIMIT with an offset) that can return
- * result sets that start in the middle of the resulting rows returned by a query
- * @since 5.0 SP1
- */
- boolean supportsRowOffset();
-
- /**
- * The number of groups supported in the from clause. Added for a Sybase limitation.
- * @since 5.6
- * @return the number of groups supported in the from clause, or -1 if there is no limit
- */
- int getMaxFromGroups();
-
- /**
- * Whether the source prefers to use ANSI style joins.
- * @since 6.0
- */
- boolean useAnsiJoin();
-
- /**
- * Whether the source supports queries without criteria.
- * @since 6.0
- */
- boolean requiresCriteria();
-
- /**
- * Whether the source supports {@link BatchedUpdates}
- * @since 6.0
- */
- boolean supportsBatchedUpdates();
-
- /**
- * Whether the source supports updates with multiple value sets
- * @since 6.0
- */
- boolean supportsBulkUpdate();
-
- /**
- * Support indicates that the connector can accept INSERTs with
- * values specified by an {@link SetQuery}.
- * @since 6.1
- */
- boolean supportsInsertWithQueryExpression();
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorEnvironment.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorEnvironment.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorEnvironment.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,92 +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.api;
-
-import java.util.Properties;
-
-import org.teiid.connector.language.LanguageFactory;
-
-
-/**
- * The environment provided to a connector by the Connector Manager. The
- * environment provides access to external resources the Connector writer may
- * need.
- */
-public interface ConnectorEnvironment {
-
- /**
- * Capabilities Class Name
- * @return
- */
- public String getCapabilitiesClass();
-
- /**
- * Defines if the Connector is read-only connector
- * @return
- */
- public boolean isImmutable();
-
- /**
- * Throw exception if there are more rows in the result set than specified in the MaxResultRows setting.
- * @return
- */
- public boolean isExceptionOnMaxRows();
-
- /**
- * Maximum result set rows to fetch
- * @return
- */
- public int getMaxResultRows();
-
- /**
- * Shows the XA transaction capability of the Connector.
- * @return
- */
- public boolean isXaCapable();
-
- /**
- * Obtain a reference to the logger that can be used to add messages to the
- * log files for debugging and error recovery.
- * @return The {@link ConnectorLogger}
- */
- ConnectorLogger getLogger();
-
- /**
- * Obtain a reference to the default LanguageFactory that can be used to construct
- * new language interface objects. This is typically needed when modifying the language
- * objects passed to the connector or for testing when objects need to be created.
- */
- LanguageFactory getLanguageFactory();
-
- /**
- * Obtain a reference to the type facility, which can be used to perform many type
- * conversions supplied by the Connector API.
- */
- TypeFacility getTypeFacility();
-
- /**
- * Get the Override capabilities for the connector
- * @return
- */
- Properties getOverrideCapabilities() throws ConnectorException;
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorException.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorException.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,79 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.connector.api;
-
-import javax.resource.ResourceException;
-
-/**
- * An exception the connector writer can return in case of an
- * error while using the connector.
- */
-public class ConnectorException extends ResourceException{
-
- private static final long serialVersionUID = -5980862789340592219L;
-
- /**
- * No-arg constructor required by Externalizable semantics.
- */
- public ConnectorException() {
- super();
- }
-
- /**
- * Construct an instance with the message specified.
- *
- * @param message A message describing the exception
- */
- public ConnectorException( String message ) {
- super( message );
- }
-
- public ConnectorException( String errorCode, String message ) {
- super( message, errorCode);
- }
-
- public ConnectorException( int errorCode, String message ) {
- super(message, Integer.toString(errorCode));
- }
-
-
- /**
- * Construct an instance from a message and an exception to chain to this one.
- *
- * @param code A code denoting the exception
- * @param e An exception to nest within this one
- */
- public ConnectorException( Throwable e, String message ) {
- super(message,e);
- }
-
- /**
- * Construct an instance with a linked exception specified.
- *
- * @param e An exception to chain to this exception
- */
- public ConnectorException( Throwable e ) {
- super( e );
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorLogger.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorLogger.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorLogger.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,117 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.connector.api;
-
-/**
- * Provide access to write messages to the logs.
- */
-public interface ConnectorLogger {
-
- /**
- * Log an error message.
- * @param message The message
- */
- void logError( String message );
-
- /**
- * Log an error message with an error, which may allow the stack
- * trace for the error to be logged, depending on the log configuration.
- * @param message The message
- * @param error The error
- */
- void logError( String message, Throwable error );
-
- /**
- * Log a warning message.
- * @param message The message
- */
- void logWarning( String message );
-
- /**
- * Log a warning message.
- * @param message The message
- */
- void logWarning( String message, Throwable error );
-
- /**
- * Log an informational message.
- * @param message The message
- */
- void logInfo( String message );
-
- /**
- * Log an informational message.
- * @param message The message
- */
- void logInfo( String message, Throwable error);
-
- /**
- * Log a detail debugging message.
- * @param message The message
- */
- void logDetail( String message );
-
- /**
- * Log a detail debugging message.
- * @param message The message
- */
- void logDetail( String message, Throwable error );
-
- /**
- * Log a trace debugging message.
- * @param message The message
- */
- void logTrace( String message );
-
- /**
- * Log a trace debugging message.
- * @param message The message
- */
- void logTrace( String message, Throwable error );
-
- /**
- * @return true if error logging is enabled
- */
- boolean isErrorEnabled();
-
- /**
- * @return true if warning logging is enabled
- */
- boolean isWarningEnabled();
-
- /**
- * @return true if info logging is enabled
- */
- boolean isInfoEnabled();
-
- /**
- * @return true if detail logging is enabled
- */
- boolean isDetailEnabled();
-
- /**
- * @return true if trace logging is enabled
- */
- boolean isTraceEnabled();
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/DataNotAvailableException.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/DataNotAvailableException.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/DataNotAvailableException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.api;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-
-/**
- * Used by asynch connectors to indicate data is not available
- * and results should be polled for after the given delay.
- */
-public class DataNotAvailableException extends MetaMatrixRuntimeException {
-
- private static final long serialVersionUID = 5569111182915674334L;
-
- private long retryDelay = 0;
-
- public DataNotAvailableException() {
- }
-
- public DataNotAvailableException(long retryDelay) {
- this.retryDelay = retryDelay;
- }
-
- public long getRetryDelay() {
- return retryDelay;
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/Execution.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/Execution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/Execution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,53 +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.api;
-
-/**
- * An execution represents the state and lifecycle for a particular
- * command execution. The methods provided on this interface define
- * standard lifecycle methods.
- * When execution completes, the {@link #close()} will be called. If
- * execution must be aborted, due to user or administrator action, the
- * {@link #cancel()} will be called.
- */
-public interface Execution {
-
- /**
- * Terminates the execution normally.
- */
- void close() throws ConnectorException;
-
- /**
- * Cancels the execution abnormally. This will happen via
- * a different thread from the one performing the execution, so
- * should be expected to happen in a multi-threaded scenario.
- */
- void cancel() throws ConnectorException;
-
- /**
- * Execute the associated command. Results will be retrieved through a specific sub-interface call.
- * @throws ConnectorException
- */
- void execute() throws ConnectorException;
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ExecutionContext.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ExecutionContext.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ExecutionContext.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,166 +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.api;
-
-import java.io.Serializable;
-
-import javax.security.auth.Subject;
-
-
-/**
- * The security context provides information about the user context in which
- * this query is being run.
- *
- * As of 4.2, the SecurityContext is a sub-interface of ExecutionContext such
- * that both interfaces contain all of the methods from the prior independent
- * interfaces. Thus, these interfaces can now be used interchangeably.
- *
- */
-public interface ExecutionContext {
-
- /**
- * Get the identifier for the current connector running the command
- * @return Connector identifier; never null
- */
- String getConnectorIdentifier();
-
- /**
- * Get the identifier for the command being executed. This can be
- * correlated back to identifiers exposed in other parts of the system.
- * @return command identifier
- */
- String getRequestIdentifier();
-
- /**
- * This specifies the node id for the atomic request in the relational plan of query.
- * when combined with the request identifier, uniquely identifies a command sent to a connector.
- */
- String getPartIdentifier();
-
- /**
- * Execution count defines an id; where every access to the connector from
- * the server in a given command execution boundary is uniquely defined;
- * Like for example in the case of "batched execution" of commands, each execution of
- * command gets new identifier.
- */
- String getExecutionCountIdentifier();
-
- /**
- * Get the name of the VDB this query is being run against.
- * @return VDB name, never null
- */
- String getVirtualDatabaseName();
-
- /**
- * Get the version of the VDB this query is being run against.
- * @return VDB version, never null
- */
- int getVirtualDatabaseVersion();
-
- /**
- * Get the user for the user running this query.
- * @return User, never null
- */
- Subject getSubject();
-
- /**
- * Get the trusted payload passed when the user statement was executed.
- * Teiid has no knowledge about what the payload contains - it is merely
- * passed through the system. It is most often used to pass security
- * information such as credentials.
- *
- * <p>Given that the Execution Payload is not authenticated by the Teiid
- * system, connector writers are responsible for ensuring its validity. </p>
- *
- * @return Trusted execution payload if one exists, otherwise null
- * @since 4.2
- */
- Serializable getExecutionPayload();
-
- /**
- * Get the identifier for the connection through which
- * the command is being executed. This represents the original JDBC user
- * connection to the Teiid system
- * @return Connection identifier
- */
- String getConnectionIdentifier();
-
- /**
- * When the execution is turned on with "alive=true", the execution object will not
- * be implicitly closed at the end of the last batch. It will only be closed at end
- * of the user query. This is useful in keeping the connection open for
- * LOB (clob/blob/xml) streaming.
- * @param alive
- */
- void keepExecutionAlive(boolean alive);
-
- /**
- * Return the current connector batch size. This may be used as a hint to the underlying source query.
- * @return the Connector batch size.
- */
- int getBatchSize();
-
- /**
- * Add an exception as a warning to this Execution.
- * @param ex
- */
- void addWarning(Exception ex);
-
- /**
- * Flag indicates that the operation needs to be executed in a XA transaction.
- * @return
- */
- boolean isTransactional();
-
- /**
- * Get a item that has been placed previously from cache. If no such object then a null will be returned.
- * The item is placed in {@link CacheScope.REQUEST} scope.
- * @param key
- * @return
- */
- Object get(Object key);
-
- /**
- * Place a item in the Cache in {@link CacheScope.REQUEST} scope.
- * @param key
- * @param value
- */
- void put(Object key, Object value);
-
- /**
- * Get a item that has been placed previously from cache. If no such object then a null will be returned. The item looked
- * up in the specified scope.
- * @param scope
- * @param key
- * @return
- */
- Object getFromCache(CacheScope scope, Object key);
-
- /**
- * Place a item in the Cache in the given scope.
- * @param scope
- * @param key
- * @param value
- */
- void storeInCache(CacheScope scope, Object key, Object value);
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/MetadataProvider.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/MetadataProvider.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/MetadataProvider.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,31 +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.api;
-
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-
-public interface MetadataProvider {
-
- void getConnectorMetadata(MetadataFactory metadataFactory) throws ConnectorException;
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ProcedureExecution.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ProcedureExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,44 +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.api;
-
-import java.util.List;
-
-import org.teiid.connector.language.Call;
-
-/**
- * The procedure execution represents the case where a connector can execute a
- * {@link Call}. The output may include 0 or more output parameters and
- * optionally a result set.
- */
-public interface ProcedureExecution extends ResultSetExecution {
-
- /**
- * Get the output parameter values. Results should place the return parameter
- * first if it is present, then the IN/OUT and OUT parameters should follow in
- * the order they appeared in the command.
- * @throws ConnectorException If an error occurs while retrieving the output value
- */
- List<?> getOutputParameterValues() throws ConnectorException;
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/ResultSetExecution.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/ResultSetExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/ResultSetExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,45 +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.api;
-
-import java.util.List;
-
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.QueryExpression;
-
-/**
- * Defines an execution for {@link QueryExpression}s and {@link Call}s that
- * returns a resultset, which is represented through the iterator method
- * {@link #next()}.
- */
-public interface ResultSetExecution extends Execution {
-
- /**
- * Retrieves the next row of the resultset.
- * @return the next row or null indicating that there are no more results
- * @throws ConnectorException
- * @throws DataNotAvailableException
- */
- List<?> next() throws ConnectorException, DataNotAvailableException;
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/TypeFacility.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/TypeFacility.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/TypeFacility.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,123 +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.api;
-
-import java.util.Calendar;
-import java.util.TimeZone;
-
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.common.types.JDBCSQLTypeInfo;
-
-/**
- */
-public abstract class TypeFacility {
-
- public interface RUNTIME_TYPES {
- public static final Class STRING = DataTypeManager.DefaultDataClasses.STRING;
- public static final Class BOOLEAN = DataTypeManager.DefaultDataClasses.BOOLEAN;
- public static final Class BYTE = DataTypeManager.DefaultDataClasses.BYTE;
- public static final Class SHORT = DataTypeManager.DefaultDataClasses.SHORT;
- public static final Class CHAR = DataTypeManager.DefaultDataClasses.CHAR;
- public static final Class INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
- public static final Class LONG = DataTypeManager.DefaultDataClasses.LONG;
- public static final Class BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
- public static final Class FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
- public static final Class DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
- public static final Class BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;
- public static final Class DATE = DataTypeManager.DefaultDataClasses.DATE;
- public static final Class TIME = DataTypeManager.DefaultDataClasses.TIME;
- public static final Class TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
- public static final Class OBJECT = DataTypeManager.DefaultDataClasses.OBJECT;
- public static final Class BLOB = DataTypeManager.DefaultDataClasses.BLOB;
- public static final Class CLOB = DataTypeManager.DefaultDataClasses.CLOB;
- public static final Class XML = DataTypeManager.DefaultDataClasses.XML;
- }
-
- public static final class RUNTIME_NAMES {
- public static final String STRING = DataTypeManager.DefaultDataTypes.STRING;
- public static final String BOOLEAN = DataTypeManager.DefaultDataTypes.BOOLEAN;
- public static final String BYTE = DataTypeManager.DefaultDataTypes.BYTE;
- public static final String SHORT = DataTypeManager.DefaultDataTypes.SHORT;
- public static final String CHAR = DataTypeManager.DefaultDataTypes.CHAR;
- public static final String INTEGER = DataTypeManager.DefaultDataTypes.INTEGER;
- public static final String LONG = DataTypeManager.DefaultDataTypes.LONG;
- public static final String BIG_INTEGER = DataTypeManager.DefaultDataTypes.BIG_INTEGER;
- public static final String FLOAT = DataTypeManager.DefaultDataTypes.FLOAT;
- public static final String DOUBLE = DataTypeManager.DefaultDataTypes.DOUBLE;
- public static final String BIG_DECIMAL = DataTypeManager.DefaultDataTypes.BIG_DECIMAL;
- public static final String DATE = DataTypeManager.DefaultDataTypes.DATE;
- public static final String TIME = DataTypeManager.DefaultDataTypes.TIME;
- public static final String TIMESTAMP = DataTypeManager.DefaultDataTypes.TIMESTAMP;
- public static final String OBJECT = DataTypeManager.DefaultDataTypes.OBJECT;
- public static final String NULL = DataTypeManager.DefaultDataTypes.NULL;
- public static final String BLOB = DataTypeManager.DefaultDataTypes.BLOB;
- public static final String CLOB = DataTypeManager.DefaultDataTypes.CLOB;
- public static final String XML = DataTypeManager.DefaultDataTypes.XML;
- }
-
- /**
- * Get the Class constant for the given String type name
- */
- public static Class<?> getDataTypeClass(String type) {
- return DataTypeManager.getDataTypeClass(type);
- }
-
- /**
- * Get the String constant for the given type class
- */
- public static String getDataTypeName(Class<?> type) {
- return DataTypeManager.getDataTypeName(type);
- }
-
- /**
- * Get the SQL type for the given runtime type Class constant
- * @param type
- * @return
- */
- public static final int getSQLTypeFromRuntimeType(Class<?> type) {
- return JDBCSQLTypeInfo.getSQLTypeFromRuntimeType(type);
- }
-
- public static final String getDataTypeNameFromSQLType(int sqlType) {
- return JDBCSQLTypeInfo.getTypeName(sqlType);
- }
-
- /**
- * Convert the given value to the closest runtime type see {@link RUNTIME_TYPES}
- * @param value
- * @return
- */
- public abstract Object convertToRuntimeType(Object value);
-
- /**
- * Convert the given date to a target type, optionally adjusting its display
- * for a given target Calendar.
- * @param date
- * @param initial
- * @param target
- * @param targetType
- * @return
- */
- public abstract Object convertDate(java.util.Date date, TimeZone initial, Calendar target, Class targetType);
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/api/UpdateExecution.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/UpdateExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/UpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,45 +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.api;
-
-import org.teiid.connector.language.BatchedUpdates;
-import org.teiid.connector.language.Delete;
-import org.teiid.connector.language.Insert;
-import org.teiid.connector.language.Update;
-
-
-/**
- * The update execution represents the case where a connector can
- * execute an {@link Insert}, {@link Update}, {@link Delete}, or {@link BatchedUpdates} command.
- */
-public interface UpdateExecution extends Execution {
-
- /**
- * Returns the update counts for the execution.
- * @return the update counts corresponding to the command executed
- * @throws DataNotAvailableException
- * @throws ConnectorException
- */
- int[] getUpdateCounts() throws DataNotAvailableException, ConnectorException;
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnection.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,96 +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.basic;
-
-import javax.resource.spi.LocalTransaction;
-import javax.transaction.xa.XAResource;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.Execution;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-/**
- * Provides a default implementation of a {@link PoolAwareConnection} for a Connector
- * that supports global capabilities. Extensions of this class should implement
- * {@link #createProcedureExecution(Call, ExecutionContext, RuntimeMetadata)}
- * {@link #createResultSetExecution(Call, ExecutionContext, RuntimeMetadata)}
- * {@link #createUpdateExecution(Call, ExecutionContext, RuntimeMetadata)}
- * as necessary.
- */
-public abstract class BasicConnection implements Connection {
-
-
- @Override
- public Execution createExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- if (command instanceof QueryExpression) {
- return createResultSetExecution((QueryExpression)command, executionContext, metadata);
- }
- if (command instanceof Call) {
- return createProcedureExecution((Call)command, executionContext, metadata);
- }
- return createUpdateExecution(command, executionContext, metadata);
- }
-
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata) throws ConnectorException {
- throw new ConnectorException("Unsupported Execution");
- }
-
- public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata) throws ConnectorException {
- throw new ConnectorException("Unsupported Execution");
- }
-
- public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata) throws ConnectorException {
- throw new ConnectorException("Unsupported Execution");
- }
-
- @Override
- public boolean isAlive() {
- return true;
- }
-
- @Override
- public ConnectorCapabilities getCapabilities() {
- return null;
- }
-
- @Override
- public LocalTransaction getLocalTransaction() {
- return null;
- }
-
- @Override
- public XAResource getXAResource() throws ConnectorException {
- return null;
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnector.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,36 +0,0 @@
-package org.teiid.connector.basic;
-
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-
-public abstract class BasicConnector implements Connector {
-
- protected ConnectorEnvironment config;
- protected ConnectorCapabilities capabilities;
-
- @Override
- public void initialize(ConnectorEnvironment config) throws ConnectorException {
- this.config = config;
- }
-
- @Override
- public ConnectorEnvironment getConnectorEnvironment(){
- return this.config;
- }
-
- public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
- return BasicConnectorCapabilities.class;
- }
-
- @Override
- public ConnectorCapabilities getCapabilities() throws ConnectorException {
- if (capabilities == null) {
- // create Capabilities
- capabilities = BasicManagedConnectionFactory.getInstance(ConnectorCapabilities.class, this.config.getCapabilitiesClass(), null, getDefaultCapabilities());
- }
- return capabilities;
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnectorCapabilities.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnectorCapabilities.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.basic;
-
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorCapabilities;
-
-
-/**
- * This class is a base implementation of the ConnectorCapabilities interface.
- * It is implemented to return false for all capabilities. Subclass this base
- * class and override any methods necessary to specify capabilities the
- * connector actually supports.
- */
-public class BasicConnectorCapabilities implements ConnectorCapabilities {
-
- /**
- * Construct the basic capabilities class.
- */
- public BasicConnectorCapabilities() {
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelectDistinct()
- */
- public boolean supportsSelectDistinct() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAliasedGroup()
- */
- public boolean supportsAliasedGroup() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelfJoins()
- */
- public boolean supportsSelfJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOuterJoins()
- */
- public boolean supportsOuterJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsFullOuterJoins()
- */
- public boolean supportsFullOuterJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsBetweenCriteria()
- */
- public boolean supportsBetweenCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCompareCriteriaEquals()
- */
- public boolean supportsCompareCriteriaEquals() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteria()
- */
- public boolean supportsLikeCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
- */
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteria()
- */
- public boolean supportsInCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteriaSubquery()
- */
- public boolean supportsInCriteriaSubquery() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsIsNullCriteria()
- */
- public boolean supportsIsNullCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrCriteria()
- */
- public boolean supportsOrCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsNotCriteria()
- */
- public boolean supportsNotCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsExistsCriteria()
- */
- public boolean supportsExistsCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
- */
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
- */
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrderBy()
- */
- public boolean supportsOrderBy() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesSum()
- */
- public boolean supportsAggregatesSum() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesAvg()
- */
- public boolean supportsAggregatesAvg() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMin()
- */
- public boolean supportsAggregatesMin() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMax()
- */
- public boolean supportsAggregatesMax() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCount()
- */
- public boolean supportsAggregatesCount() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCountStar()
- */
- public boolean supportsAggregatesCountStar() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesDistinct()
- */
- public boolean supportsAggregatesDistinct() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsScalarSubqueries()
- */
- public boolean supportsScalarSubqueries() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCorrelatedSubqueries()
- */
- public boolean supportsCorrelatedSubqueries() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCaseExpressions()
- */
- public boolean supportsCaseExpressions() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSearchedCaseExpressions()
- */
- public boolean supportsSearchedCaseExpressions() {
- return false;
- }
-
- /**
- * Return null to indicate no functions are supported.
- * @return null
- * @see org.teiid.connector.api.ConnectorCapabilities#getSupportedFunctions()
- */
- public List<String> getSupportedFunctions() {
- return null;
- }
-
- public boolean supportsInlineViews() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsUnions()
- * @since 4.2
- */
- public boolean supportsUnions() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#getMaxInCriteriaSize()
- * @since 4.2
- */
- public int getMaxInCriteriaSize() {
- return -1;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsFunctionsInGroupBy()
- * @since 5.0
- */
- public boolean supportsFunctionsInGroupBy() {
- return false;
- }
-
- public boolean supportsRowLimit() {
- return false;
- }
-
- public boolean supportsRowOffset() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#getMaxFromGroups()
- */
- public int getMaxFromGroups() {
- return -1; //-1 indicates no max
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsExcept()
- */
- public boolean supportsExcept() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsIntersect()
- */
- public boolean supportsIntersect() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsSetQueryOrderBy()
- */
- public boolean supportsSetQueryOrderBy() {
- return false;
- }
-
- @Override
- public boolean useAnsiJoin() {
- return false;
- }
-
- @Override
- public boolean requiresCriteria() {
- return false;
- }
-
- @Override
- public boolean supportsBatchedUpdates() {
- return false;
- }
-
- @Override
- public boolean supportsGroupBy() {
- return false;
- }
-
- @Override
- public boolean supportsHaving() {
- return false;
- }
-
- @Override
- public boolean supportsInnerJoins() {
- return false;
- }
-
- @Override
- public boolean supportsSelectExpression() {
- return false;
- }
-
- @Override
- public SupportedJoinCriteria getSupportedJoinCriteria() {
- return SupportedJoinCriteria.ANY;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return false;
- }
-
- @Override
- public boolean supportsInsertWithQueryExpression() {
- return false;
- }
-
- @Override
- public boolean supportsBulkUpdate() {
- return false;
- }
-
- @Override
- public boolean supportsOrderByUnrelated() {
- return false;
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicExecution.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,29 +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.basic;
-
-import org.teiid.connector.api.Execution;
-
-public abstract class BasicExecution implements Execution {
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnection.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.basic;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.resource.ResourceException;
-import javax.resource.spi.ConnectionEvent;
-import javax.resource.spi.ConnectionEventListener;
-import javax.resource.spi.ConnectionRequestInfo;
-import javax.resource.spi.LocalTransaction;
-import javax.resource.spi.ManagedConnection;
-import javax.resource.spi.ManagedConnectionMetaData;
-import javax.security.auth.Subject;
-import javax.transaction.xa.XAResource;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectionContext;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorException;
-
-public class BasicManagedConnection implements ManagedConnection {
- protected PrintWriter log;
- protected final Collection<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>();
- private BasicManagedConnectionFactory mcf;
- private Connection physicalConnection;
- private final Set<WrappedConnection> handles = new HashSet<WrappedConnection>();
- private Connector cf;
-
- public BasicManagedConnection(Connector connectionFactory, BasicManagedConnectionFactory mcf) throws ResourceException {
- this.cf = connectionFactory;
- this.physicalConnection = this.cf.getConnection();
- this.mcf = mcf;
- }
-
- @Override
- public void associateConnection(Object handle) throws ResourceException {
- if (!(handle instanceof WrappedConnection)) {
- throw new ConnectorException("Wrong connection supplied to assosiate");
- }
- ((WrappedConnection)handle).setManagedConnection(this);
- synchronized (this.handles) {
- this.handles.add((WrappedConnection)handle);
- }
- }
-
- @Override
- public void cleanup() throws ResourceException {
- synchronized (this.handles) {
- for (WrappedConnection wc:this.handles) {
- wc.setManagedConnection(null);
- }
- handles.clear();
- }
- ConnectionContext.setSubject(null);
- }
-
- @Override
- public void destroy() throws ResourceException {
- cleanup();
-
- this.physicalConnection.close();
- this.physicalConnection = null;
- }
-
- @Override
- public ManagedConnectionMetaData getMetaData() throws ResourceException {
- return null;
- }
-
- @Override
- public Object getConnection(Subject arg0, ConnectionRequestInfo arg1) throws ResourceException {
- if(!(arg1 instanceof ConnectionRequestInfoWrapper)) {
- throw new ConnectorException("Un recognized Connection Request Info object received");
- }
- ConnectionContext.setSubject(arg0);
- if (this.physicalConnection == null) {
- this.physicalConnection = this.cf.getConnection();
- }
-
- WrappedConnection wc = new WrappedConnection(this, mcf);
- synchronized(this.handles) {
- this.handles.add(wc);
- }
- return wc;
- }
-
- @Override
- public LocalTransaction getLocalTransaction() throws ResourceException {
- return this.physicalConnection.getLocalTransaction();
- }
-
- @Override
- public XAResource getXAResource() throws ResourceException {
- return this.physicalConnection.getXAResource();
- }
-
- @Override
- public void addConnectionEventListener(ConnectionEventListener arg0) {
- synchronized (this.listeners) {
- this.listeners.add(arg0);
- }
- }
-
- @Override
- public void removeConnectionEventListener(ConnectionEventListener arg0) {
- synchronized (this.listeners) {
- this.listeners.remove(arg0);
- }
- }
-
- @Override
- public void setLogWriter(PrintWriter arg0) throws ResourceException {
- this.log = arg0;
- }
-
- @Override
- public PrintWriter getLogWriter() throws ResourceException {
- return this.log;
- }
-
- // called by the wrapped connection to notify the close of the connection.
- void connectionClosed(WrappedConnection wc) throws ConnectorException {
-
- synchronized (this.handles) {
- handles.remove(wc);
- }
-
- ConnectionEvent ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED);
- ce.setConnectionHandle(wc);
-
- ArrayList<ConnectionEventListener> copy = null;
- synchronized (this.listeners) {
- copy = new ArrayList<ConnectionEventListener>(this.listeners);
- }
-
- for(ConnectionEventListener l: copy) {
- l.connectionClosed(ce);
- }
-
- // check if connector is a facade for another; in which case release it to the pool
- if (this.mcf.getSourceJNDIName() != null) {
- synchronized(this.physicalConnection) {
- this.physicalConnection.close();
- this.physicalConnection = null;
- }
- }
- }
-
- public boolean isValid() throws ConnectorException {
- return this.physicalConnection.isAlive();
- }
-
- Connection getConnection() throws ConnectorException {
- if (this.physicalConnection == null)
- throw new ConnectorException("Connection has been destroyed!!!");
- return this.physicalConnection;
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnectionFactory.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnectionFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,240 +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.basic;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.resource.ResourceException;
-import javax.resource.spi.ConnectionManager;
-import javax.resource.spi.ConnectionRequestInfo;
-import javax.resource.spi.ManagedConnection;
-import javax.resource.spi.ManagedConnectionFactory;
-import javax.resource.spi.ResourceAdapter;
-import javax.resource.spi.ResourceAdapterAssociation;
-import javax.resource.spi.ValidatingManagedConnectionFactory;
-import javax.security.auth.Subject;
-
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.language.LanguageFactory;
-
-import com.metamatrix.core.MetaMatrixCoreException;
-import com.metamatrix.core.util.ReflectionHelper;
-
-public class BasicManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation, ConnectorEnvironment, ValidatingManagedConnectionFactory {
-
- private static final long serialVersionUID = -7302713800883776790L;
- private static final TypeFacility TYPE_FACILITY = new TypeFacilityImpl();
- private ConnectorLogger logger = new DefaultConnectorLogger();
- private PrintWriter log;
- private BasicResourceAdapter ra;
-
- // Properties set by ra.xml
- private String connectorClass;
- private String capabilitiesClass;
- private boolean immutable = false;
- private boolean exceptionOnMaxRows = false;
- private int maxResultRows = -1;
- private boolean xaCapable;
- private String sourceJNDIName;
-
- private String overrideCapabilitiesFile;
-
- // derived
- private Properties overrideCapabilities;
-
- @Override
- public Object createConnectionFactory() throws ResourceException {
- try {
- Object o = ReflectionHelper.create(this.connectorClass, null, Thread.currentThread().getContextClassLoader());
- if(!(o instanceof Connector)) {
- throw new ConnectorException("Invalid Connector class specified="+this.connectorClass);
- }
- Connector connector = (Connector)o;
- connector.initialize(this);
- return connector;
- } catch (MetaMatrixCoreException e) {
- throw new ResourceException(e);
- }
- }
-
- @Override
- public Object createConnectionFactory(ConnectionManager arg0) throws ResourceException {
- return new WrappedConnector((Connector)createConnectionFactory(), arg0, this);
- }
-
- @Override
- public ManagedConnection createManagedConnection(Subject arg0, ConnectionRequestInfo arg1) throws ResourceException {
- ConnectionRequestInfoWrapper criw = (ConnectionRequestInfoWrapper)arg1;
- return new BasicManagedConnection(criw.actualConnector, this);
- }
-
- @Override
- public PrintWriter getLogWriter() throws ResourceException {
- return this.log;
- }
-
- @Override
- public ManagedConnection matchManagedConnections(Set arg0, Subject arg1, ConnectionRequestInfo arg2) throws ResourceException {
- // rameshTODO: to manage per-user based pools the information in the request info needs to be used to filter.
- return (ManagedConnection)arg0.iterator().next();
- }
-
- @Override
- public void setLogWriter(PrintWriter arg0) throws ResourceException {
- this.log = arg0;
- }
-
- @Override
- public ResourceAdapter getResourceAdapter() {
- return this.ra;
- }
-
- @Override
- public void setResourceAdapter(ResourceAdapter arg0) throws ResourceException {
- this.ra = (BasicResourceAdapter)arg0;
- }
-
- public void setConnectorClass(String arg0) {
- this.connectorClass = arg0;
- }
-
- public void setCapabilitiesClass(String arg0) {
- this.capabilitiesClass = arg0;
- }
-
- public void setImmutable(Boolean arg0) {
- this.immutable = arg0.booleanValue();
- }
-
- public void setExceptionOnMaxRows(Boolean arg0) {
- this.exceptionOnMaxRows = arg0.booleanValue();
- }
-
- public void setMaxResultRows(Integer arg0) {
- this.maxResultRows = arg0.intValue();
- }
-
- public String getCapabilitiesClass() {
- return capabilitiesClass;
- }
-
- public boolean isImmutable() {
- return immutable;
- }
-
- public boolean isExceptionOnMaxRows() {
- return exceptionOnMaxRows;
- }
-
- public int getMaxResultRows() {
- return maxResultRows;
- }
-
- public boolean isXaCapable() {
- return xaCapable;
- }
-
- public void setXaCapable(Boolean arg0) {
- this.xaCapable = arg0.booleanValue();
- }
-
- @Override
- public LanguageFactory getLanguageFactory() {
- return LanguageFactory.INSTANCE;
- }
-
- @Override
- public ConnectorLogger getLogger() {
- return logger;
- }
-
- @Override
- public TypeFacility getTypeFacility() {
- return TYPE_FACILITY;
- }
-
- public void setSourceJNDIName(String arg0) {
- this.sourceJNDIName = arg0;
- }
-
- public String getSourceJNDIName() {
- return sourceJNDIName;
- }
-
- @Override
- public Properties getOverrideCapabilities() throws ConnectorException {
- if (this.overrideCapabilities == null && this.overrideCapabilitiesFile != null) {
- try {
- this.overrideCapabilities = new Properties();
- this.overrideCapabilities.loadFromXML(this.getClass().getResourceAsStream(this.overrideCapabilitiesFile));
- } catch (IOException e) {
- throw new ConnectorException(e);
- }
- }
- return this.overrideCapabilities;
- }
-
- public void setOverrideCapabilitiesFile(String propsFile) {
- this.overrideCapabilitiesFile = propsFile;
- }
-
- public static <T> T getInstance(Class<T> expectedType, String className, Collection ctorObjs, Class defaultClass) throws ConnectorException {
- try {
- if (className == null) {
- if (defaultClass == null) {
- throw new ConnectorException("Neither class name or default class specified to create an instance");
- }
- return expectedType.cast(defaultClass.newInstance());
- }
- return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader()));
- } catch (MetaMatrixCoreException e) {
- throw new ConnectorException(e);
- } catch (IllegalAccessException e) {
- throw new ConnectorException(e);
- } catch(InstantiationException e) {
- throw new ConnectorException(e);
- }
- }
-
- @Override
- public Set<BasicManagedConnection> getInvalidConnections(Set arg0) throws ResourceException {
- HashSet<BasicManagedConnection> result = new HashSet<BasicManagedConnection>();
- for (Object object : arg0) {
- if (object instanceof BasicManagedConnection) {
- BasicManagedConnection bmc = (BasicManagedConnection)object;
- if (!bmc.isValid()) {
- result.add(bmc);
- }
- }
- }
- return result;
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicResourceAdapter.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicResourceAdapter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicResourceAdapter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,68 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2009, 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.
- */
-package org.teiid.connector.basic;
-
-import javax.resource.ResourceException;
-import javax.resource.spi.ActivationSpec;
-import javax.resource.spi.BootstrapContext;
-import javax.resource.spi.ResourceAdapter;
-import javax.resource.spi.ResourceAdapterInternalException;
-import javax.resource.spi.XATerminator;
-import javax.resource.spi.endpoint.MessageEndpointFactory;
-import javax.resource.spi.work.WorkManager;
-import javax.transaction.xa.XAResource;
-
-public class BasicResourceAdapter implements ResourceAdapter {
- BootstrapContext ctx;
-
- @Override
- public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException {
- throw new UnsupportedOperationException("not supported");
- }
-
- @Override
- public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) {
- throw new UnsupportedOperationException("not supported");
- }
-
- @Override
- public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
- return new XAResource[0];
- }
-
- @Override
- public void start(BootstrapContext ctx) throws ResourceAdapterInternalException {
- this.ctx = ctx;
- }
-
- @Override
- public void stop() {
- }
-
- public WorkManager getWorkManager() {
- return ctx.getWorkManager();
- }
-
- public XATerminator getXATerminator() {
- return ctx.getXATerminator();
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/ConnectionRequestInfoWrapper.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/ConnectionRequestInfoWrapper.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/ConnectionRequestInfoWrapper.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,34 +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.basic;
-
-import javax.resource.spi.ConnectionRequestInfo;
-
-import org.teiid.connector.api.Connector;
-
-class ConnectionRequestInfoWrapper implements ConnectionRequestInfo {
- Connector actualConnector;
-
- public ConnectionRequestInfoWrapper(Connector connector) {
- this.actualConnector = connector;
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/DefaultConnectorLogger.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/DefaultConnectorLogger.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/DefaultConnectorLogger.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,110 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-/*
- * Date: Sep 16, 2003
- * Time: 11:23:00 AM
- */
-package org.teiid.connector.basic;
-
-import org.teiid.connector.api.ConnectorLogger;
-
-/**
- * DefaultConnectorLogger.
- */
-public class DefaultConnectorLogger implements ConnectorLogger {
- @Override
- public void logError(String message) {
- //LogManager.logError(CTX_CONNECTOR, message);
- }
- @Override
- public void logError(String message, Throwable error) {
- // LogManager.logError(CTX_CONNECTOR, error, message);
- }
- @Override
- public void logWarning(String message) {
- // LogManager.logWarning(CTX_CONNECTOR, message);
- }
- @Override
- public void logInfo(String message) {
- //LogManager.logInfo(CTX_CONNECTOR, message);
- }
- @Override
- public void logDetail(String message) {
- //LogManager.logDetail(CTX_CONNECTOR, message);
- }
-
- @Override
- public void logTrace(String message) {
- // LogManager.logTrace(CTX_CONNECTOR, message);
- }
-
- @Override
- public boolean isDetailEnabled() {
- //return LogManager.isMessageToBeRecorded(CTX_CONNECTOR, MessageLevel.DETAIL);
- return true;
- }
-
- @Override
- public boolean isErrorEnabled() {
- //return LogManager.isMessageToBeRecorded(CTX_CONNECTOR, MessageLevel.ERROR);
- return true;
- }
-
- @Override
- public boolean isInfoEnabled() {
- //return LogManager.isMessageToBeRecorded(CTX_CONNECTOR, MessageLevel.INFO);
- return true;
- }
-
- @Override
- public boolean isTraceEnabled() {
- //return LogManager.isMessageToBeRecorded(CTX_CONNECTOR, MessageLevel.TRACE);
- return true;
- }
-
- @Override
- public boolean isWarningEnabled() {
- //return LogManager.isMessageToBeRecorded(CTX_CONNECTOR, MessageLevel.WARNING);
- return true;
- }
-
- @Override
- public void logDetail(String message, Throwable error) {
- //LogManager.log(MessageLevel.DETAIL, CTX_CONNECTOR, error, message);
- }
-
- @Override
- public void logInfo(String message, Throwable error) {
- //LogManager.log(MessageLevel.INFO, CTX_CONNECTOR, error, message);
- }
-
- @Override
- public void logTrace(String message, Throwable error) {
- //LogManager.log(MessageLevel.TRACE, CTX_CONNECTOR, error, message);
- }
-
- @Override
- public void logWarning(String message, Throwable error) {
- //LogManager.log(MessageLevel.WARNING, CTX_CONNECTOR, error, message);
- }
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/TypeFacilityImpl.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/TypeFacilityImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/TypeFacilityImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,52 +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.basic;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.TimeZone;
-
-import org.teiid.connector.api.TypeFacility;
-
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.common.util.TimestampWithTimezone;
-
-/**
- */
-public class TypeFacilityImpl extends TypeFacility {
-
- public TypeFacilityImpl() {
- }
-
- @Override
- public Object convertToRuntimeType(Object value) {
- return DataTypeManager.convertToRuntimeType(value);
- }
-
- @Override
- public Object convertDate(Date date, TimeZone initial, Calendar target,
- Class targetType) {
- return TimestampWithTimezone.create(date, initial, target, targetType);
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnection.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,109 +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.basic;
-
-import java.lang.reflect.Proxy;
-
-import javax.resource.spi.LocalTransaction;
-import javax.transaction.xa.XAResource;
-
-import org.teiid.connector.DataPlugin;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.Execution;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.MetadataProvider;
-import org.teiid.connector.basic.WrappedConnector.CapabilitesOverloader;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-public class WrappedConnection implements Connection, MetadataProvider {
-
- private ConnectorEnvironment env;
- private ConnectorCapabilities caps;
- private BasicManagedConnection mc;
- boolean closed = false;
-
- public WrappedConnection(BasicManagedConnection mc, ConnectorEnvironment env) {
- this.mc = mc;
- this.env = env;
- }
-
- @Override
- public void close() throws ConnectorException {
- if (!this.closed && this.mc != null) {
- this.closed = true;
- this.mc.connectionClosed(this);
- this.mc = null;
- }
- }
-
- @Override
- public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return this.mc.getConnection().createExecution(command, executionContext, metadata);
- }
-
- @Override
- public ConnectorCapabilities getCapabilities() throws ConnectorException {
- if (this.caps == null) {
- this.caps = this.mc.getConnection().getCapabilities();
- if (caps != null && this.env.getOverrideCapabilities() != null) {
- caps = (ConnectorCapabilities) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {ConnectorCapabilities.class}, new CapabilitesOverloader(caps, this.env.getOverrideCapabilities()));
- }
- }
- return this.caps;
- }
-
- @Override
- public LocalTransaction getLocalTransaction() throws ConnectorException {
- return this.mc.getConnection().getLocalTransaction();
- }
-
- @Override
- public boolean isAlive() throws ConnectorException {
- return this.mc.getConnection().isAlive();
- }
-
- @Override
- public XAResource getXAResource() throws ConnectorException {
- return this.mc.getConnection().getXAResource();
- }
-
- @Override
- public void getConnectorMetadata(MetadataFactory metadataFactory) throws ConnectorException {
- if (this.mc.getConnection() instanceof MetadataProvider) {
- ((MetadataProvider) this.mc.getConnection()).getConnectorMetadata(metadataFactory);
- } else {
- throw new ConnectorException(DataPlugin.Util.getString("WrappedConnection.no_metadata")); //$NON-NLS-1$
- }
- }
-
- // Called by managed connection for the connection management
- void setManagedConnection(BasicManagedConnection mc) {
- this.mc = mc;
- }
-
-}
Deleted: trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnector.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.basic;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.Properties;
-
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import javax.resource.Referenceable;
-import javax.resource.ResourceException;
-import javax.resource.spi.ConnectionManager;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-
-import com.metamatrix.core.MetaMatrixCoreException;
-import com.metamatrix.core.util.ReflectionHelper;
-import com.metamatrix.core.util.StringUtil;
-
-public class WrappedConnector implements Connector, Referenceable, Serializable {
-
- private static final long serialVersionUID = 5499157394014613035L;
- private Connector delegate;
- private ConnectionManager cm;
- private BasicManagedConnectionFactory mcf;
- private Reference reference;
- ConnectorCapabilities caps;
-
- public WrappedConnector(Connector delegate, ConnectionManager cm, BasicManagedConnectionFactory mcf) {
- this.delegate = delegate;
- this.cm = cm;
- this.mcf = mcf;
- }
-
- @Override
- public void initialize(ConnectorEnvironment config) throws ConnectorException {
- this.delegate.initialize(config);
- }
-
- @Override
- public ConnectorCapabilities getCapabilities() throws ConnectorException {
- if (this.caps != null) {
- return this.caps;
- }
-
- // see if enhanced capabilities are available from the connector.
- this.caps = delegate.getCapabilities();
-
- // if not use the default capabilities specified in the configuration.
- if (this.caps == null) {
- try {
- Object o = ReflectionHelper.create(this.mcf.getCapabilitiesClass(), null, Thread.currentThread().getContextClassLoader());
- this.caps = (ConnectorCapabilities)o;
- } catch (MetaMatrixCoreException e) {
- throw new ConnectorException(e);
- }
- }
- // capabilities overload
- ConnectorEnvironment env = getConnectorEnvironment();
- if (this.caps != null && env.getOverrideCapabilities() != null) {
- this.caps = (ConnectorCapabilities) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {ConnectorCapabilities.class}, new CapabilitesOverloader(this.caps, env.getOverrideCapabilities()));
- }
- return caps;
- }
-
- @Override
- public Connection getConnection() throws ConnectorException {
- try {
- return (Connection)cm.allocateConnection(mcf, new ConnectionRequestInfoWrapper(this.delegate));
- } catch (ResourceException e) {
- throw new ConnectorException(e);
- }
- }
-
- @Override
- public ConnectorEnvironment getConnectorEnvironment() {
- return this.delegate.getConnectorEnvironment();
- }
-
- @Override
- public void setReference(Reference arg0) {
- this.reference = arg0;
- }
-
- @Override
- public Reference getReference() throws NamingException {
- return this.reference;
- }
-
-
- /**
- * Overloads the connector capabilities with one defined in the connector binding properties
- */
- static final class CapabilitesOverloader implements InvocationHandler {
- ConnectorCapabilities caps;
- Properties properties;
-
- CapabilitesOverloader(ConnectorCapabilities caps, Properties properties){
- this.caps = caps;
- this.properties = properties;
- }
-
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- String value = this.properties.getProperty(method.getName());
- if (value == null || value.trim().length() == 0 || (args != null && args.length != 0)) {
- return method.invoke(this.caps, args);
- }
- return StringUtil.valueOf(value, method.getReturnType());
- }
- }
-}
Modified: trunk/connector-api/src/main/java/org/teiid/connector/language/Condition.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/language/Condition.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/language/Condition.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.connector.language;
-import org.teiid.connector.api.TypeFacility;
+import org.teiid.resource.cci.TypeFacility;
/**
* Represents criteria, which is also a boolean expression
Modified: trunk/connector-api/src/main/java/org/teiid/connector/language/LanguageFactory.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/language/LanguageFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/language/LanguageFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,6 @@
package org.teiid.connector.language;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Modified: trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/BaseColumn.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/BaseColumn.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/BaseColumn.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.connector.metadata.runtime;
-import org.teiid.connector.api.TypeFacility;
+import org.teiid.resource.cci.TypeFacility;
public abstract class BaseColumn extends AbstractMetadataRecord {
Modified: trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/MetadataFactory.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/MetadataFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/MetadataFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,8 +29,8 @@
import java.util.Properties;
import org.teiid.connector.DataPlugin;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.TypeFacility;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.TypeFacility;
import com.metamatrix.core.id.UUIDFactory;
Modified: trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/RuntimeMetadata.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/RuntimeMetadata.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/main/java/org/teiid/connector/metadata/runtime/RuntimeMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.connector.metadata.runtime;
-import org.teiid.connector.api.ConnectorException;
+import org.teiid.resource.ConnectorException;
/**
* Helper methods that can be used to access runtime metadata.
Copied: trunk/connector-api/src/main/java/org/teiid/logging/AuditMessage.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/logging/api/AuditMessage.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/AuditMessage.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/AuditMessage.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,72 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.util.Arrays;
+
+/**
+ * Log format for auditing.
+ */
+public class AuditMessage {
+ private String context;
+ private String activity;
+ private String principal;
+ private Object[] resources;
+
+ public AuditMessage(String context, String activity, String principal, String[] resources ) {
+ this.context = context;
+ this.activity = activity;
+ this.principal = principal;
+ this.resources = resources;
+ }
+
+ public String getContext() {
+ return this.context;
+ }
+
+ public String getActivity() {
+ return this.activity;
+ }
+
+ public String getPrincipal() {
+ return this.principal;
+ }
+
+ public Object[] getResources() {
+ return this.resources;
+ }
+
+ public String toString() {
+ StringBuffer msg = new StringBuffer();
+ msg.append(" ["); //$NON-NLS-1$
+ msg.append( getPrincipal() );
+ msg.append("] <"); //$NON-NLS-1$
+ msg.append( getContext() );
+ msg.append('.');
+ msg.append( getActivity() );
+ msg.append("> "); //$NON-NLS-1$
+ msg.append( Arrays.toString(resources) );
+ return msg.toString();
+ }
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/logging/CommandLogMessage.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/logging/api/CommandLogMessage.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/CommandLogMessage.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/CommandLogMessage.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,215 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.text.DateFormat;
+import java.util.Date;
+
+import org.teiid.resource.cci.ExecutionContext;
+
+/**
+ * Log Message for source and user command events.
+ */
+public class CommandLogMessage {
+
+ public enum Event {
+ NEW,
+ END,
+ CANCEL,
+ ERROR
+ }
+
+ private boolean source;
+ private Event event;
+ private long timestamp;
+
+ // Transaction info
+ private String transactionID;
+
+ // Session info
+ private String sessionID;
+ private String applicationName;
+ private String principal;
+ private String vdbName;
+ private int vdbVersion;
+
+ // RequestInfo
+ private String requestID;
+ private Long sourceCommandID;
+ private String sql;
+ private Integer rowCount;
+ private String modelName;
+ private String connectorBindingName;
+ private ExecutionContext executionContext;
+
+ public CommandLogMessage(long timestamp,
+ String requestID,
+ String transactionID,
+ String sessionID,
+ String applicationName,
+ String principal,
+ String vdbName,
+ int vdbVersion,
+ String sql) {
+ // userCommandStart
+ this(timestamp, requestID, transactionID, sessionID, principal, vdbName, vdbVersion, null, Event.NEW);
+ this.applicationName = applicationName;
+ this.sql = sql;
+ }
+ public CommandLogMessage(long timestamp,
+ String requestID,
+ String transactionID,
+ String sessionID,
+ String principal,
+ String vdbName,
+ int vdbVersion,
+ Integer finalRowCount,
+ Event event) {
+ // userCommandEnd
+ this.event = event;
+ this.timestamp = timestamp;
+ this.requestID = requestID;
+ this.transactionID = transactionID;
+ this.sessionID = sessionID;
+ this.principal = principal;
+ this.vdbName = vdbName;
+ this.vdbVersion = vdbVersion;
+ this.rowCount = finalRowCount;
+ }
+ public CommandLogMessage(long timestamp,
+ String requestID,
+ long sourceCommandID,
+ String transactionID,
+ String modelName,
+ String connectorBindingName,
+ String sessionID,
+ String principal,
+ String sql,
+ ExecutionContext context) {
+ // dataSourceCommandStart
+ this(timestamp, requestID, sourceCommandID, transactionID, modelName, connectorBindingName, sessionID, principal, null, Event.NEW, context);
+ this.sql = sql;
+ }
+ public CommandLogMessage(long timestamp,
+ String requestID,
+ long sourceCommandID,
+ String transactionID,
+ String modelName,
+ String connectorBindingName,
+ String sessionID,
+ String principal,
+ Integer finalRowCount,
+ Event event,
+ ExecutionContext context) {
+ // dataSourceCommandEnd
+ this.source = true;
+ this.event = event;
+ this.timestamp = timestamp;
+ this.requestID = requestID;
+ this.sourceCommandID = sourceCommandID;
+ this.transactionID = transactionID;
+ this.modelName = modelName;
+ this.connectorBindingName = connectorBindingName;
+ this.sessionID = sessionID;
+ this.principal = principal;
+ this.rowCount = finalRowCount;
+ this.executionContext = context;
+ }
+
+ public String toString() {
+ if (!source && event == Event.NEW) {
+ return "\tSTART USER COMMAND:\tstartTime=" + getTimestampString(new Date(timestamp)) + "\trequestID=" + requestID + "\ttxID=" + transactionID + "\tsessionID=" + sessionID + "\tapplicationName=" + applicationName + "\tprincipal=" + principal + "\tvdbName=" + vdbName + "\tvdbVersion=" + vdbVersion + "\tsql=" + sql; //$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$
+ }
+ if (!source) {
+ return "\t"+ event +" USER COMMAND:\tendTime=" + getTimestampString(new Date(timestamp)) + "\trequestID=" + requestID + "\ttxID=" + transactionID + "\tsessionID=" + sessionID + "\tprincipal=" + principal + "\tvdbName=" + vdbName + "\tvdbVersion=" + vdbVersion + "\tfinalRowCount=" + rowCount; //$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$
+ }
+ if (event == Event.NEW) {
+ return "\tSTART DATA SRC COMMAND:\tstartTime=" + getTimestampString(new Date(timestamp)) + "\trequestID=" + requestID + "\tsourceCommandID="+ sourceCommandID + "\ttxID=" + transactionID + "\tmodelName="+ modelName + "\tconnectorBindingName=" + connectorBindingName + "\tsessionID=" + sessionID + "\tprincipal=" + principal + "\tsql=" + sql; //$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$
+ }
+ return "\t"+ event +" SRC COMMAND:\tendTime=" + getTimestampString(new Date(timestamp)) + "\trequestID=" + requestID + "\tsourceCommandID="+ sourceCommandID + "\ttxID=" + transactionID + "\tmodelName="+ modelName + "\tconnectorBindingName=" + connectorBindingName + "\tsessionID=" + sessionID + "\tprincipal=" + principal + "\tfinalRowCount=" + rowCount; //$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$
+ }
+
+ private String getTimestampString(Date date) {
+ return DateFormat.getDateInstance().format(date);
+ }
+ public long getTimestamp() {
+ return timestamp;
+ }
+ public String getTransactionID() {
+ return transactionID;
+ }
+ public String getSessionID() {
+ return sessionID;
+ }
+ public String getApplicationName() {
+ return applicationName;
+ }
+ public String getPrincipal() {
+ return principal;
+ }
+ public String getVdbName() {
+ return vdbName;
+ }
+ public int getVdbVersion() {
+ return vdbVersion;
+ }
+ public String getRequestID() {
+ return requestID;
+ }
+ public Long getSourceCommandID() {
+ return sourceCommandID;
+ }
+ /**
+ * Returns the command. Only valid for {@link Event#NEW}
+ * @return
+ */
+ public String getSql() {
+ return sql;
+ }
+ /**
+ * Returns the command. Only valid for {@link Event#END}
+ * @return
+ */
+ public Integer getRowCount() {
+ return rowCount;
+ }
+ public String getModelName() {
+ return modelName;
+ }
+ public String getConnectorBindingName() {
+ return connectorBindingName;
+ }
+ public Event getStatus() {
+ return event;
+ }
+ public boolean isSource() {
+ return source;
+ }
+ /**
+ * Only available for source commands
+ * @return
+ */
+ public ExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+}
Copied: trunk/connector-api/src/main/java/org/teiid/logging/JavaLogWriter.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/JavaLogWriter.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/JavaLogWriter.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/JavaLogWriter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,75 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Write to Java logging
+ */
+public class JavaLogWriter implements LogListener {
+
+ @Override
+ public boolean isEnabled(String context, int msgLevel) {
+ Logger logger = Logger.getLogger(context);
+
+ Level javaLevel = convertLevel(msgLevel);
+ return logger.isLoggable(javaLevel);
+ }
+
+ public void log(int level, String context, Object msg) {
+ Logger logger = Logger.getLogger(context);
+
+ Level javaLevel = convertLevel(level);
+ logger.log(javaLevel, msg.toString());
+ }
+
+ public void log(int level, String context, Throwable t, Object msg) {
+ Logger logger = Logger.getLogger(context);
+
+ Level javaLevel = convertLevel(level);
+ logger.log(javaLevel, msg.toString(), t);
+ }
+
+ public Level convertLevel(int level) {
+ switch (level) {
+ case MessageLevel.CRITICAL:
+ case MessageLevel.ERROR:
+ return Level.SEVERE;
+ case MessageLevel.WARNING:
+ return Level.WARNING;
+ case MessageLevel.INFO:
+ return Level.FINE;
+ case MessageLevel.DETAIL:
+ return Level.FINER;
+ case MessageLevel.TRACE:
+ return Level.FINEST;
+ }
+ return Level.ALL;
+ }
+
+ public void shutdown() {
+ }
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/logging/JavaLogWriter.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connector-api/src/main/java/org/teiid/logging/LogConstants.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/LogConstants.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/LogConstants.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/LogConstants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,44 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+
+public interface LogConstants {
+ // add the new contexts to the Log4JUtil.java class, for configuration purpose
+ public static final String CTX_SECURITY = "org.teiid.SECURITY"; //$NON-NLS-1$
+ public static final String CTX_TRANSPORT = "org.teiid.TRANSPORT"; //$NON-NLS-1$
+ public static final String CTX_QUERY_PLANNER = "org.teiid.PLANNER"; //$NON-NLS-1$
+ public static final String CTX_DQP = "org.teiid.PROCESSOR"; //$NON-NLS-1$
+ public static final String CTX_CONNECTOR = "org.teiid.CONNECTOR"; //$NON-NLS-1$
+ public static final String CTX_BUFFER_MGR = "org.teiid.BUFFER_MGR"; //$NON-NLS-1$
+ public static final String CTX_TXN_LOG = "org.teiid.TXN_LOG"; //$NON-NLS-1$
+ public static final String CTX_COMMANDLOGGING = "org.teiid.COMMAND_LOG"; //$NON-NLS-1$
+ public static final String CTX_AUDITLOGGING = "org.teiid.AUDIT_LOG"; //$NON-NLS-1$
+ public static final String CTX_ADMIN_API = "org.teiid.ADMIN_API"; //$NON-NLS-1$
+ public static final String CTX_RUNTIME = "org.teiid.RUNTIME"; //$NON-NLS-1$
+ // Query contexts
+ public static final String CTX_FUNCTION_TREE = CTX_QUERY_PLANNER + ".FUNCTION_TREE"; //$NON-NLS-1$
+ public static final String CTX_QUERY_RESOLVER = CTX_QUERY_PLANNER + ".RESOLVER"; //$NON-NLS-1$
+ public static final String CTX_XML_PLANNER = CTX_QUERY_PLANNER + ".XML_PLANNER"; //$NON-NLS-1$
+ public static final String CTX_XML_PLAN = CTX_DQP + ".XML_PLAN"; //$NON-NLS-1$
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/logging/LogConstants.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/logging/LogListener.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/LogListener.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/LogListener.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/LogListener.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+
+/**
+ * LogListener
+ */
+public interface LogListener {
+
+ /**
+ * Is the logging for the given context at the specified message level enabled.
+ * @param context
+ * @param msgLevel
+ * @return
+ */
+ boolean isEnabled(String context, int msgLevel);
+
+ void log(int level, String context, Object msg);
+
+ void log(int level, String context, Throwable t, Object msg);
+
+ /**
+ * Shut down this listener, requesting it clean up and release any resources it
+ * may have acquired during its use. The listener is free to ignore this
+ * request if it is not responsible for managing the resources it uses or if
+ * there are no resources.
+ */
+ void shutdown();
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/logging/LogManager.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/LogManager.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/LogManager.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/LogManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,399 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+
+
+/**
+ * This class represents the interface to a single logging framework
+ * that is easily accessible by any component. Using the LogManager, a component
+ * can quickly submit a log message, and can rely upon the LogManager to determine
+ * (a) whether that message is to be recorded or discarded; and (b) where
+ * to send any recorded messages. Thus, the component's code that submits
+ * messages does not have to be modified to alter the logging behavior of the
+ * application.
+ * <p>
+ * By default, all context(s) are logged by the LogManager. The messages that
+ * the LogManager actually records and sends to the destinations
+ * can be controlled using two different and orthogonal parameters.
+ * The first is a message <i>level</i> that filters messages based upon detail,
+ * and the second is a message <i>context</i> that filters messages based upon
+ * origin. The LogManager tracks only those context(s) that should NOT be
+ * logged. Only if a message (which also is defined with these two parameters)
+ * passes both filters will it be sent to the destinations.
+ * <p>
+ * Each message is submitted with one of the following levels (determined
+ * by the particular method used to submit the message), sorted from the
+ * least detailed to the greatest:
+ * <li><b>Critical</b>: This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.</li>
+ * <li><b>Error</b>: Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.</li>
+ * <li><b>Warning</b>: Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.</li>
+ * <li><b>Information</b>: This level of logging is the usually
+ * the normal level. All interesting periodic events should be logged at this
+ * level so someone looking through the log can see the amount and kind of
+ * processing happening in the system.</li>
+ * <li><b>Detail</b>: Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.</li>
+ * <li><b>Trace</b>: A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.</li>
+ * <p>
+ * The context for a message is any application-specified String. Again, only
+ * those message contexts that match those in the LogManager's configuration will
+ * be sent to the destinations.
+ *
+ */
+public final class LogManager {
+
+ public static class LoggingProxy implements InvocationHandler {
+ private final Object instance;
+ private final String loggingContext;
+ private final int level;
+
+ public LoggingProxy(Object instance, String loggingContext, int level) {
+ this.instance = instance;
+ this.loggingContext = loggingContext;
+ this.level = level;
+ }
+
+ public Object invoke(Object proxy,
+ Method method,
+ Object[] args) throws Throwable {
+ boolean log = LogManager.isMessageToBeRecorded(loggingContext, level);
+ if (log) {
+ StringBuffer message = new StringBuffer();
+ message.append("before "); //$NON-NLS-1$
+ message.append(method.getName());
+ message.append(":"); //$NON-NLS-1$
+ message.append(instance);
+ message.append("("); //$NON-NLS-1$
+ if (args != null) {
+ for (int i = 0; i < args.length; i++) {
+ if (args[i] != null) {
+ message.append(args[i]);
+ } else {
+ message.append("null"); //$NON-NLS-1$
+ }
+ if (i != args.length - 1) {
+ message.append(","); //$NON-NLS-1$
+ }
+ }
+ }
+ message.append(")"); //$NON-NLS-1$
+ LogManager.log(level, loggingContext, message.toString());
+ }
+ try {
+ Object result = method.invoke(instance, args);
+ if (log) {
+ LogManager.log(level, loggingContext,
+ "after " + method.getName()+ " : "+result); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return result;
+ } catch (InvocationTargetException e) {
+ throw e.getTargetException();
+ }
+ }
+ }
+
+ static LogListener logListener = new JavaLogWriter(); // either injected or manually set using the set methods
+
+ /**
+ * Send a critical message to the log. This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logCritical(String context, String message) {
+ logMessage(MessageLevel.CRITICAL, context, message);
+ }
+
+ /**
+ * Send a critical message to the log. This level of message is generally
+ * used to record an event or error that must be recorded (if any logging
+ * is used). If it is used to record an error, it generally means that the
+ * system encountered a critical error which affects the integrity, accuracy,
+ * reliability and/or capability of the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logCritical(String context, Throwable e, String message) {
+ log(MessageLevel.CRITICAL,context,e,message);
+ }
+
+ /**
+ * Send an error message to the log. Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logError(String context, String message) {
+ logMessage(MessageLevel.ERROR, context,message);
+ }
+
+ /**
+ * Send an error message to the log. Error messages are generally used
+ * to record unexpected problems, or errors that are not critical in nature
+ * and from which the system can automatically recover.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logError(String context, Throwable e, String message) {
+ log(MessageLevel.ERROR,context,e,message);
+ }
+
+ /**
+ * Send a warning message to the log. Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logWarning(String context, String message) {
+ logMessage(MessageLevel.WARNING, context,message);
+ }
+
+ /**
+ * Send a warning message to the log. Warning messages generally described
+ * expected errors from which the system should recover. However, this level
+ * is used to record the fact that such an error or event did occur.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logWarning(String context, Throwable e, String message) {
+ log(MessageLevel.WARNING,context,e,message);
+ }
+
+ /**
+ * Send a information message to the log. This level of logging is the usually
+ * the normal level. All interesting periodic events should be logged at this
+ * level so someone looking through the log can see the amount and kind of
+ * processing happening in the system.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logInfo(String context, String message) {
+ logMessage(MessageLevel.INFO, context,message);
+ }
+
+ /**
+ * Send a detail message to the log. Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param msgParts the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logDetail(String context, Object ... msgParts) {
+ logMessage(MessageLevel.DETAIL, context, msgParts);
+ }
+
+ /**
+ * Send a detail message to the log. Such messages are moderately detailed,
+ * and help to debug typical problems in the system. Generally, these
+ * messages are not so detailed that the big picture gets lost.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the log message (may be null)
+ */
+ public static void logDetail(String context, Throwable e, Object ... message) {
+ log(MessageLevel.DETAIL,context,e,message);
+ }
+
+ /**
+ * Send a trace message to the log. A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param msgParts the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void logTrace(String context, Object ... msgParts) {
+ logMessage(MessageLevel.TRACE, context, msgParts);
+ }
+
+ /**
+ * Send a trace message to the log. A trace message is the most detailed
+ * logging level, used to trace system execution for really nasty problems.
+ * At this level, logging will be so verbose that the system performance
+ * may be affected.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param msgParts the individual parts of the log message (may be null)
+ */
+ public static void logTrace(String context, Throwable e, Object ... msgParts) {
+ logMessage(MessageLevel.TRACE,context,e,msgParts);
+ }
+
+ /**
+ * Send a message of the specified level to the log.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param msgLevel
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param message the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void log(int msgLevel, String context, Object message) {
+ logMessage(msgLevel, context, message);
+ }
+
+ /**
+ * Send a message of the specified level to the log.
+ * <p>
+ * Only if the log manager is configured to send such messages to the
+ * destination will the message be recorded.
+ * @param context the context for this log message (for example, the component
+ * that is generating this message).
+ * @param e the exception that is to be logged; the message is
+ * not logged if this parameter is null
+ * @param message the individual parts of the log message; the message is
+ * not logged if this parameter is null
+ */
+ public static void log(int msgLevel, String context, Throwable e, Object message) {
+ if (!isMessageToBeRecorded(context, msgLevel)) {
+ return;
+ }
+ logListener.log(msgLevel, context, e, message);
+ }
+
+ public static void setLogListener(LogListener listener) {
+ logListener.shutdown();
+ if (listener != null) {
+ logListener = listener;
+ }
+ else {
+ logListener = new JavaLogWriter();
+ }
+ }
+
+ /**
+ * Utility method to identify whether a log message with the specified
+ * context and level will be recorded in the LogManager's destinations.
+ * @param context
+ * @param msgLevel
+ * @return true if the message would be recorded if sent to the LogManager,
+ * or false if it would be discarded by the LogManager.
+ */
+ public static boolean isMessageToBeRecorded(String context, int msgLevel) {
+ if (logListener != null) {
+ return logListener.isEnabled(context, msgLevel);
+ }
+ return true;
+ }
+
+ private static void logMessage(int level, String context, Object ... msgParts) {
+ if (msgParts == null || msgParts.length == 0 || !isMessageToBeRecorded(context, level)) {
+ return;
+ }
+ logListener.log(level, context, new LogMessage(msgParts));
+ }
+
+
+ /**
+ * Create a logging proxy, that logs at entry and exit points of the method calls on the provided interfaces.
+ */
+ public static Object createLoggingProxy(final String loggingContext,
+ final Object instance,
+ final Class<?>[] interfaces,
+ final int level) {
+ return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new LoggingProxy(instance, loggingContext, level));
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/logging/LogManager.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connector-api/src/main/java/org/teiid/logging/LogMessage.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/LogMessage.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/LogMessage.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/LogMessage.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.io.Serializable;
+
+
+public class LogMessage implements Serializable{
+
+ private Object[] msgParts;
+
+ public LogMessage(Object[] msgParts) {
+ this.msgParts = msgParts;
+ }
+
+ public Object[] getMessageParts() {
+ return this.msgParts;
+ }
+
+ public String getText() {
+ StringBuffer text = null;
+ if(msgParts != null) {
+ text = new StringBuffer();
+ for(int i=0; i<msgParts.length; i++) {
+ if (i>0) text.append(" "); //$NON-NLS-1$
+ Object omsg = msgParts[i];
+ if ( omsg != null ) {
+ text.append(omsg.toString());
+ }
+ }
+ }
+
+ if (text == null) {
+ return "NULL"; //$NON-NLS-1$
+ }
+ return text.toString();
+ }
+
+ public String toString() {
+ return getText();
+ }
+}
Copied: trunk/connector-api/src/main/java/org/teiid/logging/MessageLevel.java (from rev 2083, trunk/engine/src/main/java/com/metamatrix/common/log/MessageLevel.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/logging/MessageLevel.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/logging/MessageLevel.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,230 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.util.*;
+
+/**
+ * Constants that define the level of the messages that are to be recorded
+ * by the LogManager.
+ */
+public final class MessageLevel {
+
+ /**
+ * Message level value that specifies that no messages are to be recorded.
+ */
+ public static final int NONE = 0;
+
+ /**
+ * Message level value that specifies that critical messages are to be recorded.
+ */
+ public static final int CRITICAL = 1;
+
+ /**
+ * Message level value that specifies that error messages and critical
+ * messages are to be recorded.
+ */
+ public static final int ERROR = 2;
+
+ /**
+ * Message level value that specifies that warning, error and critical
+ * messages are to be recorded.
+ */
+ public static final int WARNING = 3;
+
+ /**
+ * Message level value that specifies that information, warning, error and critical
+ * messages are to be recorded.
+ */
+ public static final int INFO = 4;
+
+ /**
+ * Message level value that specifies that detailed, information, warning, error and critical
+ * messages are to be recorded.
+ */
+ public static final int DETAIL = 5;
+
+ /**
+ * Message level value that specifies that all messages are to be recorded.
+ */
+ public static final int TRACE = 6;
+
+
+ /**
+ * The default message level is WARNING.
+ */
+ public static final int DEFAULT_MESSAGE_LEVEL = WARNING;
+
+ private static final int MINIMUM = NONE;
+ private static final int MAXIMUM = TRACE;
+
+ /**
+ * Constants that define the types of the messages that are to be recorded
+ * by the LogManager.
+ */
+ public static class Labels {
+ public static final String CRITICAL = "CRITICAL"; //$NON-NLS-1$
+ public static final String ERROR = "ERROR"; //$NON-NLS-1$
+ public static final String WARNING = "WARNING"; //$NON-NLS-1$
+ public static final String INFO = "INFO"; //$NON-NLS-1$
+ public static final String DETAIL = "DETAIL"; //$NON-NLS-1$
+ public static final String TRACE = "TRACE"; //$NON-NLS-1$
+ public static final String NONE = "NONE"; //$NON-NLS-1$
+ static final String UNKNOWN = "UNKNOWN"; //$NON-NLS-1$
+ }
+
+ /**
+ * Constants that define the types of the messages that are to be recorded
+ * by the LogManager.
+ */
+ public static class DisplayNames {
+ public static final String CRITICAL = "Critical"; //$NON-NLS-1$
+ public static final String ERROR = "Error"; //$NON-NLS-1$
+ public static final String WARNING = "Warning"; //$NON-NLS-1$
+ public static final String INFO = "Information"; //$NON-NLS-1$
+ public static final String DETAIL = "Detail"; //$NON-NLS-1$
+ public static final String TRACE = "Trace"; //$NON-NLS-1$
+ public static final String NONE = "None"; //$NON-NLS-1$
+ }
+
+ private static Map LABEL_TO_LEVEL_MAP = new HashMap();
+ private static Map DISPLAY_TO_LEVEL_MAP = new HashMap();
+ private static List LABELS = new ArrayList(MAXIMUM - MINIMUM + 1);
+ private static List DISPLAYS = new ArrayList(MAXIMUM - MINIMUM + 1);
+
+ static {
+ LABEL_TO_LEVEL_MAP.put(Labels.CRITICAL, new Integer(CRITICAL) );
+ LABEL_TO_LEVEL_MAP.put(Labels.ERROR, new Integer(ERROR) );
+ LABEL_TO_LEVEL_MAP.put(Labels.WARNING, new Integer(WARNING) );
+ LABEL_TO_LEVEL_MAP.put(Labels.INFO, new Integer(INFO) );
+ LABEL_TO_LEVEL_MAP.put(Labels.DETAIL, new Integer(DETAIL) );
+ LABEL_TO_LEVEL_MAP.put(Labels.TRACE, new Integer(TRACE) );
+ LABEL_TO_LEVEL_MAP.put(Labels.NONE, new Integer(NONE) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.CRITICAL, new Integer(CRITICAL) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.ERROR, new Integer(ERROR) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.WARNING, new Integer(WARNING) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.INFO, new Integer(INFO) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.DETAIL, new Integer(DETAIL) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.TRACE, new Integer(TRACE) );
+ DISPLAY_TO_LEVEL_MAP.put(DisplayNames.NONE, new Integer(NONE) );
+
+ // Do in the correct order so that the indexes match the levels
+ LABELS.add(Labels.NONE);
+ LABELS.add(Labels.CRITICAL);
+ LABELS.add(Labels.ERROR);
+ LABELS.add(Labels.WARNING);
+ LABELS.add(Labels.INFO);
+ LABELS.add(Labels.DETAIL);
+ LABELS.add(Labels.TRACE);
+ DISPLAYS.add(DisplayNames.NONE);
+ DISPLAYS.add(DisplayNames.CRITICAL);
+ DISPLAYS.add(DisplayNames.ERROR);
+ DISPLAYS.add(DisplayNames.WARNING);
+ DISPLAYS.add(DisplayNames.INFO);
+ DISPLAYS.add(DisplayNames.DETAIL);
+ DISPLAYS.add(DisplayNames.TRACE);
+ }
+
+ /**
+ * Utility method to set the level of messages that are recorded for this VM.
+ * @param newMessageLevel the new level; must be either
+ * <code>MessageLevel.NONE</code>,
+ * <code>MessageLevel.CRITICAL</code>,
+ * <code>MessageLevel.ERROR</code>,
+ * <code>MessageLevel.WARNING</code>,
+ * <code>MessageLevel.INFO</code>,
+ * <code>MessageLevel.DETAIL</code>, or
+ * <code>MessageLevel.TRACE.
+ * @throws IllegalArgumentException if the level is out of range.
+ */
+ public static boolean isMessageLevelValid( int newMessageLevel ) {
+ return !( newMessageLevel < MessageLevel.NONE || newMessageLevel > MessageLevel.TRACE );
+ }
+
+ /**
+ * Utility method for knowing what is the lower boundary for
+ * a valid message level.
+ * @return int message level
+ * @see #validUpperMessageLevel
+ */
+ public static int getValidLowerMessageLevel() {
+ return MessageLevel.NONE;
+ }
+
+ /**
+ * Utility method for knowing what is the upper boundary for
+ * a valid message level.
+ * @return int message level
+ * @see #validLowerMessageLevel
+ */
+ public static int getValidUpperMessageLevel() {
+ return MessageLevel.TRACE;
+ }
+
+ public static String getLabelForLevel( int level ) {
+ switch ( level ) {
+ case MessageLevel.NONE:
+ return Labels.NONE;
+ case MessageLevel.CRITICAL:
+ return Labels.CRITICAL;
+ case MessageLevel.ERROR:
+ return Labels.ERROR;
+ case MessageLevel.WARNING:
+ return Labels.WARNING;
+ case MessageLevel.INFO:
+ return Labels.INFO;
+ case MessageLevel.DETAIL:
+ return Labels.DETAIL;
+ case MessageLevel.TRACE:
+ return Labels.TRACE;
+ }
+ return Labels.UNKNOWN;
+ //throw new IllegalArgumentException("The specified message level \"" + level + "\" is invalid");
+ }
+
+ public static int getMinimumLevel() {
+ return MINIMUM;
+ }
+
+ public static int getMaximumLevel() {
+ return MAXIMUM;
+ }
+
+ public static Collection getDisplayNames() {
+ return DISPLAYS;
+ }
+
+
+ /**
+ * Utility method to get the labels for the levels, starting with the lowest
+ * level and ending with the highest level.
+ * @return an ordered list of String labels
+ */
+ public static List getLabels() {
+ return LABELS;
+ }
+
+
+
+}
+
Copied: trunk/connector-api/src/main/java/org/teiid/resource/ConnectorException.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorException.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/ConnectorException.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/ConnectorException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource;
+
+import javax.resource.ResourceException;
+
+/**
+ * An exception the connector writer can return in case of an
+ * error while using the connector.
+ */
+public class ConnectorException extends ResourceException{
+
+ private static final long serialVersionUID = -5980862789340592219L;
+
+ /**
+ * No-arg constructor required by Externalizable semantics.
+ */
+ public ConnectorException() {
+ super();
+ }
+
+ /**
+ * Construct an instance with the message specified.
+ *
+ * @param message A message describing the exception
+ */
+ public ConnectorException( String message ) {
+ super( message );
+ }
+
+ public ConnectorException( String errorCode, String message ) {
+ super( message, errorCode);
+ }
+
+ public ConnectorException( int errorCode, String message ) {
+ super(message, Integer.toString(errorCode));
+ }
+
+
+ /**
+ * Construct an instance from a message and an exception to chain to this one.
+ *
+ * @param code A code denoting the exception
+ * @param e An exception to nest within this one
+ */
+ public ConnectorException( Throwable e, String message ) {
+ super(message,e);
+ }
+
+ /**
+ * Construct an instance with a linked exception specified.
+ *
+ * @param e An exception to chain to this exception
+ */
+ public ConnectorException( Throwable e ) {
+ super( e );
+ }
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/ConnectorException.java
___________________________________________________________________
Name: svn:mergeinfo
+
Copied: trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicConnectorCapabilities.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnectorCapabilities.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicConnectorCapabilities.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,380 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.List;
+
+import org.teiid.resource.cci.ConnectorCapabilities;
+
+
+/**
+ * This class is a base implementation of the ConnectorCapabilities interface.
+ * It is implemented to return false for all capabilities. Subclass this base
+ * class and override any methods necessary to specify capabilities the
+ * connector actually supports.
+ */
+public class BasicConnectorCapabilities implements ConnectorCapabilities {
+
+ /**
+ * Construct the basic capabilities class.
+ */
+ public BasicConnectorCapabilities() {
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelectDistinct()
+ */
+ public boolean supportsSelectDistinct() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAliasedGroup()
+ */
+ public boolean supportsAliasedGroup() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelfJoins()
+ */
+ public boolean supportsSelfJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOuterJoins()
+ */
+ public boolean supportsOuterJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsFullOuterJoins()
+ */
+ public boolean supportsFullOuterJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsBetweenCriteria()
+ */
+ public boolean supportsBetweenCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCompareCriteriaEquals()
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteria()
+ */
+ public boolean supportsLikeCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
+ */
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteria()
+ */
+ public boolean supportsInCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteriaSubquery()
+ */
+ public boolean supportsInCriteriaSubquery() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsIsNullCriteria()
+ */
+ public boolean supportsIsNullCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrCriteria()
+ */
+ public boolean supportsOrCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsNotCriteria()
+ */
+ public boolean supportsNotCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsExistsCriteria()
+ */
+ public boolean supportsExistsCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
+ */
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
+ */
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrderBy()
+ */
+ public boolean supportsOrderBy() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesSum()
+ */
+ public boolean supportsAggregatesSum() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesAvg()
+ */
+ public boolean supportsAggregatesAvg() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMin()
+ */
+ public boolean supportsAggregatesMin() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMax()
+ */
+ public boolean supportsAggregatesMax() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCount()
+ */
+ public boolean supportsAggregatesCount() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCountStar()
+ */
+ public boolean supportsAggregatesCountStar() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesDistinct()
+ */
+ public boolean supportsAggregatesDistinct() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsScalarSubqueries()
+ */
+ public boolean supportsScalarSubqueries() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCorrelatedSubqueries()
+ */
+ public boolean supportsCorrelatedSubqueries() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCaseExpressions()
+ */
+ public boolean supportsCaseExpressions() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSearchedCaseExpressions()
+ */
+ public boolean supportsSearchedCaseExpressions() {
+ return false;
+ }
+
+ /**
+ * Return null to indicate no functions are supported.
+ * @return null
+ * @see org.teiid.resource.cci.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ return null;
+ }
+
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsUnions()
+ * @since 4.2
+ */
+ public boolean supportsUnions() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#getMaxInCriteriaSize()
+ * @since 4.2
+ */
+ public int getMaxInCriteriaSize() {
+ return -1;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return false;
+ }
+
+ public boolean supportsRowLimit() {
+ return false;
+ }
+
+ public boolean supportsRowOffset() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#getMaxFromGroups()
+ */
+ public int getMaxFromGroups() {
+ return -1; //-1 indicates no max
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsExcept()
+ */
+ public boolean supportsExcept() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsIntersect()
+ */
+ public boolean supportsIntersect() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsSetQueryOrderBy()
+ */
+ public boolean supportsSetQueryOrderBy() {
+ return false;
+ }
+
+ @Override
+ public boolean useAnsiJoin() {
+ return false;
+ }
+
+ @Override
+ public boolean requiresCriteria() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsBatchedUpdates() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsGroupBy() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsHaving() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsInnerJoins() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSelectExpression() {
+ return false;
+ }
+
+ @Override
+ public SupportedJoinCriteria getSupportedJoinCriteria() {
+ return SupportedJoinCriteria.ANY;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsBulkUpdate() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOrderByUnrelated() {
+ return false;
+ }
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecution.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicExecution.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecution.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,29 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import org.teiid.resource.cci.Execution;
+
+public abstract class BasicExecution implements Execution {
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecutionFactory.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicConnector.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecutionFactory.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/adapter/BasicExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,219 @@
+package org.teiid.resource.adapter;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.Collection;
+import java.util.Properties;
+
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.Execution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ExecutionFactory;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.resource.cci.TypeFacilityImpl;
+import org.teiid.resource.cci.UpdateExecution;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
+import com.metamatrix.core.MetaMatrixCoreException;
+import com.metamatrix.core.util.ReflectionHelper;
+import com.metamatrix.core.util.StringUtil;
+
+public class BasicExecutionFactory implements ExecutionFactory {
+
+ protected ConnectorCapabilities capabilities;
+ private static final TypeFacility TYPE_FACILITY = new TypeFacilityImpl();
+
+ private String capabilitiesClass;
+ private boolean immutable = false;
+ private boolean exceptionOnMaxRows = false;
+ private int maxResultRows = -1;
+ private boolean xaCapable;
+ private String overrideCapabilitiesFile;
+ private boolean sourceRequired = true;
+
+ @Override
+ public void start() throws ConnectorException {
+ }
+
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return BasicConnectorCapabilities.class;
+ }
+
+ @Override
+ public ConnectorCapabilities getCapabilities() throws ConnectorException {
+ if (capabilities == null) {
+ // create Capabilities
+ capabilities = BasicManagedConnectionFactory.getInstance(ConnectorCapabilities.class, getCapabilitiesClass(), null, getDefaultCapabilities());
+ }
+
+ // capabilities overload
+ Properties props = getOverrideCapabilities();
+ if (this.capabilities != null && props != null) {
+ this.capabilities = (ConnectorCapabilities) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {ConnectorCapabilities.class}, new CapabilitesOverloader(this.capabilities, props));
+ }
+ return capabilities;
+ }
+
+ @Override
+ public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory) throws ConnectorException {
+ if (command instanceof QueryExpression) {
+ return createResultSetExecution((QueryExpression)command, executionContext, metadata, connectionFactory);
+ }
+ if (command instanceof Call) {
+ return createProcedureExecution((Call)command, executionContext, metadata, connectionFactory);
+ }
+ return createUpdateExecution(command, executionContext, metadata, connectionFactory);
+ }
+
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ throw new ConnectorException("Unsupported Execution"); //$NON-NLS-1$
+ }
+
+ public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ throw new ConnectorException("Unsupported Execution");//$NON-NLS-1$
+ }
+
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ throw new ConnectorException("Unsupported Execution");//$NON-NLS-1$
+ }
+
+ // derived
+ private Properties overrideCapabilities;
+
+
+ @Override
+ public LanguageFactory getLanguageFactory() {
+ return LanguageFactory.INSTANCE;
+ }
+
+ @Override
+ public TypeFacility getTypeFacility() {
+ return TYPE_FACILITY;
+ }
+
+ @Override
+ public Properties getOverrideCapabilities() throws ConnectorException {
+ if (this.overrideCapabilities == null && getOverrideCapabilitiesFile() != null) {
+ try {
+ this.overrideCapabilities = new Properties();
+ this.overrideCapabilities.loadFromXML(this.getClass().getResourceAsStream(getOverrideCapabilitiesFile()));
+ } catch (IOException e) {
+ throw new ConnectorException(e);
+ }
+ }
+ return this.overrideCapabilities;
+ }
+
+ public static <T> T getInstance(Class<T> expectedType, String className, Collection ctorObjs, Class defaultClass) throws ConnectorException {
+ try {
+ if (className == null) {
+ if (defaultClass == null) {
+ throw new ConnectorException("Neither class name or default class specified to create an instance"); //$NON-NLS-1$
+ }
+ return expectedType.cast(defaultClass.newInstance());
+ }
+ return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader()));
+ } catch (MetaMatrixCoreException e) {
+ throw new ConnectorException(e);
+ } catch (IllegalAccessException e) {
+ throw new ConnectorException(e);
+ } catch(InstantiationException e) {
+ throw new ConnectorException(e);
+ }
+ }
+ /**
+ * Overloads the connector capabilities with one defined in the connector binding properties
+ */
+ static final class CapabilitesOverloader implements InvocationHandler {
+ ConnectorCapabilities caps;
+ Properties properties;
+
+ CapabilitesOverloader(ConnectorCapabilities caps, Properties properties){
+ this.caps = caps;
+ this.properties = properties;
+ }
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ String value = this.properties.getProperty(method.getName());
+ if (value == null || value.trim().length() == 0 || (args != null && args.length != 0)) {
+ return method.invoke(this.caps, args);
+ }
+ return StringUtil.valueOf(value, method.getReturnType());
+ }
+ }
+
+ @Override
+ public String getCapabilitiesClass() {
+ return capabilitiesClass;
+ }
+
+ public void setCapabilitiesClass(String arg0) {
+ this.capabilitiesClass = arg0;
+ }
+
+ @Override
+ public boolean isImmutable() {
+ return immutable;
+ }
+
+ public void setImmutable(boolean arg0) {
+ this.immutable = arg0;
+ }
+
+ @Override
+ public boolean isExceptionOnMaxRows() {
+ return exceptionOnMaxRows;
+ }
+
+ public void setExceptionOnMaxRows(boolean arg0) {
+ this.exceptionOnMaxRows = arg0;
+ }
+
+ @Override
+ public int getMaxResultRows() {
+ return maxResultRows;
+ }
+
+ public void setMaxResultRows(int arg0) {
+ this.maxResultRows = arg0;
+ }
+
+ @Override
+ public boolean isXaCapable() {
+ return xaCapable;
+ }
+
+ public void setXaCapable(boolean arg0) {
+ this.xaCapable = arg0;
+ }
+
+ @Override
+ public String getOverrideCapabilitiesFile() throws ConnectorException {
+ return this.overrideCapabilitiesFile;
+ }
+
+
+ public void setOverrideCapabilitiesFile(String overrideCapabilitiesFile) {
+ this.overrideCapabilitiesFile = overrideCapabilitiesFile;
+ }
+
+ @Override
+ public boolean isSourceRequired() {
+ return sourceRequired;
+ }
+
+ public void setSourceRequired(boolean value) {
+ this.sourceRequired = value;
+ }
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/CacheScope.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/CacheScope.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/CacheScope.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/CacheScope.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import java.io.Serializable;
+
+/**
+ * Cache Scope
+ *
+ * REQUEST - Items placed in this scope are retained until the end of the top level request. The items to be placed
+ * does not need to implement {@link Serializable}, however recommended. These items are not replicated across the cluster.
+ * SERVICE - Items from this scope are available to the identified connector
+ *
+ * All the items placed in the below scopes must be {@link Serializable}, as they are replicated across cluster.
+ *
+ * SESSION - Items placed in the scope retained until the particular User's session of top level request is alive.
+ * VDB - Items placed with this scope retained until the life of the VDB;
+ *
+ * GLOBAL - Items placed in this will available to all until the Query Service is recycled.
+ */
+public enum CacheScope {
+ REQUEST,
+ SERVICE,
+ SESSION,
+ VDB,
+ GLOBAL;
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/CacheScope.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/ConnectorCapabilities.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectorCapabilities.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/ConnectorCapabilities.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/ConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.cci;
+
+import java.util.List;
+
+import org.teiid.connector.language.BatchedUpdates;
+import org.teiid.connector.language.SetQuery;
+
+
+/**
+ * Allows a connector to specify the capabilities that a connector
+ * supports.
+ */
+public interface ConnectorCapabilities {
+
+ public enum SupportedJoinCriteria {
+ /**
+ * Indicates that any supported criteria is allowed.
+ */
+ ANY,
+ /**
+ * Indicates that any simple comparison of elements is allowed.
+ */
+ THETA,
+ /**
+ * Indicates that only equality predicates of elements are allowed.
+ */
+ EQUI,
+ /**
+ * Indicates that only equality predicates between
+ * exactly one primary and foreign key is allowed per join.
+ */
+ KEY
+ }
+
+ /**
+ * Support indicates connector can accept queries with SELECT DISTINCT
+ * @since 3.1 SP2
+ */
+ boolean supportsSelectDistinct();
+
+ /**
+ * Support indicates connector can accept expressions other than element
+ * symbols in the SELECT clause. Specific supports for the expression
+ * type are still checked.
+ * @since 6.1.0
+ */
+ boolean supportsSelectExpression();
+
+ /**
+ * Support indicates connector can accept groups with aliases
+ * @since 3.1 SP2
+ */
+ boolean supportsAliasedGroup();
+
+ /**
+ * Get the supported join criteria. A null return value will be treated
+ * as {@link SupportedJoinCriteria#ANY}
+ * @since 6.1.0
+ */
+ SupportedJoinCriteria getSupportedJoinCriteria();
+
+ /**
+ * Support indicates connector can accept inner or cross joins
+ * @since 6.1.0
+ */
+ boolean supportsInnerJoins();
+
+ /**
+ * Support indicates connector can accept self-joins where a
+ * group is joined to itself with aliases. Connector must also support
+ * {@link #supportsAliasedGroup()}.
+ * @since 3.1 SP2
+ */
+ boolean supportsSelfJoins();
+
+ /**
+ * Support indicates connector can accept left outer joins
+ * @since 3.1 SP2
+ */
+ boolean supportsOuterJoins();
+
+ /**
+ * Support indicates connector can accept full outer joins
+ * @since 3.1 SP2
+ */
+ boolean supportsFullOuterJoins();
+
+ /**
+ * Support indicates connector can accept inline views (subqueries
+ * in the FROM clause).
+ * @since 4.1
+ */
+ boolean supportsInlineViews();
+
+ /**
+ * Support indicates connector accepts criteria of form (element BETWEEN constant AND constant)
+ * <br>NOT CURRENTLY USED - between is rewritten as compound compare criteria
+ * @since 4.0
+ */
+ boolean supportsBetweenCriteria();
+
+ /**
+ * Support indicates connector accepts criteria of form (element = constant)
+ * @since 3.1 SP2
+ */
+ boolean supportsCompareCriteriaEquals();
+
+ /**
+ * Support indicates connector accepts criteria of form (element <=|>= constant)
+ * <br>The query engine will may pushdown queries containing < or > if NOT is also
+ * supported.
+ * @since 3.1 SP2
+ */
+ boolean supportsCompareCriteriaOrdered();
+
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant)
+ * @since 3.1 SP2
+ */
+ boolean supportsLikeCriteria();
+
+ /**
+ * Support indicates connector accepts criteria of form (element LIKE constant ESCAPE char)
+ * @since 3.1 SP2
+ */
+ boolean supportsLikeCriteriaEscapeCharacter();
+
+ /**
+ * Support indicates connector accepts criteria of form (element IN set)
+ * @since 3.1 SP2
+ */
+ boolean supportsInCriteria();
+
+ /**
+ * Support indicates connector accepts IN criteria with a subquery on the right side
+ * @since 4.0
+ */
+ boolean supportsInCriteriaSubquery();
+
+ /**
+ * Support indicates connector accepts criteria of form (element IS NULL)
+ * @since 3.1 SP2
+ */
+ boolean supportsIsNullCriteria();
+
+ /**
+ * Support indicates connector accepts logical criteria connected by OR
+ * @since 3.1 SP2
+ */
+ boolean supportsOrCriteria();
+
+ /**
+ * Support indicates connector accepts logical criteria NOT
+ * @since 3.1 SP2
+ */
+ boolean supportsNotCriteria();
+
+ /**
+ * Support indicates connector accepts the EXISTS criteria
+ * @since 4.0
+ */
+ boolean supportsExistsCriteria();
+
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that
+ * use SOME
+ * @since 4.0
+ */
+ boolean supportsQuantifiedCompareCriteriaSome();
+
+ /**
+ * Support indicates connector accepts the quantified comparison criteria that
+ * use ALL
+ * @since 4.0
+ */
+ boolean supportsQuantifiedCompareCriteriaAll();
+
+ /**
+ * Support indicates connector accepts ORDER BY clause, including multiple elements
+ * and ascending and descending sorts.
+ * @since 3.1 SP2
+ */
+ boolean supportsOrderBy();
+
+ /**
+ * Support indicates connector accepts ORDER BY clause with columns not from the select
+ * @since 6.2
+ * @return
+ */
+ boolean supportsOrderByUnrelated();
+
+ /**
+ * Whether the source supports an explicit GROUP BY clause
+ * @since 6.1
+ */
+ boolean supportsGroupBy();
+
+ /**
+ * Whether the source supports the HAVING clause
+ * @since 6.1
+ */
+ boolean supportsHaving();
+
+ /**
+ * Support indicates connector can accept the SUM aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesSum();
+
+ /**
+ * Support indicates connector can accept the AVG aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesAvg();
+
+ /**
+ * Support indicates connector can accept the MIN aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesMin();
+
+ /**
+ * Support indicates connector can accept the MAX aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesMax();
+
+ /**
+ * Support indicates connector can accept the COUNT aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesCount();
+
+ /**
+ * Support indicates connector can accept the COUNT(*) aggregate function
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesCountStar();
+
+ /**
+ * Support indicates connector can accept DISTINCT within aggregate functions
+ * @since 3.1 SP2
+ */
+ boolean supportsAggregatesDistinct();
+
+ /**
+ * Support indicates connector can accept scalar subqueries in the SELECT, WHERE, and
+ * HAVING clauses
+ * @since 4.0
+ */
+ boolean supportsScalarSubqueries();
+
+ /**
+ * Support indicates connector can accept correlated subqueries wherever subqueries
+ * are accepted
+ * @since 4.0
+ */
+ boolean supportsCorrelatedSubqueries();
+
+ /**
+ * Support indicates connector can accept queries with non-searched
+ * CASE <expression> WHEN <expression> ... END
+ * <br>NOT CURRENTLY USED - case is pushed down as searched case
+ * @since 4.0
+ */
+ boolean supportsCaseExpressions();
+
+ /**
+ * Support indicates connector can accept queries with searched CASE WHEN <criteria> ... END
+ * @since 4.0
+ */
+ boolean supportsSearchedCaseExpressions();
+
+ /**
+ * Support indicates that the connector supports the UNION of two queries.
+ * @since 4.2
+ */
+ boolean supportsUnions();
+
+ /**
+ * Support indicates that the connector supports an ORDER BY on a SetQuery.
+ * @since 5.6
+ */
+ boolean supportsSetQueryOrderBy();
+
+ /**
+ * Support indicates that the connector supports the INTERSECT of two queries.
+ * @since 5.6
+ */
+ boolean supportsIntersect();
+
+ /**
+ * Support indicates that the connector supports the EXCEPT of two queries.
+ * @since 5.6
+ */
+ boolean supportsExcept();
+
+ /**
+ * Get list of all supported function names. Arithmetic functions have names like
+ * "+".
+ * @since 3.1 SP3
+ */
+ List<String> getSupportedFunctions();
+
+ /**
+ * Get the integer value representing the number of values allowed in an IN criteria
+ * in the WHERE clause of a query
+ * @since 5.0
+ */
+ int getMaxInCriteriaSize();
+
+ /**
+ * <p>Support indicates that the connector supports functions in GROUP BY, such as:
+ * <code>SELECT dayofmonth(theDate), COUNT(*) FROM table GROUP BY dayofmonth(theDate)</code></p>
+ *
+ * <br>NOT CURRENTLY USED - group by expressions create an inline view for pushdown
+ * @since 5.0
+ */
+ boolean supportsFunctionsInGroupBy();
+
+ /**
+ * Gets whether the connector can limit the number of rows returned by a query.
+ * @since 5.0 SP1
+ */
+ boolean supportsRowLimit();
+
+ /**
+ * Gets whether the connector supports a SQL clause (similar to the LIMIT with an offset) that can return
+ * result sets that start in the middle of the resulting rows returned by a query
+ * @since 5.0 SP1
+ */
+ boolean supportsRowOffset();
+
+ /**
+ * The number of groups supported in the from clause. Added for a Sybase limitation.
+ * @since 5.6
+ * @return the number of groups supported in the from clause, or -1 if there is no limit
+ */
+ int getMaxFromGroups();
+
+ /**
+ * Whether the source prefers to use ANSI style joins.
+ * @since 6.0
+ */
+ boolean useAnsiJoin();
+
+ /**
+ * Whether the source supports queries without criteria.
+ * @since 6.0
+ */
+ boolean requiresCriteria();
+
+ /**
+ * Whether the source supports {@link BatchedUpdates}
+ * @since 6.0
+ */
+ boolean supportsBatchedUpdates();
+
+ /**
+ * Whether the source supports updates with multiple value sets
+ * @since 6.0
+ */
+ boolean supportsBulkUpdate();
+
+ /**
+ * Support indicates that the connector can accept INSERTs with
+ * values specified by an {@link SetQuery}.
+ * @since 6.1
+ */
+ boolean supportsInsertWithQueryExpression();
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/DataNotAvailableException.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/DataNotAvailableException.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/DataNotAvailableException.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/DataNotAvailableException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,47 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import com.metamatrix.core.MetaMatrixRuntimeException;
+
+/**
+ * Used by asynch connectors to indicate data is not available
+ * and results should be polled for after the given delay.
+ */
+public class DataNotAvailableException extends MetaMatrixRuntimeException {
+
+ private static final long serialVersionUID = 5569111182915674334L;
+
+ private long retryDelay = 0;
+
+ public DataNotAvailableException() {
+ }
+
+ public DataNotAvailableException(long retryDelay) {
+ this.retryDelay = retryDelay;
+ }
+
+ public long getRetryDelay() {
+ return retryDelay;
+ }
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/DataNotAvailableException.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/Execution.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/Execution.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/Execution.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/Execution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import org.teiid.resource.ConnectorException;
+
+/**
+ * An execution represents the state and lifecycle for a particular
+ * command execution. The methods provided on this interface define
+ * standard lifecycle methods.
+ * When execution completes, the {@link #close()} will be called. If
+ * execution must be aborted, due to user or administrator action, the
+ * {@link #cancel()} will be called.
+ */
+public interface Execution {
+
+ /**
+ * Terminates the execution normally.
+ */
+ void close() throws ConnectorException;
+
+ /**
+ * Cancels the execution abnormally. This will happen via
+ * a different thread from the one performing the execution, so
+ * should be expected to happen in a multi-threaded scenario.
+ */
+ void cancel() throws ConnectorException;
+
+ /**
+ * Execute the associated command. Results will be retrieved through a specific sub-interface call.
+ * @throws ConnectorException
+ */
+ void execute() throws ConnectorException;
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionContext.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ExecutionContext.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionContext.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionContext.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,167 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import java.io.Serializable;
+
+import javax.security.auth.Subject;
+
+
+
+/**
+ * The security context provides information about the user context in which
+ * this query is being run.
+ *
+ * As of 4.2, the SecurityContext is a sub-interface of ExecutionContext such
+ * that both interfaces contain all of the methods from the prior independent
+ * interfaces. Thus, these interfaces can now be used interchangeably.
+ *
+ */
+public interface ExecutionContext {
+
+ /**
+ * Get the identifier for the current connector running the command
+ * @return Connector identifier; never null
+ */
+ String getConnectorIdentifier();
+
+ /**
+ * Get the identifier for the command being executed. This can be
+ * correlated back to identifiers exposed in other parts of the system.
+ * @return command identifier
+ */
+ String getRequestIdentifier();
+
+ /**
+ * This specifies the node id for the atomic request in the relational plan of query.
+ * when combined with the request identifier, uniquely identifies a command sent to a connector.
+ */
+ String getPartIdentifier();
+
+ /**
+ * Execution count defines an id; where every access to the connector from
+ * the server in a given command execution boundary is uniquely defined;
+ * Like for example in the case of "batched execution" of commands, each execution of
+ * command gets new identifier.
+ */
+ String getExecutionCountIdentifier();
+
+ /**
+ * Get the name of the VDB this query is being run against.
+ * @return VDB name, never null
+ */
+ String getVirtualDatabaseName();
+
+ /**
+ * Get the version of the VDB this query is being run against.
+ * @return VDB version, never null
+ */
+ int getVirtualDatabaseVersion();
+
+ /**
+ * Get the user for the user running this query.
+ * @return User, never null
+ */
+ Subject getSubject();
+
+ /**
+ * Get the trusted payload passed when the user statement was executed.
+ * Teiid has no knowledge about what the payload contains - it is merely
+ * passed through the system. It is most often used to pass security
+ * information such as credentials.
+ *
+ * <p>Given that the Execution Payload is not authenticated by the Teiid
+ * system, connector writers are responsible for ensuring its validity. </p>
+ *
+ * @return Trusted execution payload if one exists, otherwise null
+ * @since 4.2
+ */
+ Serializable getExecutionPayload();
+
+ /**
+ * Get the identifier for the connection through which
+ * the command is being executed. This represents the original JDBC user
+ * connection to the Teiid system
+ * @return Connection identifier
+ */
+ String getConnectionIdentifier();
+
+ /**
+ * When the execution is turned on with "alive=true", the execution object will not
+ * be implicitly closed at the end of the last batch. It will only be closed at end
+ * of the user query. This is useful in keeping the connection open for
+ * LOB (clob/blob/xml) streaming.
+ * @param alive
+ */
+ void keepExecutionAlive(boolean alive);
+
+ /**
+ * Return the current connector batch size. This may be used as a hint to the underlying source query.
+ * @return the Connector batch size.
+ */
+ int getBatchSize();
+
+ /**
+ * Add an exception as a warning to this Execution.
+ * @param ex
+ */
+ void addWarning(Exception ex);
+
+ /**
+ * Flag indicates that the operation needs to be executed in a XA transaction.
+ * @return
+ */
+ boolean isTransactional();
+
+ /**
+ * Get a item that has been placed previously from cache. If no such object then a null will be returned.
+ * The item is placed in {@link CacheScope.REQUEST} scope.
+ * @param key
+ * @return
+ */
+ Object get(Object key);
+
+ /**
+ * Place a item in the Cache in {@link CacheScope.REQUEST} scope.
+ * @param key
+ * @param value
+ */
+ void put(Object key, Object value);
+
+ /**
+ * Get a item that has been placed previously from cache. If no such object then a null will be returned. The item looked
+ * up in the specified scope.
+ * @param scope
+ * @param key
+ * @return
+ */
+ Object getFromCache(CacheScope scope, Object key);
+
+ /**
+ * Place a item in the Cache in the given scope.
+ * @param scope
+ * @param key
+ * @param value
+ */
+ void storeInCache(CacheScope scope, Object key, Object value);
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionContext.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionFactory.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/Connector.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionFactory.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/ExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.cci;
+
+import java.util.Properties;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+
+
+
+/**
+ * <p>The primary entry point for a Connector. This interface should be implemented
+ * by the connector writer.</p>
+ *
+ * <p>The JCA Container will instantiate the implementation of this class. Once the class has been
+ * instantiated, the {@link #start()} method will be called
+ * with all necessary connector properties. </p>
+ */
+public interface ExecutionFactory {
+
+ /**
+ * Initialize the connector with supplied configuration
+ */
+ void start() throws ConnectorException;
+
+ /**
+ * Capabilities Class Name
+ * @return
+ */
+ @TranslatorProperty(name="capabilities-class", display="Connector Capabilities",description="The class to use to provide the Connector Capabilities")
+ public String getCapabilitiesClass();
+
+ /**
+ * Defines if the Connector is read-only connector
+ * @return
+ */
+ @TranslatorProperty(name="immutable", display="Is Immutable",description="Is Immutable, True if the source never changes.",advanced=true, defaultValue="false")
+ public boolean isImmutable();
+
+ /**
+ * Throw exception if there are more rows in the result set than specified in the MaxResultRows setting.
+ * @return
+ */
+ @TranslatorProperty(name="exception-on-max-rows", display="Exception on Exceeding Max Rows",description="Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",advanced=true, defaultValue="true")
+ public boolean isExceptionOnMaxRows();
+
+ /**
+ * Maximum result set rows to fetch
+ * @return
+ */
+ @TranslatorProperty(name="max-result-rows", display="Maximum Result Rows", description="Maximum Result Rows allowed", advanced=true, defaultValue="-1")
+ public int getMaxResultRows();
+
+ /**
+ * Shows the XA transaction capability of the Connector.
+ * @return
+ */
+ @TranslatorProperty(name="xa-capable", display="Is XA Capable", description="True, if this connector supports XA Transactions", defaultValue="false")
+ public boolean isXaCapable();
+
+ /**
+ * Get the Override capabilities for the connector
+ * @return
+ */
+ @TranslatorProperty(name="override-capabilities-file", display="Override capabilities file", description="Property file that defines the override capability properties")
+ String getOverrideCapabilitiesFile() throws ConnectorException;
+
+ /**
+ * Flag that indicates if a underlying source connection required for this execution factory to work
+ * @return
+ */
+ @TranslatorProperty(name="source-required", display="Source Connection Required", description="Flag that indicates, a source required for the translator to work", readOnly= true)
+ boolean isSourceRequired();
+
+ /**
+ * Obtain a reference to the default LanguageFactory that can be used to construct
+ * new language interface objects. This is typically needed when modifying the language
+ * objects passed to the connector or for testing when objects need to be created.
+ */
+ LanguageFactory getLanguageFactory();
+
+ /**
+ * Obtain a reference to the type facility, which can be used to perform many type
+ * conversions supplied by the Connector API.
+ */
+ TypeFacility getTypeFacility();
+
+ /**
+ * Get the Override capabilities for the connector
+ * @return
+ */
+ Properties getOverrideCapabilities() throws ConnectorException;
+
+ /**
+ * Get the capabilities of this connector. The capabilities affect what kinds of
+ * queries (and other commands) will be sent to the connector.
+ * @return ConnectorCapabilities
+ */
+ ConnectorCapabilities getCapabilities() throws ConnectorException;
+
+ /**
+ * Create an execution object for the specified command
+ * @param command the command
+ * @param executionContext Provides information about the context that this command is
+ * executing within, such as the identifiers for the command being executed
+ * @param metadata Access to runtime metadata if needed to translate the command
+ * @param connection connection factory object to the data source
+ * @return An execution object that can use to execute the command
+ */
+ Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory) throws ConnectorException;
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/MetadataProvider.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/MetadataProvider.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/MetadataProvider.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/MetadataProvider.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,32 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.resource.ConnectorException;
+
+public interface MetadataProvider {
+
+ void getConnectorMetadata(MetadataFactory metadataFactory, Object connectionFactory) throws ConnectorException;
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/MetadataProvider.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/ProcedureExecution.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ProcedureExecution.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/ProcedureExecution.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/ProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,45 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import java.util.List;
+
+import org.teiid.connector.language.Call;
+import org.teiid.resource.ConnectorException;
+
+/**
+ * The procedure execution represents the case where a connector can execute a
+ * {@link Call}. The output may include 0 or more output parameters and
+ * optionally a result set.
+ */
+public interface ProcedureExecution extends ResultSetExecution {
+
+ /**
+ * Get the output parameter values. Results should place the return parameter
+ * first if it is present, then the IN/OUT and OUT parameters should follow in
+ * the order they appeared in the command.
+ * @throws ConnectorException If an error occurs while retrieving the output value
+ */
+ List<?> getOutputParameterValues() throws ConnectorException;
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/ResultSetExecution.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ResultSetExecution.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/ResultSetExecution.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/ResultSetExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import java.util.List;
+
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.resource.ConnectorException;
+
+/**
+ * Defines an execution for {@link QueryExpression}s and {@link Call}s that
+ * returns a resultset, which is represented through the iterator method
+ * {@link #next()}.
+ */
+public interface ResultSetExecution extends Execution {
+
+ /**
+ * Retrieves the next row of the resultset.
+ * @return the next row or null indicating that there are no more results
+ * @throws ConnectorException
+ * @throws DataNotAvailableException
+ */
+ List<?> next() throws ConnectorException, DataNotAvailableException;
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/ResultSetExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/SourceSystemFunctions.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/SourceSystemFunctions.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/SourceSystemFunctions.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.cci;
+
+/**
+ * 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 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 XMLELEMENT = "xmlelement"; //$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$
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/SourceSystemFunctions.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connector-api/src/main/java/org/teiid/resource/cci/TranslatorProperty.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/TranslatorProperty.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/TranslatorProperty.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.cci;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Inherited;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+(a)Target({ElementType.METHOD})
+(a)Retention(RetentionPolicy.RUNTIME)
+@Inherited
+public @interface TranslatorProperty {
+
+ public static final String EMPTY_STRING = ""; //$NON-NLS-1$
+ public static final String GENERATED = "%GENERATED%"; //$NON-NLS-1$
+
+ // name of the property
+ String name() default GENERATED;
+
+ // type of the property
+ Class type() default java.lang.String.class;
+
+ // description
+ String description() default GENERATED;
+
+ // display name to be used in tools
+ String display() default GENERATED;
+
+ // is this mandatory property
+ boolean required() default false;
+
+ // is it modifiable
+ boolean readOnly() default false;
+
+ // is advanced?
+ boolean advanced() default false;
+
+ // should mask the values of this property in the tools
+ boolean masked() default false;
+
+ // if this represents a enum what are the legal values?
+ String[] allowed() default {};
+
+ // what is the default in the string form
+ String defaultValue() default EMPTY_STRING;
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/cci/TranslatorProperty.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacility.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/TypeFacility.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacility.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacility.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.cci;
+
+import java.util.Calendar;
+import java.util.TimeZone;
+
+import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.common.types.JDBCSQLTypeInfo;
+
+/**
+ */
+public abstract class TypeFacility {
+
+ public interface RUNTIME_TYPES {
+ public static final Class STRING = DataTypeManager.DefaultDataClasses.STRING;
+ public static final Class BOOLEAN = DataTypeManager.DefaultDataClasses.BOOLEAN;
+ public static final Class BYTE = DataTypeManager.DefaultDataClasses.BYTE;
+ public static final Class SHORT = DataTypeManager.DefaultDataClasses.SHORT;
+ public static final Class CHAR = DataTypeManager.DefaultDataClasses.CHAR;
+ public static final Class INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
+ public static final Class LONG = DataTypeManager.DefaultDataClasses.LONG;
+ public static final Class BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
+ public static final Class FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
+ public static final Class DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
+ public static final Class BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;
+ public static final Class DATE = DataTypeManager.DefaultDataClasses.DATE;
+ public static final Class TIME = DataTypeManager.DefaultDataClasses.TIME;
+ public static final Class TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
+ public static final Class OBJECT = DataTypeManager.DefaultDataClasses.OBJECT;
+ public static final Class BLOB = DataTypeManager.DefaultDataClasses.BLOB;
+ public static final Class CLOB = DataTypeManager.DefaultDataClasses.CLOB;
+ public static final Class XML = DataTypeManager.DefaultDataClasses.XML;
+ }
+
+ public static final class RUNTIME_NAMES {
+ public static final String STRING = DataTypeManager.DefaultDataTypes.STRING;
+ public static final String BOOLEAN = DataTypeManager.DefaultDataTypes.BOOLEAN;
+ public static final String BYTE = DataTypeManager.DefaultDataTypes.BYTE;
+ public static final String SHORT = DataTypeManager.DefaultDataTypes.SHORT;
+ public static final String CHAR = DataTypeManager.DefaultDataTypes.CHAR;
+ public static final String INTEGER = DataTypeManager.DefaultDataTypes.INTEGER;
+ public static final String LONG = DataTypeManager.DefaultDataTypes.LONG;
+ public static final String BIG_INTEGER = DataTypeManager.DefaultDataTypes.BIG_INTEGER;
+ public static final String FLOAT = DataTypeManager.DefaultDataTypes.FLOAT;
+ public static final String DOUBLE = DataTypeManager.DefaultDataTypes.DOUBLE;
+ public static final String BIG_DECIMAL = DataTypeManager.DefaultDataTypes.BIG_DECIMAL;
+ public static final String DATE = DataTypeManager.DefaultDataTypes.DATE;
+ public static final String TIME = DataTypeManager.DefaultDataTypes.TIME;
+ public static final String TIMESTAMP = DataTypeManager.DefaultDataTypes.TIMESTAMP;
+ public static final String OBJECT = DataTypeManager.DefaultDataTypes.OBJECT;
+ public static final String NULL = DataTypeManager.DefaultDataTypes.NULL;
+ public static final String BLOB = DataTypeManager.DefaultDataTypes.BLOB;
+ public static final String CLOB = DataTypeManager.DefaultDataTypes.CLOB;
+ public static final String XML = DataTypeManager.DefaultDataTypes.XML;
+ }
+
+ /**
+ * Get the Class constant for the given String type name
+ */
+ public static Class<?> getDataTypeClass(String type) {
+ return DataTypeManager.getDataTypeClass(type);
+ }
+
+ /**
+ * Get the String constant for the given type class
+ */
+ public static String getDataTypeName(Class<?> type) {
+ return DataTypeManager.getDataTypeName(type);
+ }
+
+ /**
+ * Get the SQL type for the given runtime type Class constant
+ * @param type
+ * @return
+ */
+ public static final int getSQLTypeFromRuntimeType(Class<?> type) {
+ return JDBCSQLTypeInfo.getSQLTypeFromRuntimeType(type);
+ }
+
+ public static final String getDataTypeNameFromSQLType(int sqlType) {
+ return JDBCSQLTypeInfo.getTypeName(sqlType);
+ }
+
+ /**
+ * Convert the given value to the closest runtime type see {@link RUNTIME_TYPES}
+ * @param value
+ * @return
+ */
+ public abstract Object convertToRuntimeType(Object value);
+
+ /**
+ * Convert the given date to a target type, optionally adjusting its display
+ * for a given target Calendar.
+ * @param date
+ * @param initial
+ * @param target
+ * @param targetType
+ * @return
+ */
+ public abstract Object convertDate(java.util.Date date, TimeZone initial, Calendar target, Class targetType);
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacilityImpl.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/TypeFacilityImpl.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacilityImpl.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/TypeFacilityImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+
+import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.common.util.TimestampWithTimezone;
+
+/**
+ */
+public class TypeFacilityImpl extends TypeFacility {
+
+ public TypeFacilityImpl() {
+ }
+
+ @Override
+ public Object convertToRuntimeType(Object value) {
+ return DataTypeManager.convertToRuntimeType(value);
+ }
+
+ @Override
+ public Object convertDate(Date date, TimeZone initial, Calendar target,
+ Class targetType) {
+ return TimestampWithTimezone.create(date, initial, target, targetType);
+ }
+
+}
Copied: trunk/connector-api/src/main/java/org/teiid/resource/cci/UpdateExecution.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/UpdateExecution.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/cci/UpdateExecution.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/cci/UpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci;
+
+import org.teiid.connector.language.BatchedUpdates;
+import org.teiid.connector.language.Delete;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.language.Update;
+import org.teiid.resource.ConnectorException;
+
+
+/**
+ * The update execution represents the case where a connector can
+ * execute an {@link Insert}, {@link Update}, {@link Delete}, or {@link BatchedUpdates} command.
+ */
+public interface UpdateExecution extends Execution {
+
+ /**
+ * Returns the update counts for the execution.
+ * @return the update counts corresponding to the command executed
+ * @throws DataNotAvailableException
+ * @throws ConnectorException
+ */
+ int[] getUpdateCounts() throws DataNotAvailableException, ConnectorException;
+
+}
Added: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnection.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnection.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,53 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionMetaData;
+import javax.resource.cci.Interaction;
+import javax.resource.cci.LocalTransaction;
+import javax.resource.cci.ResultSetInfo;
+
+public abstract class BasicConnection implements Connection {
+
+ @Override
+ public Interaction createInteraction() throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$
+ }
+
+ @Override
+ public LocalTransaction getLocalTransaction() throws ResourceException {
+ return null;
+ }
+
+ @Override
+ public ConnectionMetaData getMetaData() throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$
+ }
+
+ @Override
+ public ResultSetInfo getResultSetInfo() throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$
+ }
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnection.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnectionFactory.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnectionFactory.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,40 @@
+package org.teiid.resource.spi;
+
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionFactory;
+import javax.resource.cci.ConnectionSpec;
+import javax.resource.cci.RecordFactory;
+import javax.resource.cci.ResourceAdapterMetaData;
+
+public abstract class BasicConnectionFactory implements ConnectionFactory {
+ private static final long serialVersionUID = 2900581028589520388L;
+ private Reference reference;
+
+ @Override
+ public Connection getConnection(ConnectionSpec arg0) throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$;
+ }
+
+ @Override
+ public ResourceAdapterMetaData getMetaData() throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$;
+ }
+
+ @Override
+ public RecordFactory getRecordFactory() throws ResourceException {
+ throw new ResourceException("This operation not supported"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void setReference(Reference arg0) {
+ this.reference = arg0;
+ }
+
+ @Override
+ public Reference getReference() throws NamingException {
+ return this.reference;
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicConnectionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnection.java (from rev 2084, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnection.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnection.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,165 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.spi.ConnectionEvent;
+import javax.resource.spi.ConnectionEventListener;
+import javax.resource.spi.ConnectionRequestInfo;
+import javax.resource.spi.LocalTransaction;
+import javax.resource.spi.ManagedConnection;
+import javax.resource.spi.ManagedConnectionMetaData;
+import javax.security.auth.Subject;
+import javax.transaction.xa.XAResource;
+
+import org.teiid.resource.ConnectorException;
+
+public class BasicManagedConnection implements ManagedConnection {
+ protected PrintWriter log;
+ protected final Collection<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>();
+ private Connection physicalConnection;
+ private final Set<WrappedConnection> handles = new HashSet<WrappedConnection>();
+
+ public BasicManagedConnection(Connection connection) {
+ this.physicalConnection = connection;
+ }
+
+ @Override
+ public void associateConnection(Object handle) throws ResourceException {
+ if (!(handle instanceof WrappedConnection)) {
+ throw new ResourceException("Wrong connection supplied to assosiate"); //$NON-NLS-1$
+ }
+ ((WrappedConnection)handle).setManagedConnection(this);
+ synchronized (this.handles) {
+ this.handles.add((WrappedConnection)handle);
+ }
+ }
+
+ @Override
+ public void cleanup() throws ResourceException {
+ synchronized (this.handles) {
+ for (WrappedConnection wc:this.handles) {
+ wc.setManagedConnection(null);
+ }
+ handles.clear();
+ }
+ ConnectionContext.setSubject(null);
+ }
+
+ @Override
+ public void destroy() throws ResourceException {
+ cleanup();
+
+ this.physicalConnection.close();
+ this.physicalConnection = null;
+ }
+
+ @Override
+ public ManagedConnectionMetaData getMetaData() throws ResourceException {
+ return null;
+ }
+
+ @Override
+ public Object getConnection(Subject arg0, ConnectionRequestInfo arg1) throws ResourceException {
+ if(!(arg1 instanceof ConnectionRequestInfoWrapper)) {
+ throw new ConnectorException("Un-recognized Connection Request Info object received"); //$NON-NLS-1$
+ }
+ ConnectionContext.setSubject(arg0);
+
+ WrappedConnection wc = new WrappedConnection(this);
+ synchronized(this.handles) {
+ this.handles.add(wc);
+ }
+ return wc;
+ }
+
+ @Override
+ public LocalTransaction getLocalTransaction() throws ResourceException {
+ return null;
+ }
+
+ @Override
+ public XAResource getXAResource() throws ResourceException {
+ return null;
+ }
+
+ @Override
+ public void addConnectionEventListener(ConnectionEventListener arg0) {
+ synchronized (this.listeners) {
+ this.listeners.add(arg0);
+ }
+ }
+
+ @Override
+ public void removeConnectionEventListener(ConnectionEventListener arg0) {
+ synchronized (this.listeners) {
+ this.listeners.remove(arg0);
+ }
+ }
+
+ @Override
+ public void setLogWriter(PrintWriter arg0) throws ResourceException {
+ this.log = arg0;
+ }
+
+ @Override
+ public PrintWriter getLogWriter() throws ResourceException {
+ return this.log;
+ }
+
+ // called by the wrapped connection to notify the close of the connection.
+ void connectionClosed(WrappedConnection wc) {
+
+ synchronized (this.handles) {
+ handles.remove(wc);
+ }
+
+ ConnectionEvent ce = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED);
+ ce.setConnectionHandle(wc);
+
+ ArrayList<ConnectionEventListener> copy = null;
+ synchronized (this.listeners) {
+ copy = new ArrayList<ConnectionEventListener>(this.listeners);
+ }
+
+ for(ConnectionEventListener l: copy) {
+ l.connectionClosed(ce);
+ }
+ }
+
+ Connection getConnection() throws ConnectorException {
+ if (this.physicalConnection == null)
+ throw new ConnectorException("Connection has been destroyed!!!"); //$NON-NLS-1$
+ return this.physicalConnection;
+ }
+
+ public boolean isValid() {
+ return true;
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnection.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnectionFactory.java (from rev 2084, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicManagedConnectionFactory.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnectionFactory.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.spi;
+
+import java.io.PrintWriter;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.resource.ResourceException;
+import javax.resource.spi.ConnectionManager;
+import javax.resource.spi.ConnectionRequestInfo;
+import javax.resource.spi.ManagedConnection;
+import javax.resource.spi.ManagedConnectionFactory;
+import javax.resource.spi.ResourceAdapter;
+import javax.resource.spi.ResourceAdapterAssociation;
+import javax.resource.spi.ValidatingManagedConnectionFactory;
+import javax.security.auth.Subject;
+
+import org.teiid.resource.ConnectorException;
+
+import com.metamatrix.core.MetaMatrixCoreException;
+import com.metamatrix.core.util.ReflectionHelper;
+
+public abstract class BasicManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation, ValidatingManagedConnectionFactory {
+
+ private static final long serialVersionUID = -7302713800883776790L;
+ private PrintWriter log;
+ private BasicResourceAdapter ra;
+
+ @Override
+ public abstract Object createConnectionFactory() throws ResourceException;
+
+ @Override
+ public Object createConnectionFactory(ConnectionManager arg0) throws ResourceException {
+ return createConnectionFactory();
+ }
+
+ @Override
+ public ManagedConnection createManagedConnection(Subject arg0, ConnectionRequestInfo arg1) throws ResourceException {
+ ConnectionRequestInfoWrapper criw = (ConnectionRequestInfoWrapper)arg1;
+ return new BasicManagedConnection(criw.cf.getConnection());
+ }
+
+ @Override
+ public PrintWriter getLogWriter() throws ResourceException {
+ return this.log;
+ }
+
+ @Override
+ public ManagedConnection matchManagedConnections(Set arg0, Subject arg1, ConnectionRequestInfo arg2) throws ResourceException {
+ return (ManagedConnection)arg0.iterator().next();
+ }
+
+ @Override
+ public void setLogWriter(PrintWriter arg0) throws ResourceException {
+ this.log = arg0;
+ }
+
+ @Override
+ public ResourceAdapter getResourceAdapter() {
+ return this.ra;
+ }
+
+ @Override
+ public void setResourceAdapter(ResourceAdapter arg0) throws ResourceException {
+ this.ra = (BasicResourceAdapter)arg0;
+ }
+
+ public static <T> T getInstance(Class<T> expectedType, String className, Collection ctorObjs, Class defaultClass) throws ConnectorException {
+ try {
+ if (className == null) {
+ if (defaultClass == null) {
+ throw new ConnectorException("Neither class name or default class specified to create an instance"); //$NON-NLS-1$
+ }
+ return expectedType.cast(defaultClass.newInstance());
+ }
+ return expectedType.cast(ReflectionHelper.create(className, ctorObjs, Thread.currentThread().getContextClassLoader()));
+ } catch (MetaMatrixCoreException e) {
+ throw new ConnectorException(e);
+ } catch (IllegalAccessException e) {
+ throw new ConnectorException(e);
+ } catch(InstantiationException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public Set<BasicManagedConnection> getInvalidConnections(Set arg0) throws ResourceException {
+ HashSet<BasicManagedConnection> result = new HashSet<BasicManagedConnection>();
+ for (Object object : arg0) {
+ if (object instanceof BasicManagedConnection) {
+ BasicManagedConnection bmc = (BasicManagedConnection)object;
+ if (!bmc.isValid()) {
+ result.add(bmc);
+ }
+ }
+ }
+ return result;
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicManagedConnectionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicResourceAdapter.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/BasicResourceAdapter.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicResourceAdapter.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicResourceAdapter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2009, 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.
+ */
+package org.teiid.resource.spi;
+
+import javax.resource.ResourceException;
+import javax.resource.spi.ActivationSpec;
+import javax.resource.spi.BootstrapContext;
+import javax.resource.spi.ResourceAdapter;
+import javax.resource.spi.ResourceAdapterInternalException;
+import javax.resource.spi.XATerminator;
+import javax.resource.spi.endpoint.MessageEndpointFactory;
+import javax.resource.spi.work.WorkManager;
+import javax.transaction.xa.XAResource;
+
+public class BasicResourceAdapter implements ResourceAdapter {
+ BootstrapContext ctx;
+
+ @Override
+ public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException {
+ throw new UnsupportedOperationException("not supported"); //$NON-NLS-1$
+ }
+
+ @Override
+ public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) {
+ throw new UnsupportedOperationException("not supported"); //$NON-NLS-1$
+ }
+
+ @Override
+ public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
+ return new XAResource[0];
+ }
+
+ @Override
+ public void start(BootstrapContext ctx) throws ResourceAdapterInternalException {
+ this.ctx = ctx;
+ }
+
+ @Override
+ public void stop() {
+ }
+
+ public WorkManager getWorkManager() {
+ return ctx.getWorkManager();
+ }
+
+ public XATerminator getXATerminator() {
+ return ctx.getXATerminator();
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/BasicResourceAdapter.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionContext.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/api/ConnectionContext.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionContext.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionContext.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,44 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import javax.security.auth.Subject;
+
+/**
+ * Thread local class to access the Subject in the Connector code. This is set just before the
+ * connector connection is created.
+ */
+public class ConnectionContext {
+ private static ThreadLocal<Subject> SUBJECT = new ThreadLocal<Subject>() {
+ protected Subject initialValue() {
+ return null;
+ }
+ };
+
+ public static Subject getSubject() {
+ return SUBJECT.get();
+ }
+
+ public static void setSubject(Subject subject) {
+ SUBJECT.set(subject);
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionContext.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionRequestInfoWrapper.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/ConnectionRequestInfoWrapper.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionRequestInfoWrapper.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionRequestInfoWrapper.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,33 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import javax.resource.cci.ConnectionFactory;
+import javax.resource.spi.ConnectionRequestInfo;
+
+class ConnectionRequestInfoWrapper implements ConnectionRequestInfo {
+ ConnectionFactory cf;
+
+ public ConnectionRequestInfoWrapper(ConnectionFactory cf) {
+ this.cf = cf;
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/ConnectionRequestInfoWrapper.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnection.java (from rev 2084, trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnection.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnection.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,73 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionMetaData;
+import javax.resource.cci.Interaction;
+import javax.resource.cci.ResultSetInfo;
+
+public class WrappedConnection implements Connection {
+
+ private BasicManagedConnection mc;
+ boolean closed = false;
+
+ public WrappedConnection(BasicManagedConnection mc) {
+ this.mc = mc;
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ if (!this.closed && this.mc != null) {
+ this.closed = true;
+ this.mc.connectionClosed(this);
+ this.mc = null;
+ }
+ }
+
+ // Called by managed connection for the connection management
+ void setManagedConnection(BasicManagedConnection mc) {
+ this.mc = mc;
+ }
+
+ @Override
+ public Interaction createInteraction() throws ResourceException {
+ return this.mc.getConnection().createInteraction();
+ }
+
+ @Override
+ public javax.resource.cci.LocalTransaction getLocalTransaction() throws ResourceException {
+ return this.mc.getConnection().getLocalTransaction();
+ }
+
+ @Override
+ public ConnectionMetaData getMetaData() throws ResourceException {
+ return this.mc.getConnection().getMetaData();
+ }
+
+ @Override
+ public ResultSetInfo getResultSetInfo() throws ResourceException {
+ return this.mc.getConnection().getResultSetInfo();
+ }
+
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnection.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnectionFactory.java (from rev 2071, trunk/connector-api/src/main/java/org/teiid/connector/basic/WrappedConnector.java)
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnectionFactory.java (rev 0)
+++ trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.spi;
+
+import java.io.Serializable;
+
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.resource.Referenceable;
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionFactory;
+import javax.resource.cci.ConnectionSpec;
+import javax.resource.cci.RecordFactory;
+import javax.resource.cci.ResourceAdapterMetaData;
+import javax.resource.spi.ConnectionManager;
+
+public class WrappedConnectionFactory implements ConnectionFactory, Referenceable, Serializable {
+
+ private static final long serialVersionUID = 5499157394014613035L;
+ private ConnectionFactory delegate;
+ private ConnectionManager cm;
+ private BasicManagedConnectionFactory mcf;
+ private Reference reference;
+
+ public WrappedConnectionFactory(ConnectionFactory delegate, ConnectionManager cm, BasicManagedConnectionFactory mcf) {
+ this.delegate = delegate;
+ this.cm = cm;
+ this.mcf = mcf;
+ }
+
+ @Override
+ public Connection getConnection() throws ResourceException {
+ return (Connection)cm.allocateConnection(mcf, new ConnectionRequestInfoWrapper(this.delegate));
+ }
+
+
+ @Override
+ public void setReference(Reference arg0) {
+ this.reference = arg0;
+ }
+
+ @Override
+ public Reference getReference() throws NamingException {
+ return this.reference;
+ }
+
+ @Override
+ public Connection getConnection(ConnectionSpec arg0) throws ResourceException {
+ return getConnection();
+ }
+
+ @Override
+ public ResourceAdapterMetaData getMetaData() throws ResourceException {
+ return this.delegate.getMetaData();
+ }
+
+ @Override
+ public RecordFactory getRecordFactory() throws ResourceException {
+ return this.delegate.getRecordFactory();
+ }
+}
Property changes on: trunk/connector-api/src/main/java/org/teiid/resource/spi/WrappedConnectionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connector-api/src/test/java/org/teiid/connector/TestBasicExecutionFactory.java (from rev 2071, trunk/connector-api/src/test/java/org/teiid/connector/TestWrappedConnector.java)
===================================================================
--- trunk/connector-api/src/test/java/org/teiid/connector/TestBasicExecutionFactory.java (rev 0)
+++ trunk/connector-api/src/test/java/org/teiid/connector/TestBasicExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,61 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Properties;
+
+import org.junit.Test;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionFactory;
+
+
+public class TestBasicExecutionFactory {
+
+ @Test public void testConnectorCapabilitiesOverride() throws Exception {
+
+ ExecutionFactory c = new BasicExecutionFactory();
+ //Mockito.stub(c.getCapabilities()).toReturn(new BasicConnectorCapabilities());
+
+ ConnectorCapabilities caps = c.getCapabilities();
+ assertFalse(caps.supportsExistsCriteria());
+ assertFalse(caps.supportsExcept());
+
+
+ c = new BasicExecutionFactory() {
+ @Override
+ public Properties getOverrideCapabilities() {
+ Properties props = new Properties();
+ props.setProperty("supportsExistsCriteria", "true"); //$NON-NLS-1$ //$NON-NLS-2$
+ props.setProperty("supportsExcept", "true"); //$NON-NLS-1$ //$NON-NLS-2$
+ return props;
+ }
+ };
+
+ caps = c.getCapabilities();
+ assertTrue(caps.supportsExistsCriteria());
+ assertTrue(caps.supportsExcept());
+ }
+}
Property changes on: trunk/connector-api/src/test/java/org/teiid/connector/TestBasicExecutionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: trunk/connector-api/src/test/java/org/teiid/connector/TestWrappedConnector.java
===================================================================
--- trunk/connector-api/src/test/java/org/teiid/connector/TestWrappedConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connector-api/src/test/java/org/teiid/connector/TestWrappedConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,71 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.connector;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Properties;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-import org.teiid.connector.basic.WrappedConnector;
-
-
-public class TestWrappedConnector {
-
- @Test public void testConnectorCapabilitiesOverride() throws Exception {
-
- Connector c = Mockito.mock(Connector.class);
- Mockito.stub(c.getCapabilities()).toReturn(new BasicConnectorCapabilities());
- ConnectorEnvironment env = Mockito.mock(ConnectorEnvironment.class);
- Mockito.stub(c.getConnectorEnvironment()).toReturn(env);
-
- WrappedConnector connector = new WrappedConnector(c, null, null);
-
- ConnectorCapabilities caps = connector.getCapabilities();
- assertFalse(caps.supportsExistsCriteria());
- assertFalse(caps.supportsExcept());
-
-
- c = Mockito.mock(Connector.class);
- Mockito.stub(c.getCapabilities()).toReturn(new BasicConnectorCapabilities());
-
- connector = new WrappedConnector(c, null, null);
-
- Properties props = new Properties();
- props.setProperty("supportsExistsCriteria", "true"); //$NON-NLS-1$ //$NON-NLS-2$
- props.setProperty("supportsExcept", "true"); //$NON-NLS-1$ //$NON-NLS-2$
-
- env = Mockito.mock(ConnectorEnvironment.class);
- Mockito.stub(env.getOverrideCapabilities()).toReturn(props);
- Mockito.stub(c.getConnectorEnvironment()).toReturn(env);
-
- caps = connector.getCapabilities();
- assertTrue(caps.supportsExistsCriteria());
- assertTrue(caps.supportsExcept());
- }
-}
Copied: trunk/connector-api/src/test/java/org/teiid/logging/TestLogManager.java (from rev 2083, trunk/engine/src/test/java/com/metamatrix/common/log/TestLogManager.java)
===================================================================
--- trunk/connector-api/src/test/java/org/teiid/logging/TestLogManager.java (rev 0)
+++ trunk/connector-api/src/test/java/org/teiid/logging/TestLogManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,165 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.logging;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.logging.LogListener;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
+import junit.framework.TestCase;
+
+
+/**
+ * This test case tests the LogManager.
+ */
+public class TestLogManager extends TestCase {
+
+ String context = "SomeContext"; //$NON-NLS-1$
+
+ /**
+ * Constructor for TestLogManager.
+ * @param name
+ */
+ public TestLogManager(String name) {
+ super(name);
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ ListLogger logger = new ListLogger();
+ logger.setLogLevel(context, MessageLevel.DETAIL);
+ LogManager.logListener = logger;
+ }
+
+ // =========================================================================
+ // T E S T C A S E S
+ // =========================================================================
+
+ /*
+ * Test for boolean isMessageToBeRecorded(String, int)
+ */
+ public void testIsMessageToBeRecordedString() {
+ assertTrue(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
+
+ ListLogger cfg = (ListLogger)LogManager.logListener;
+ cfg.setLogLevel(context, MessageLevel.NONE);
+ assertFalse(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
+ }
+
+ /**
+ * Test that all msgs logged are equal and output in same order.
+ */
+ public void testLogMessage() throws Exception {
+ ListLogger cfg = (ListLogger)LogManager.logListener;
+ cfg.setLogLevel(context, MessageLevel.INFO );
+
+ List<String> sentMsgList = new ArrayList<String>();
+ sentMsgList.add("A message 1"); //$NON-NLS-1$
+ sentMsgList.add("A message 2"); //$NON-NLS-1$
+ sentMsgList.add("A message 3"); //$NON-NLS-1$
+ sentMsgList.add("A message 4"); //$NON-NLS-1$
+ sentMsgList.add("A message 5"); //$NON-NLS-1$
+ sentMsgList.add("A message 6"); //$NON-NLS-1$
+
+ for (Iterator iter = sentMsgList.iterator(); iter.hasNext();) {
+ String msg = (String) iter.next();
+ LogManager.logInfo(context, msg);
+ }
+
+ List recevedMsgList = cfg.getLoggedMessages();
+ assertEquals(sentMsgList.size(), recevedMsgList.size());
+ assertEquals(sentMsgList, recevedMsgList);
+ }
+
+ /**
+ *
+ * A log listener that saves messages (IStatus)s in a
+ * List for later comparison.
+ */
+ class ListLogger implements LogListener {
+ private List<String> messages = new ArrayList<String>();
+ private Map<String, Integer> contextMap = new HashMap<String, Integer>();
+ private int defaultLevel;
+
+ public ListLogger() {
+ }
+
+ /* (non-Javadoc)
+ * @see com.metamatrix.core.log.LogListener#logMessage(org.eclipse.core.runtime.IStatus, long, java.lang.String, java.lang.String)
+ */
+ public void log(int level, String context, Object msg){
+ this.messages.add(msg.toString());
+ }
+
+ public void log(int level, String context, Throwable t, Object msg) {
+ this.messages.add(msg.toString());
+ }
+
+ /* (non-Javadoc)
+ * @see com.metamatrix.core.log.LogListener#shutdown()
+ */
+ public void shutdown() {
+ messages.clear();
+ messages = null;
+
+ }
+
+ public int size() {
+ return this.messages.size();
+ }
+
+ public List getLoggedMessages() {
+ return this.messages;
+ }
+
+ public Set<String> getContexts() {
+ return this.contextMap.keySet();
+ }
+
+ public int getLogLevel(String context) {
+ Integer level = this.contextMap.get(context);
+ if (level != null) {
+ return level;
+ }
+ return defaultLevel;
+ }
+
+ public void setLogLevel(String context, int logLevel) {
+ this.contextMap.put(context, logLevel);
+ }
+
+ @Override
+ public boolean isEnabled(String context, int msgLevel) {
+ int level = getLogLevel(context);
+ return level >= msgLevel;
+ }
+ }
+
+}
Modified: trunk/connectors/connector-ldap/pom.xml
===================================================================
--- trunk/connectors/connector-ldap/pom.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-ldap/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,15 +1,15 @@
<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.0.0-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>
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-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>
@@ -23,12 +23,17 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>translator-ldap</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>
@@ -51,7 +56,6 @@
<classifier>lib</classifier>
</configuration>
</execution>
-
</executions>
</plugin>
</plugins>
Copied: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap (from rev 2083, trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap)
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/IQueryToLdapSearchParser.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/IQueryToLdapSearchParser.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/IQueryToLdapSearchParser.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,656 +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.
- */
-
-/**
- * Utility class to handle the parsing of an IQuery object into all the relevant LDAP search
- * information. Uses LdapSearchDetails class to store this information and return the search details.
- * This class was intended for use by the execution classes that need to translate SQL. As new capabilities
- * are implemented, this class will be expanded to accommodate the appropriate SQL.
- *
- * This class should remove all the MMX-specific stuff, and turn it into something any
- * LDAP implementation can understand.
- *
- */
-
-package com.metamatrix.connector.ldap;
-
-import java.sql.Timestamp;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-
-import javax.naming.NamingException;
-import javax.naming.directory.BasicAttribute;
-import javax.naming.directory.SearchControls;
-import javax.naming.ldap.SortKey;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.language.AggregateFunction;
-import org.teiid.connector.language.AndOr;
-import org.teiid.connector.language.ColumnReference;
-import org.teiid.connector.language.Comparison;
-import org.teiid.connector.language.Condition;
-import org.teiid.connector.language.DerivedColumn;
-import org.teiid.connector.language.Exists;
-import org.teiid.connector.language.Expression;
-import org.teiid.connector.language.Function;
-import org.teiid.connector.language.In;
-import org.teiid.connector.language.Like;
-import org.teiid.connector.language.Limit;
-import org.teiid.connector.language.Literal;
-import org.teiid.connector.language.NamedTable;
-import org.teiid.connector.language.Not;
-import org.teiid.connector.language.OrderBy;
-import org.teiid.connector.language.ScalarSubquery;
-import org.teiid.connector.language.SearchedCase;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.language.SortSpecification;
-import org.teiid.connector.language.TableReference;
-import org.teiid.connector.language.Comparison.Operator;
-import org.teiid.connector.language.SortSpecification.Ordering;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-import org.teiid.connector.metadata.runtime.Table;
-
-
-/**
- * Utility class which translates a SQL query into an LDAP search.
- */
-public class IQueryToLdapSearchParser {
- private RuntimeMetadata rm;
- private LDAPManagedConnectionFactory config;
-
- /**
- * Constructor.
- * @param logger the connector logger
- * @param rm the RuntimeMetadata
- */
- public IQueryToLdapSearchParser(RuntimeMetadata rm, LDAPManagedConnectionFactory config) {
- this.rm = rm;
- this.config = config;
- }
-
- /**
- * Public entry point to the parser.
- * Parses the IQuery object, and constructs an equivalent LDAP search filter,
- * keeping track of the attributes of interest.
- * Here are some example SQL queries, and the equivalent LDAP search info:
- * SQL: select cn, managerName from people_table where managerName LIKE "John%" and cn!="Mar()"
- * Context name: [people_table's NameInSource, e.g. (ou=people,dc=company,dc=com)]
- * LDAP attributes: (cn, String), (managerName, String)
- * LDAP search filter: (&(managerName="John*")(!(cn="Mar\(\)")))
- *
- * @param query the query
- * @return the LDAPSearchDetails object
- */
- // GHH 20080326 - added ability to restrict queries to only values where
- // objectClass = table name. This is done by adding a third parameter,
- // RESTRICT, to the NameInSource property in the model:
- // ou=people,dc=company,dc=com?SUBTREE_SCOPE?RESTRICT
- // TODO - change method for calling RESTRICT to also specify
- // object class name (RESTRICT=inetOrgPerson)
- public LDAPSearchDetails translateSQLQueryToLDAPSearch(Select query) throws ConnectorException {
- // Parse SELECT symbols.
- // The columns will be translated into LDAP attributes of interest.
- ArrayList attributeList = getAttributesFromSelectSymbols(query);
- ArrayList elementList = getElementsFromSelectSymbols(query);
-
- // Parse FROM table.
- // Only one table is expected here.
- List fromList = query.getFrom();
- Iterator itr = fromList.listIterator();
- if(!itr.hasNext()) {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.noTablesInFromError"); //$NON-NLS-1$
- this.config.getLogger().logError(msg);
- throw new ConnectorException(msg);
- }
- TableReference fItm = (TableReference)itr.next();
- if(itr.hasNext()) {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.multiItemsInFromError"); //$NON-NLS-1$
- this.config.getLogger().logError(msg);
- throw new ConnectorException(msg);
- }
- String contextName = getContextNameFromFromItem(fItm);
- int searchScope = getSearchScopeFromFromItem(fItm);
- // GHH 20080326 - added check for RESTRICT parameter in
- // NameInSource of from item
- String classRestriction = getRestrictToNamedClass(fItm);
-
- // Parse the WHERE clause.
- // Create an equivalent LDAP search filter.
- List searchStringList = new LinkedList();
- searchStringList = getSearchFilterFromWhereClause(query.getWhere(), searchStringList);
- String filter = new String();
- ListIterator filterItr = searchStringList.listIterator();
- while(filterItr.hasNext()) {
- filter += filterItr.next();
- }
- // GHH 20080326 - if there is a class restriction,
- // add it to the search filter
- if (classRestriction != null && classRestriction.trim().length()>0) {
- filter = "(&"+filter+"(objectClass="+classRestriction+"))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- // Parse the ORDER BY clause.
- // Create an ordered sort list.
- OrderBy orderBy = (OrderBy)query.getOrderBy();
- // Referenced the JNDI standard...arguably, this should not be done inside this
- // class, and we should make our own key class. In practice, this makes things simpler.
- SortKey[] sortKeys = getSortKeysFromOrderByClause(orderBy);
-
- // Parse LIMIT clause.
- // Note that offsets are not supported.
- Limit limit = (Limit)query.getLimit();
- long countLimit = -1;
- if(limit != null) {
- countLimit = limit.getRowLimit();
- }
-
- // Create Search Details
- LDAPSearchDetails sd = new LDAPSearchDetails(contextName, searchScope, filter, attributeList, sortKeys, countLimit, elementList);
- // Search Details logging
- try {
- sd.printDetailsToLog(this.config.getLogger());
- } catch (NamingException nme) {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.searchDetailsLoggingError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
-
- return sd;
-
- }
-
- /**
- * get SortKeys from the supplied ORDERBY clause.
- * @param orderBy the OrderBy clause
- * @param the array of SortKeys
- */
- private SortKey[] getSortKeysFromOrderByClause(OrderBy orderBy) throws ConnectorException {
- SortKey[] sortKeys = null;
- if(orderBy != null) {
- List orderItems = orderBy.getSortSpecifications();
- if(orderItems == null) {
- return null;
- }
- SortKey sortKey = null;
- sortKeys = new SortKey[orderItems.size()];
- Iterator orderItr = orderItems.iterator();
- int i = 0;
- while(orderItr.hasNext()) {
- SortSpecification item = (SortSpecification)orderItr.next();
- if(item != null) {
- String itemName = getExpressionString((Expression)item.getExpression());
- this.config.getLogger().logTrace("Adding sort key for item: " + itemName); //$NON-NLS-1$
- if(item.getOrdering() == Ordering.ASC) {
- this.config.getLogger().logTrace("with ASC ordering."); //$NON-NLS-1$
- sortKey = new SortKey(itemName, true, null);
- } else if(item.getOrdering() == Ordering.DESC){
- this.config.getLogger().logTrace("with DESC ordering."); //$NON-NLS-1$
- sortKey = new SortKey(itemName, false, null);
- }
- }
- sortKeys[i] = sortKey;
- i++;
- }
-
- } else {
- // Insert a default? No, allow the Execution to do this. Just return a null list.
- }
- return sortKeys;
- }
-
- /**
- * Utility method to pull the name in source (or, base DN/context name) from the table.
- * @param fromItem
- * @return name in source
- */
- // GHH 20080409 - changed to fall back on new connector property
- // for default base DN if available
- private String getContextNameFromFromItem(TableReference fromItem) throws ConnectorException {
- String nameInSource;
- String contextName;
-
- // TODO: Re-use the getExpressionString method if possible, rather than
- // rewriting the same code twice.
- if(fromItem instanceof NamedTable) {
- Table group = ((NamedTable)fromItem).getMetadataObject();
- nameInSource = group.getNameInSource();
- // if NameInSource is null set it to an empty
- // string instead so we can safely call split on it
- if(nameInSource == null) {
- nameInSource = ""; //$NON-NLS-1$
- }
- // now split it on ? to find the part of it that specifies context name
- String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
- contextName = nameInSourceArray[0];
- // if there is no context name specified
- // try the default in the connector properties
- if(contextName.equals("")) { //$NON-NLS-1$
- contextName = this.config.getSearchDefaultBaseDN();
- }
- } else {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- // if the context name is not specified either in Name in Source
- // or in the default connector properties it'll be either
- // null or an empty string
- if(contextName == null || contextName.equals("")) { //$NON-NLS-1$
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.baseContextNameError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- return contextName;
-
- }
-
- // GHH 20080326 - added below method to check for RESTRICT parameter in
- // from item's NameInSource, and if true return name (not NameInSource)
- // of from item as the objectClass name on to which the query should
- // be restricted
- private String getRestrictToNamedClass(TableReference fromItem) throws ConnectorException {
- String nameInSource;
- String namedClass = null;
- if(fromItem instanceof NamedTable) {
- // Here we use slightly different logic than in
- // getContextNameFromFromItem so it is easier to get
- // the group name later if needed
- Table mdIDGroup = ((NamedTable)fromItem).getMetadataObject();
- nameInSource = mdIDGroup.getNameInSource();
- // groupName = mdIDGroup.getName();
- // if NameInSource is null set it to an empty
- // string instead so we can safely call split on it
- if(nameInSource == null) {
- nameInSource = ""; //$NON-NLS-1$
- }
- // now split it on ? to find the part of it that specifies the objectClass we should restrict on
- String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
- if(nameInSourceArray.length >= 3) {
- namedClass = nameInSourceArray[2];
- }
- // if there is no specification in the Name In Source,
- // see if the connector property is set to true. If
- // it is, use the Name of the class for the restriction.
- if(namedClass == null || namedClass.equals("")) { //$NON-NLS-1$
- if (!this.config.isRestrictToObjectClass()) { //$NON-NLS-1$
- namedClass = ""; //$NON-NLS-1$
- } else {
- namedClass = mdIDGroup.getName();
- }
- }
- } else {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- return namedClass;
- }
-
- private int getSearchScopeFromFromItem(TableReference fromItem) throws ConnectorException {
- String searchScopeString = ""; //$NON-NLS-1$
- int searchScope = LDAPConnectorConstants.ldapDefaultSearchScope;
- // TODO: Re-use the getExpressionString method if possible, rather than
- // rewriting the same code twice.
- if(fromItem instanceof NamedTable) {
- Table group = ((NamedTable)fromItem).getMetadataObject();
- String nameInSource = group.getNameInSource();
- // if NameInSource is null set it to an empty
- // string instead so we can safely call split on it
- if(nameInSource == null) {
- nameInSource = ""; //$NON-NLS-1$
- }
- // now split it on ? to find the part of it that specifies search scope
- String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
- if(nameInSourceArray.length >= 2) {
- searchScopeString = nameInSourceArray[1];
- }
- // if there is no search scope specified
- // try the default in the connector properties
- if(searchScopeString.equals("")) { //$NON-NLS-1$
- searchScopeString = this.config.getSearchDefaultScope();
- // protect against getting null back from the property
- if(searchScopeString == null) {
- searchScopeString = ""; //$NON-NLS-1$
- }
- }
- if(searchScopeString.equals("SUBTREE_SCOPE")) { //$NON-NLS-1$
- searchScope = SearchControls.SUBTREE_SCOPE;
- } else if(searchScopeString.equals("ONELEVEL_SCOPE")) { //$NON-NLS-1$
- searchScope = SearchControls.ONELEVEL_SCOPE;
- } else if(searchScopeString.equals("OBJECT_SCOPE")) { //$NON-NLS-1$
- searchScope = SearchControls.OBJECT_SCOPE;
- }
- } else {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- return searchScope;
- }
-
- /**
- * Utility method to convert operator to the appropriate string value for LDAP.
- * @param op operator to evaluate
- * @return LDAP-specific string equivalent of the operator
- */
- private String parseCompoundCriteriaOp(AndOr.Operator op) throws ConnectorException {
- switch(op) {
- case AND:
- return "&"; //$NON-NLS-1$
- case OR:
- return "|"; //$NON-NLS-1$
- default:
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.criteriaNotParsableError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- }
-
- /**
- * Utility method to convert expression to the appropriate string value for LDAP.
- * @param e expression to evaluate
- * @return LDAP-specific string equivalent of the expression
- */
- // GHH 20080326 - found that code to fall back on Name if NameInSource
- // was null wasn't working properly, so replaced with tried and true
- // code from another custom connector.
- private String getExpressionString(Expression e) throws ConnectorException {
- String expressionName = null;
- // GHH 20080326 - changed around the IElement handling here
- // - the rest of this method is unchanged
- if(e instanceof ColumnReference) {
- Column mdIDElement = ((ColumnReference)e).getMetadataObject();
- expressionName = mdIDElement.getNameInSource();
- if(expressionName == null || expressionName.equals("")) { //$NON-NLS-1$
- expressionName = mdIDElement.getName();
- }
- } else if(e instanceof Literal) {
- try {
- if(((Literal)e).getType().equals(Class.forName(Timestamp.class.getName()))) {
- this.config.getLogger().logTrace("Found an expression that uses timestamp; converting to LDAP string format."); //$NON-NLS-1$
- Timestamp ts = (Timestamp)((Literal)e).getValue();
- Date dt = new Date(ts.getTime());
- //TODO: Fetch format if provided.
- SimpleDateFormat sdf = new SimpleDateFormat(LDAPConnectorConstants.ldapTimestampFormat);
- expressionName = sdf.format(dt);
- this.config.getLogger().logTrace("Timestamp to stsring is: " + expressionName); //$NON-NLS-1$
- }
- else {
- expressionName = ((Literal)e).getValue().toString();
- }
- } catch (ClassNotFoundException cce) {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.timestampClassNotFoundError"); //$NON-NLS-1$
- throw new ConnectorException(cce, msg);
- }
-
- } else {
- if(e instanceof AggregateFunction) {
- this.config.getLogger().logError("Received IAggregate, but it is not supported. Check capabilities."); //$NON-NLS-1$
- } else if(e instanceof Function) {
- this.config.getLogger().logError("Received IFunction, but it is not supported. Check capabilties."); //$NON-NLS-1$
- } else if(e instanceof ScalarSubquery) {
- this.config.getLogger().logError("Received IScalarSubquery, but it is not supported. Check capabilties."); //$NON-NLS-1$
- } else if (e instanceof SearchedCase) {
- this.config.getLogger().logError("Received ISearchedCaseExpression, but it is not supported. Check capabilties."); //$NON-NLS-1$
- }
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.unsupportedElementError"); //$NON-NLS-1$
- throw new ConnectorException(msg + e.toString());
- }
- expressionName = escapeReservedChars(expressionName);
- return expressionName;
- }
-
- private String escapeReservedChars(String expr) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < expr.length(); i++) {
- char curChar = expr.charAt(i);
- switch (curChar) {
- case '\\':
- sb.append("\\5c"); //$NON-NLS-1$
- break;
- case '*':
- sb.append("\\2a"); //$NON-NLS-1$
- break;
- case '(':
- sb.append("\\28"); //$NON-NLS-1$
- break;
- case ')':
- sb.append("\\29"); //$NON-NLS-1$
- break;
- case '\u0000':
- sb.append("\\00"); //$NON-NLS-1$
- break;
- default:
- sb.append(curChar);
- }
- }
- return sb.toString();
- }
-
- /**
- * Recursive method to translate the where clause into an LDAP search filter.
- * The goal is to convert infix notation to prefix (Polish) notation.
- * TODO: There's probably a clever way to do this with a Visitor.
- * @param criteria Criteria to evaluate.
- * @param List list to hold each pre-fix character of the search filter.
- * @return list list that can be traversed in order to construct the search filter.
- */
- private List<String> getSearchFilterFromWhereClause(Condition criteria, List<String> filterList) throws ConnectorException {
- if(criteria == null) {
- filterList.add("(objectClass=*)"); //$NON-NLS-1$
- }
- boolean isNegated = false;
- // Recursive case: compound criteria
- if(criteria instanceof AndOr) {
- AndOr crit = (AndOr)criteria;
- AndOr.Operator op = crit.getOperator();
- this.config.getLogger().logTrace("Parsing compound criteria."); //$NON-NLS-1$
- String stringOp = parseCompoundCriteriaOp(op);
-
- filterList.add("("); //$NON-NLS-1$
- filterList.add(stringOp);
- filterList.addAll(getSearchFilterFromWhereClause(crit.getLeftCondition(), new LinkedList<String>()));
- filterList.addAll(getSearchFilterFromWhereClause(crit.getRightCondition(), new LinkedList<String>()));
- filterList.add(")"); //$NON-NLS-1$
- // Base case
- } else if(criteria instanceof Comparison) {
- this.config.getLogger().logTrace("Parsing compare criteria."); //$NON-NLS-1$
- Comparison.Operator op = ((Comparison) criteria).getOperator();
-
- isNegated = op == Operator.NE || op == Operator.GT || op == Operator.LT;
-
- Expression lhs = ((Comparison) criteria).getLeftExpression();
- Expression rhs = ((Comparison) criteria).getRightExpression();
-
- String lhsString = getExpressionString(lhs);
- String rhsString = getExpressionString(rhs);
- if(lhsString == null || rhsString == null) {
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.missingNISError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
-
- addCompareCriteriaToList(filterList, op, lhsString, rhsString);
- // Base case
- } else if(criteria instanceof Exists) {
- this.config.getLogger().logTrace("Parsing EXISTS criteria: NOT IMPLEMENTED YET"); //$NON-NLS-1$
- // TODO Exists should be supported in a future release.
- // Base case
- } else if(criteria instanceof Like) {
- this.config.getLogger().logTrace("Parsing LIKE criteria."); //$NON-NLS-1$
- isNegated = ((Like) criteria).isNegated();
- // Convert LIKE to Equals, where any "%" symbol is replaced with "*".
- Comparison.Operator op = Operator.EQ;
- Expression lhs = ((Like) criteria).getLeftExpression();
- Expression rhs = ((Like) criteria).getRightExpression();
-
- String lhsString = getExpressionString(lhs);
- String rhsString = getExpressionString(rhs);
- rhsString = rhsString.replace("%", "*"); //$NON-NLS-1$ //$NON-NLS-2$
- addCompareCriteriaToList(filterList, op, lhsString, rhsString);
-
- // Base case
- } else if(criteria instanceof In) {
- this.config.getLogger().logTrace("Parsing IN criteria."); //$NON-NLS-1$
- isNegated = ((In) criteria).isNegated();
- Expression lhs = ((In)criteria).getLeftExpression();
- List rhsList = ((In)criteria).getRightExpressions();
- // Recursively add each IN expression to the filter list.
- processInCriteriaList(filterList, rhsList, lhs);
- } else if (criteria instanceof Not) {
- this.config.getLogger().logTrace("Parsing NOT criteria."); //$NON-NLS-1$
- isNegated = true;
- filterList.addAll(getSearchFilterFromWhereClause(((Not)criteria).getCriteria(), new LinkedList()));
- }
-
- if (isNegated) {
- filterList.add(0, "("); //$NON-NLS-1$
- filterList.add(1, "!"); //$NON-NLS-1$
- filterList.add(")"); //$NON-NLS-1$
- }
-
- return filterList;
- }
-
- /**
- * Process a list of right-hand side IN expresssions and add the corresponding LDAP filter
- * clause string to the given filterList.
- */
- private void processInCriteriaList(List filterList, List rhsList, Expression lhs) throws ConnectorException {
- if(rhsList.size() == 0) {
- return;
- }
- filterList.add("("); //$NON-NLS-1$
- filterList.add(parseCompoundCriteriaOp(org.teiid.connector.language.AndOr.Operator.OR));
- Iterator rhsItr = rhsList.iterator();
- while(rhsItr.hasNext()) {
- addCompareCriteriaToList(filterList, Operator.EQ, getExpressionString(lhs),
- getExpressionString((Expression)rhsItr.next()));
- }
- filterList.add(")"); //$NON-NLS-1$
- }
-
- /**
- * Add Compare Criteria to List
- * @param filterList the filter list
- * @param op
- * @param lhs left hand side expression
- * @param rhs right hand side expression
- */
- private void addCompareCriteriaToList(List filterList, Comparison.Operator op, String lhs, String rhs) throws ConnectorException {
- // Push the comparison statement into the list, e.g.:
- // (sn=Mike)
- // !(empNum>=100)
- filterList.add("("); //$NON-NLS-1$
- filterList.add(lhs);
-
- switch(op) {
- case NE:
- case EQ:
- filterList.add("="); //$NON-NLS-1$
- break;
- case LT:
- case GE:
- filterList.add(">="); //$NON-NLS-1$
- break;
- case GT:
- case LE:
- filterList.add("<="); //$NON-NLS-1$
- break;
- default:
- final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.criteriaNotSupportedError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
-
- }
- filterList.add(rhs);
- filterList.add(")"); //$NON-NLS-1$
- }
-
- /**
- * Method to get name from the supplied Element
- * @param e the supplied Element
- * @return the name
- */
- // GHH 20080326 - found that code to fall back on Name if NameInSource
- // was null wasn't working properly, so replaced with tried and true
- // code from another custom connector.
- public String getNameFromElement(Column e) throws ConnectorException {
- String ldapAttributeName = null;
- ldapAttributeName = e.getNameInSource();
- if (ldapAttributeName == null || ldapAttributeName.equals("")) { //$NON-NLS-1$
- ldapAttributeName = e.getName();
- // If name in source is not set, then fall back to the column name.
- }
- return ldapAttributeName;
- }
-
- /**
- * Method to get SELECT Element list from the supplied query
- * @param query the supplied Query
- * @return the list of SELECT elements
- */
- private ArrayList getElementsFromSelectSymbols(Select query) throws ConnectorException {
- ArrayList selectElementList = new ArrayList();
- Iterator selectSymbolItr = query.getDerivedColumns().iterator();
-
- while(selectSymbolItr.hasNext()) {
- Column e = getElementFromSymbol((DerivedColumn)selectSymbolItr.next());
- selectElementList.add(e);
- }
- return selectElementList;
- }
-
- /**
- * Method to get attribute list from the supplied query
- * @param query the supplied Query
- * @return the list of attributes
- */
- private ArrayList getAttributesFromSelectSymbols(Select query) throws ConnectorException {
- ArrayList ldapAttributeList = new ArrayList();
-
- Iterator selectSymbolItr = query.getDerivedColumns().iterator();
- int i=0;
- while(selectSymbolItr.hasNext()) {
- Column e = getElementFromSymbol((DerivedColumn)selectSymbolItr.next());
- String ldapAttributeName = this.getNameFromElement(e);
- Object ldapAttributeClass = e.getJavaType();
-
- // Store the element's name and class type, so that we know what to look for in the search results.
- BasicAttribute newAttr = new BasicAttribute(ldapAttributeName, ldapAttributeClass);
- ldapAttributeList.add(newAttr);
- i++;
- }
- return ldapAttributeList;
- }
-
- /**
- * Helper method for getting runtime {@link org.teiid.connector.metadata.runtime.Element} from a
- * {@link org.teiid.connector.language.DerivedColumn}.
- * @param symbol Input ISelectSymbol
- * @return Element returned metadata runtime Element
- */
- private Column getElementFromSymbol(DerivedColumn symbol) throws ConnectorException {
- ColumnReference expr = (ColumnReference) symbol.getExpression();
- return expr.getMetadataObject();
- }
-
-
-}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnection.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPConnection.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,206 +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 com.metamatrix.connector.ldap;
-
-import java.util.Hashtable;
-import java.util.Properties;
-
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.ldap.InitialLdapContext;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-
-/**
- * Represents a connection to an LDAP data source.
- */
-public class LDAPConnection extends BasicConnection {
-
- private LDAPManagedConnectionFactory config;
-
- // Standard Connection data members
- private InitialLdapContext initCtx;
-
- // LDAP-specific properties
- public static final String LDAP_AUTH_TYPE = "simple"; //$NON-NLS-1$
- public static final String LDAP_USER_OBJECT_TYPE = "person"; //$NON-NLS-1$
- public static final String LDAP_REFERRAL_MODE = "follow"; //$NON-NLS-1$
-
- private String jndiLdapCtxFactory;
-
- public LDAPConnection(LDAPManagedConnectionFactory config) throws ConnectorException {
- this(config, LDAPConnectorConstants.JNDI_LDAP_CTX_FACTORY);
- }
-
- public LDAPConnection(LDAPManagedConnectionFactory config, String jndiLdapCtxFactory) throws ConnectorException {
- this.config = config;
- this.jndiLdapCtxFactory = jndiLdapCtxFactory;
-
- checkProperties();
-
- // Create initial LDAP connection.
- try {
- this.initCtx = initializeLDAPContext();
- } catch(ConnectorException ce) {
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.contextInitFailed"); //$NON-NLS-1$
- throw new ConnectorException(ce, msg);
- }
-
- this.config.getLogger().logDetail("LDAP Connection has been newly created."); //$NON-NLS-1$
- }
-
- public void setJndiLdapCtxFactory(String jndiLdapCtxFactory) {
- this.jndiLdapCtxFactory = jndiLdapCtxFactory;
- }
-
- /**
- * Helper method to retrieve the LDAP Connector properties. If any properties are in error,
- * a ConnectorException is thrown.
- * @param props
- */
- private void checkProperties() throws ConnectorException {
- // LDAP URL
- if(this.config.getLdapUrl() == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.urlPropNotFound"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- // LDAP Admin User DN
- if(this.config.getLdapAdminUserDN() == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.adminUserDNPropNotFound"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- // LDAP Admin User Password
- if(this.config.getLdapAdminUserPassword() == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.adminUserPassPropNotFound"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- }
-
- /**
- * Setup a standard initial LDAP context using JNDI's context factory.
- * This method may be extended to support Sun-specific and AD-specific
- * contexts, in order to support the different paging implementations they provide.
- * @return the initial LDAP Context
- */
- private InitialLdapContext initializeLDAPContext() throws ConnectorException {
- // Create the root context.
- InitialLdapContext initContext;
-
- Hashtable connenv = new Hashtable();
- connenv.put(Context.INITIAL_CONTEXT_FACTORY, jndiLdapCtxFactory);
- connenv.put(Context.PROVIDER_URL, this.config.getLdapUrl());
- connenv.put(Context.REFERRAL, LDAP_REFERRAL_MODE);
- // If username is blank, we will perform an anonymous bind.
- // Note: This is not supported when using Sun's VLVs, so remove this if VLVs are used.
- if(!this.config.getLdapAdminUserDN().equals("")) { //$NON-NLS-1$
-
- connenv.put(Context.SECURITY_AUTHENTICATION, LDAP_AUTH_TYPE);
- connenv.put(Context.SECURITY_PRINCIPAL, this.config.getLdapAdminUserDN());
- connenv.put(Context.SECURITY_CREDENTIALS, this.config.getLdapAdminUserPassword());
- } else {
- this.config.getLogger().logWarning("LDAP Username DN was blank; performing anonymous bind."); //$NON-NLS-1$
- connenv.put(Context.SECURITY_AUTHENTICATION, "none"); //$NON-NLS-1$
- }
-
- if(this.config.getLdapTxnTimeoutInMillis() != -1) { //$NON-NLS-1$
- connenv.put("com.sun.jndi.ldap.connect.timeout", this.config.getLdapTxnTimeoutInMillis()); //$NON-NLS-1$
- }
-
- // Enable connection pooling for the Initial context.
- connenv.put("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
- connenv.put("com.sun.jndi.ldap.connect.pool.debug", "fine"); //$NON-NLS-1$ //$NON-NLS-2$
-
- try {
- initContext = new InitialLdapContext(connenv, null);
- } catch(NamingException ne){
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.directoryNamingError",ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg);
- } catch(Exception e) {
- final String msg = LDAPPlugin.Util.getString("LDAPConnection.directoryInitError"); //$NON-NLS-1$
- throw new ConnectorException(e, msg);
- }
- this.config.getLogger().logDetail("Successfully obtained initial LDAP context."); //$NON-NLS-1$
- return initContext;
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new LDAPSyncQueryExecution((Select)command, executionContext, metadata, this.initCtx, this.config);
- }
-
- @Override
- public UpdateExecution createUpdateExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new LDAPUpdateExecution(command, executionContext, metadata, this.initCtx, this.config);
- }
-
- /**
- * Closes LDAP context, effectively closing the connection to LDAP.
- * (non-Javadoc)
- * @see com.metamatrix.connector.pool.PoolAwareConnection#closeSource()
- */
- @Override
- public void close() {
- if(initCtx != null) {
- try {
- initCtx.close();
- } catch(NamingException e) {
- this.config.getLogger().logDetail(LDAPPlugin.Util.getString("LDAPConnection.contextCloseError",e.getExplanation())); //$NON-NLS-1$
- }
- }
- this.config.getLogger().logDetail("LDAP context has been closed."); //$NON-NLS-1$
- }
-
- /**
- * Currently, this method always returns alive. We assume the connection is alive,
- * and rely on proper timeout values to automatically clean up connections before
- * any server-side timeout occurs. Rather than incur overhead by rebinding,
- * we'll assume the connection is always alive, and throw an error when it is actually used,
- * if the connection fails. This may be a more efficient way of handling failed connections,
- * with the one tradeoff that stale connections will not be detected until execution time. In
- * practice, there is no benefit to detecting stale connections before execution time.
- *
- * One possible extension is to implement a UnsolicitedNotificationListener.
- * (non-Javadoc)
- * @see com.metamatrix.connector.pool.PoolAwareConnection#isAlive()
- */
- @Override
- public boolean isAlive() {
- this.config.getLogger().logTrace("LDAP Connection is alive."); //$NON-NLS-1$
- return true;
- }
-
-}
Added: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectionImpl.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectionImpl.java (rev 0)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,181 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.resource.cci.ldap;
+
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.ldap.InitialLdapContext;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.ldap.LDAPConnection;
+import org.teiid.resource.spi.BasicConnection;
+
+
+
+/**
+ * Represents a connection to an LDAP data source.
+ */
+public class LDAPConnectionImpl extends BasicConnection implements LDAPConnection {
+
+ private LDAPManagedConnectionFactory config;
+
+ // Standard Connection data members
+ private InitialLdapContext initCtx;
+
+ // LDAP-specific properties
+ public static final String LDAP_AUTH_TYPE = "simple"; //$NON-NLS-1$
+ public static final String LDAP_USER_OBJECT_TYPE = "person"; //$NON-NLS-1$
+ public static final String LDAP_REFERRAL_MODE = "follow"; //$NON-NLS-1$
+
+ public LDAPConnectionImpl(LDAPManagedConnectionFactory config) throws ConnectorException {
+ this.config = config;
+
+ checkProperties();
+
+ // Create initial LDAP connection.
+ try {
+ this.initCtx = initializeLDAPContext();
+ } catch(ConnectorException ce) {
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.contextInitFailed"); //$NON-NLS-1$
+ throw new ConnectorException(ce, msg);
+ }
+
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "LDAP Connection has been newly created."); //$NON-NLS-1$
+ }
+
+ /**
+ * Helper method to retrieve the LDAP Connector properties. If any properties are in error,
+ * a ConnectorException is thrown.
+ * @param props
+ */
+ private void checkProperties() throws ConnectorException {
+ // LDAP URL
+ if(this.config.getLdapUrl() == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.urlPropNotFound"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ // LDAP Admin User DN
+ if(this.config.getLdapAdminUserDN() == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.adminUserDNPropNotFound"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ // LDAP Admin User Password
+ if(this.config.getLdapAdminUserPassword() == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.adminUserPassPropNotFound"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ }
+
+ /**
+ * Setup a standard initial LDAP context using JNDI's context factory.
+ * This method may be extended to support Sun-specific and AD-specific
+ * contexts, in order to support the different paging implementations they provide.
+ * @return the initial LDAP Context
+ */
+ private InitialLdapContext initializeLDAPContext() throws ConnectorException {
+ // Create the root context.
+ InitialLdapContext initContext;
+
+ Hashtable connenv = new Hashtable();
+ connenv.put(Context.INITIAL_CONTEXT_FACTORY, this.config.getLdapContextFactory());
+ connenv.put(Context.PROVIDER_URL, this.config.getLdapUrl());
+ connenv.put(Context.REFERRAL, LDAP_REFERRAL_MODE);
+ // If username is blank, we will perform an anonymous bind.
+ // Note: This is not supported when using Sun's VLVs, so remove this if VLVs are used.
+ if(!this.config.getLdapAdminUserDN().equals("")) { //$NON-NLS-1$
+
+ connenv.put(Context.SECURITY_AUTHENTICATION, LDAP_AUTH_TYPE);
+ connenv.put(Context.SECURITY_PRINCIPAL, this.config.getLdapAdminUserDN());
+ connenv.put(Context.SECURITY_CREDENTIALS, this.config.getLdapAdminUserPassword());
+ } else {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "LDAP Username DN was blank; performing anonymous bind."); //$NON-NLS-1$
+ connenv.put(Context.SECURITY_AUTHENTICATION, "none"); //$NON-NLS-1$
+ }
+
+ if(this.config.getLdapTxnTimeoutInMillis() != -1) {
+ connenv.put("com.sun.jndi.ldap.connect.timeout", this.config.getLdapTxnTimeoutInMillis()); //$NON-NLS-1$
+ }
+
+ // Enable connection pooling for the Initial context.
+ connenv.put("com.sun.jndi.ldap.connect.pool", "true"); //$NON-NLS-1$ //$NON-NLS-2$
+ connenv.put("com.sun.jndi.ldap.connect.pool.debug", "fine"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ try {
+ initContext = new InitialLdapContext(connenv, null);
+ } catch(NamingException ne){
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.directoryNamingError",ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ } catch(Exception e) {
+ final String msg = LDAPPlugin.Util.getString("LDAPConnection.directoryInitError"); //$NON-NLS-1$
+ throw new ConnectorException(e, msg);
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Successfully obtained initial LDAP context."); //$NON-NLS-1$
+ return initContext;
+ }
+
+
+
+ /**
+ * Closes LDAP context, effectively closing the connection to LDAP.
+ * (non-Javadoc)
+ * @see com.metamatrix.connector.pool.PoolAwareConnection#closeSource()
+ */
+ @Override
+ public void close() {
+ if(initCtx != null) {
+ try {
+ initCtx.close();
+ } catch(NamingException e) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, LDAPPlugin.Util.getString("LDAPConnection.contextCloseError",e.getExplanation())); //$NON-NLS-1$
+ }
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"LDAP context has been closed."); //$NON-NLS-1$
+ }
+
+ /**
+ * Currently, this method always returns alive. We assume the connection is alive,
+ * and rely on proper timeout values to automatically clean up connections before
+ * any server-side timeout occurs. Rather than incur overhead by rebinding,
+ * we'll assume the connection is always alive, and throw an error when it is actually used,
+ * if the connection fails. This may be a more efficient way of handling failed connections,
+ * with the one tradeoff that stale connections will not be detected until execution time. In
+ * practice, there is no benefit to detecting stale connections before execution time.
+ *
+ * One possible extension is to implement a UnsolicitedNotificationListener.
+ * (non-Javadoc)
+ * @see com.metamatrix.connector.pool.PoolAwareConnection#isAlive()
+ */
+ public boolean isAlive() {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "LDAP Connection is alive."); //$NON-NLS-1$
+ return true;
+ }
+
+ @Override
+ public Object lookup(String context) throws NamingException {
+ return this.initCtx.lookup(context);
+ }
+}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnector.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPConnector.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,52 +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 com.metamatrix.connector.ldap;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.basic.BasicConnector;
-
-
-/**
- * LDAPConnector. This is responsible for initializing
- * a connection factory, and obtaining connections to LDAP.
- */
-public class LDAPConnector extends BasicConnector {
- private LDAPManagedConnectionFactory config;
-
- public Connection getConnection() throws ConnectorException {
- config.getLogger().logDetail(LDAPPlugin.Util.getString("LDAPSourceConnectionFactory.creatingConnection"));
- return new LDAPConnection(this.config);
- }
-
- @Override
- public void initialize(ConnectorEnvironment env) throws ConnectorException {
- super.initialize(env);
- this.config = (LDAPManagedConnectionFactory)env;
- }
-
- public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
- return LDAPConnectorCapabilities.class;
- }
-}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorCapabilities.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPConnectorCapabilities.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,82 +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 com.metamatrix.connector.ldap;
-
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-
-/**
- * This class extends the BasicConnectorCapabilities class, and establishes
- * the capabilities that are supported by the LDAPConnector.
- */
-public class LDAPConnectorCapabilities extends BasicConnectorCapabilities {
-
- @Override
- public int getMaxInCriteriaSize() {
- return 1000;
- }
-
- public boolean supportsCompareCriteriaEquals() {
- return true;
- }
-
- public boolean supportsInCriteria() {
- return true;
- }
-
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- public boolean supportsOrCriteria() {
- return true;
- }
-
- public boolean supportsOrderBy() {
- // Removed this support -- see LDAPSyncQueryExecution comments for details.
- return false;
- }
-
- public boolean supportsRowLimit() {
- // GHH 20080408 - turned this on, because I fixed issue
- // in nextBatch that was causing this to fail
- return true;
- }
-
- public boolean supportsRowOffset() {
- // TODO This might actually be possible in future releases,
- // when using virtual list views/Sun. note that this requires the ability
- // to set the count limit, as well as an offset, so setCountLimit::searchControls
- // won't do it alone.
- return false;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return true;
- }
-
- @Override
- public boolean supportsNotCriteria() {
- return true;
- }
-
-}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorConstants.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPConnectorConstants.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPConnectorConstants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,41 +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 com.metamatrix.connector.ldap;
-
-import javax.naming.directory.*;
-
-/**
- * Utility class to maintain list of constants for the LDAPConnector.
- * Please modify constants here; changes should be reflected throughout
- * the connector code.
- */
-public class LDAPConnectorConstants {
-
- public static final String ldapDefaultSortName = "guid"; //$NON-NLS-1$
- public static final int ldapDefaultSearchScope = SearchControls.ONELEVEL_SCOPE;
- public static final boolean ldapDefaultIsAscending = true;
-
- public static final String JNDI_LDAP_CTX_FACTORY =
- "com.sun.jndi.ldap.LdapCtxFactory"; //$NON-NLS-1$
-
- public static final String ldapTimestampFormat = "yyyyMMddhhmmss\'Z\'"; //$NON-NLS-1$
-}
Modified: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPManagedConnectionFactory.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -19,29 +19,34 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
-package com.metamatrix.connector.ldap;
+package org.teiid.resource.cci.ldap;
-import org.teiid.connector.basic.BasicManagedConnectionFactory;
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
public class LDAPManagedConnectionFactory extends BasicManagedConnectionFactory {
private static final long serialVersionUID = -1832915223199053471L;
- private String searchDefaultBaseDN;
private String ldapAdminUserDN;
private String ldapAdminUserPassword;
- private boolean restrictToObjectClass = false;
- private long ldapTxnTimeoutInMillis;
private String ldapUrl;
- private String searchDefaultScope = "SUBTREE_SCOPE";
+ private long ldapTxnTimeoutInMillis;
+ private String ldapContextFactory;
- public String getSearchDefaultBaseDN() {
- return searchDefaultBaseDN;
- }
- public void setSearchDefaultBaseDN(String searchDefaultBaseDN) {
- this.searchDefaultBaseDN = searchDefaultBaseDN;
- }
+ @Override
+ public Object createConnectionFactory() throws ResourceException {
+ return new BasicConnectionFactory() {
+ @Override
+ public Connection getConnection() throws ResourceException {
+ return new LDAPConnectionImpl(LDAPManagedConnectionFactory.this);
+ }
+ };
+ }
public String getLdapAdminUserDN() {
return ldapAdminUserDN;
@@ -59,14 +64,6 @@
this.ldapAdminUserPassword = ldapAdminUserPassword;
}
- public boolean isRestrictToObjectClass() {
- return restrictToObjectClass;
- }
-
- public void setRestrictToObjectClass(Boolean restrictToObjectClass) {
- this.restrictToObjectClass = restrictToObjectClass.booleanValue();
- }
-
public long getLdapTxnTimeoutInMillis() {
return ldapTxnTimeoutInMillis;
}
@@ -83,11 +80,11 @@
this.ldapUrl = ldapUrl;
}
- public String getSearchDefaultScope() {
- return searchDefaultScope;
+ public String getLdapContextFactory() {
+ return ldapContextFactory;
}
-
- public void setSearchDefaultScope(String searchDefaultScope) {
- this.searchDefaultScope = searchDefaultScope;
- }
+
+ public void setLdapContextFactory(String ldapContextFactory) {
+ this.ldapContextFactory = ldapContextFactory;
+ }
}
Modified: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPPlugin.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPPlugin.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -19,7 +19,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
-package com.metamatrix.connector.ldap;
+package org.teiid.resource.cci.ldap;
import java.util.ResourceBundle;
@@ -30,11 +30,7 @@
*/
public class LDAPPlugin {
- /**
- * The plug-in identifier of this plugin
- * (value <code>"com.metamatrix.connector.ldap"</code>).
- */
- public static final String PLUGIN_ID = "com.metamatrix.connector.ldap" ; //$NON-NLS-1$
+ public static final String PLUGIN_ID = "org.teiid.resource.cci.ldap" ; //$NON-NLS-1$
/**
* Provides access to the plugin's log and to it's resources.
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSearchDetails.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPSearchDetails.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSearchDetails.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,191 +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 com.metamatrix.connector.ldap;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.SearchControls;
-import javax.naming.ldap.SortKey;
-
-import org.teiid.connector.api.ConnectorLogger;
-
-
-/**
- * Utility class used to maintain the details of a particular LDAP search,
- * such as the context, the attributes of interest, the filter, and the
- * search scope.
- */
-public class LDAPSearchDetails {
- private String contextName;
- private int searchScope;
- private String contextFilter;
- private ArrayList attributeList;
- private SortKey[] keys;
-// private LdapSortKey[] netscapeKeys;
- // If limit is set to -1, this means no limit (return all rows)
- private long limit;
- private ArrayList elementList;
-
- /**
- * Constructor
- * @param name the context name
- * @param searchScope the search scope
- * @param filter the context filter
- * @param attributeList the list of attributes
- * @param keys
- * @param limit
- * @param elementList
- */
- public LDAPSearchDetails(String name, int searchScope, String filter, ArrayList attributeList, SortKey[] keys, long limit, ArrayList elementList) {
-
- this.contextName = name;
- this.searchScope = searchScope;
- this.contextFilter = filter;
- this.attributeList = attributeList;
- this.keys = keys;
- this.limit = limit;
- this.elementList = elementList;
- }
-
- /**
- * get the context name
- * @return the context name
- */
- public String getContextName() {
- return contextName;
- }
-
- /**
- * get the context name
- * @return the context name
- */
- public int getSearchScope() {
- return searchScope;
- }
-
- /**
- * get the context filter
- * @return the context filter
- */
- public String getContextFilter() {
- return contextFilter;
- }
-
- /**
- * get the attribute list
- * @return the attribute list
- */
- public ArrayList getAttributeList() {
- return attributeList;
- }
-
- /**
- * get the element list
- * @return the element list
- */
- public ArrayList getElementList() {
- return elementList;
- }
-
- /**
- * get the sort keys
- * @return the sort keys
- */
- public SortKey[] getSortKeys() {
- return keys;
- }
-
- /**
- * get the count limit
- * @return the count limit
- */
- public long getCountLimit() {
- return limit;
- }
- /*
- public LdapSortKey[] getNetscapeSortKeys() {
- return netscapeKeys;
- }
- private void createNetscapeKeys() {
- if(keys != null) {
- netscapeKeys = new LdapSortKey[keys.length];
- for(int i=0; i<keys.length; i++) {
- LdapSortKey nKey = new LdapSortKey(keys[i].getAttributeID(),
- keys[i].isAscending());
- netscapeKeys[i] = nKey;
- }
- } else {
- // set it null
- netscapeKeys = null;
- }
- }
- */
-
- /**
- * Print Method for Logging - (Detail level logging)
- * @param logger the connector logger.
- */
- public void printDetailsToLog(ConnectorLogger logger) throws NamingException {
- // Log Search Scope
- logger.logDetail("Search context: " + contextName); //$NON-NLS-1$
- if(searchScope == SearchControls.SUBTREE_SCOPE) {
- logger.logDetail("Search scope = SUBTREE_SCOPE"); //$NON-NLS-1$
- } else if(searchScope == SearchControls.OBJECT_SCOPE) {
- logger.logDetail("Search scope = OBJECT_SCOPE"); //$NON-NLS-1$
- } else if(searchScope == SearchControls.ONELEVEL_SCOPE) {
- logger.logDetail("Search scope = ONELEVEL_SCOPE"); //$NON-NLS-1$
- }
-
- // Log Search Attributes
- logger.logDetail("Search attributes: "); //$NON-NLS-1$
- Iterator itr = this.attributeList.iterator();
- int i = 0;
- while(itr.hasNext()) {
- Attribute attr = (Attribute)itr.next();
- logger.logDetail("Attribute [" + i + "]: " + attr.getID() + " (" +attr.get().toString() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- i++;
- }
-
- // Log Context Filter
- if(contextFilter != null && (!contextFilter.equals(""))) { //$NON-NLS-1$
- logger.logDetail("Where clause was translated into Ldap search filter: " + contextFilter); //$NON-NLS-1$
- }
-
- // Log Sort Keys
- if(keys != null) {
- logger.logDetail("Sort keys: "); //$NON-NLS-1$
- for(int j=0; j<keys.length; j++) {
- logger.logDetail("\tName: " + keys[j].getAttributeID()); //$NON-NLS-1$
- logger.logDetail("\tOrder: "); //$NON-NLS-1$
- if(keys[j].isAscending()) {
- logger.logDetail("ASC"); //$NON-NLS-1$
- } else {
- logger.logDetail("DESC"); //$NON-NLS-1$
- }
- }
- }
- }
-}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSyncQueryExecution.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPSyncQueryExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPSyncQueryExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,489 +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.
- */
-
-/**
- *
- * Please see the user's guide for a full description of capabilties, etc.
- *
- * Description/Assumptions:
- * 1. Table's name in source defines the base DN (or context) for the search.
- * Example: Table.NameInSource=ou=people,dc=gene,dc=com
- * [Optional] The table's name in source can also define a search scope. Append
- * a "?" character as a delimiter to the base DN, and add the search scope string.
- * The following scopes are available:
- * SUBTREE_SCOPE
- * ONELEVEL_SCOPE
- * OBJECT_SCOPE
- * [Default] LDAPConnectorConstants.ldapDefaultSearchScope
- * is the default scope used, if no scope is defined (currently, ONELEVEL_SCOPE).
- *
- * 2. Column's name in source defines the LDAP attribute name.
- * [Default] If no name in source is defined, then we attempt to use the column name
- * as the LDAP attribute name.
- *
- *
- * TODO: Implement paged searches -- the LDAP server must support VirtualListViews.
- * TODO: Implement cancel.
- * TODO: Add Sun/Netscape implementation, AD/OpenLDAP implementation.
- *
- *
- * Note:
- * Greater than is treated as >=
- * Less-than is treater as <=
- * If an LDAP entry has more than one entry for an attribute of interest (e.g. a select item), we only return the
- * first occurrance. The first occurance is not predictably the same each time, either, according to the LDAP spec.
- * If an attribute is not present, we return the empty string. Arguably, we could throw an exception.
- *
- * Sun LDAP won't support Sort Orders for very large datasets. So, we've set the sorting to NONCRITICAL, which
- * allows Sun to ignore the sort order. This will result in the results to come back as unsorted, without any error.
- *
- * Removed support for ORDER BY for two reasons:
- * 1: LDAP appears to have a limit to the number of records that
- * can be server-side sorted. When the limit is reached, two things can happen:
- * a. If sortControl is set to CRITICAL, then the search fails.
- * b. If sortControl is NONCRITICAL, then the search returns, unsorted.
- * We'd like to support ORDER BY, no matter how large the size, so we turn it off,
- * and allow MetaMatrix to do it for us.
- * 2: Supporting ORDER BY appears to negatively effect the query plan
- * when cost analysis is used. We stop using dependent queries, and start
- * using inner joins.
- *
- */
-
-package com.metamatrix.connector.ldap;
-
-import java.io.IOException;
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.SizeLimitExceededException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import javax.naming.ldap.Control;
-import javax.naming.ldap.InitialLdapContext;
-import javax.naming.ldap.LdapContext;
-import javax.naming.ldap.SortControl;
-import javax.naming.ldap.SortKey;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-
-/**
- * LDAPSyncQueryExecution is responsible for executing an LDAP search
- * corresponding to a read-only "select" query from MetaMatrix.
- */
-public class LDAPSyncQueryExecution extends BasicExecution implements ResultSetExecution {
-
- private LDAPSearchDetails searchDetails;
- private RuntimeMetadata rm;
- private InitialLdapContext initialLdapContext;
- private LdapContext ldapCtx;
- private NamingEnumeration searchEnumeration;
- private IQueryToLdapSearchParser parser;
- private Select query;
- private LDAPManagedConnectionFactory config;
-
- /**
- * Constructor
- * @param executionMode the execution mode.
- * @param ctx the execution context.
- * @param rm the runtimeMetadata
- * @param logger the ConnectorLogger
- * @param ldapCtx the LDAP Context
- */
- public LDAPSyncQueryExecution(Select query, ExecutionContext ctx, RuntimeMetadata rm, InitialLdapContext ldapCtx, LDAPManagedConnectionFactory config) throws ConnectorException {
- this.rm = rm;
- this.initialLdapContext = ldapCtx;
- this.query = query;
- this.config = config;
- }
-
- /**
- * method to execute the supplied query
- * @param query the query object.
- * @param maxBatchSize the max batch size.
- */
- @Override
- public void execute() throws ConnectorException {
- // Parse the IQuery, and translate it into an appropriate LDAP search.
- this.parser = new IQueryToLdapSearchParser(this.rm, this.config);
- searchDetails = parser.translateSQLQueryToLDAPSearch(query);
-
- // Create and configure the new search context.
- createSearchContext();
- SearchControls ctrls = setSearchControls();
- setStandardRequestControls();
- // Execute the search.
- executeSearch(ctrls);
- }
-
- /**
- * Set the standard request controls
- */
- private void setStandardRequestControls() throws ConnectorException {
- Control[] sortCtrl = new Control[1];
- SortKey[] keys = searchDetails.getSortKeys();
- if (keys != null) {
- try {
- sortCtrl[0] = new SortControl(keys, Control.NONCRITICAL);
- this.ldapCtx.setRequestControls(sortCtrl);
- this.config.getLogger().logTrace("Sort ordering was requested, and sort control was created successfully."); //$NON-NLS-1$
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError") + //$NON-NLS-1$
- " : "+ne.getExplanation(); //$NON-NLS-1$
- throw new ConnectorException(msg);
- } catch(IOException e) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError"); //$NON-NLS-1$
- throw new ConnectorException(e,msg);
- }
- }
- }
-
- /**
- * Perform a lookup against the initial LDAP context, which
- * sets the context to something appropriate for the search that is about to occur.
- *
- */
- private void createSearchContext() throws ConnectorException {
- try {
- ldapCtx = (LdapContext) this.initialLdapContext.lookup(searchDetails.getContextName());
- } catch (NamingException ne) {
- if (searchDetails.getContextName() != null) {
- this.config.getLogger().logError("Attempted to search context: " //$NON-NLS-1$
- + searchDetails.getContextName());
- }
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.createContextError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- }
-
-
- /**
- * Set the search controls
- */
- private SearchControls setSearchControls() throws ConnectorException {
- SearchControls ctrls = new SearchControls();
- //ArrayList modelAttrList = searchDetails.getAttributeList();
- ArrayList modelAttrList = searchDetails.getElementList();
- String[] attrs = new String[modelAttrList.size()];
- Iterator itr = modelAttrList.iterator();
- int i = 0;
- while(itr.hasNext()) {
- attrs[i] = (parser.getNameFromElement((Column)itr.next()));
- //attrs[i] = (((Attribute)itr.next()).getID();
- //logger.logTrace("Adding attribute named " + attrs[i] + " to the search list.");
- i++;
- }
-
- ctrls.setSearchScope(searchDetails.getSearchScope());
- ctrls.setReturningAttributes(attrs);
-
- long limit = searchDetails.getCountLimit();
- if(limit != -1) {
- ctrls.setCountLimit(limit);
- }
- return ctrls;
- }
-
- /**
- * Perform the LDAP search against the subcontext, using the filter and
- * search controls appropriate to the query and model metadata.
- */
- private void executeSearch(SearchControls ctrls) throws ConnectorException {
- String ctxName = searchDetails.getContextName();
- String filter = searchDetails.getContextFilter();
- if (ctxName == null || filter == null || ctrls == null) {
- this.config.getLogger().logError("Search context, filter, or controls were null. Cannot execute search."); //$NON-NLS-1$
- }
- try {
- searchEnumeration = this.ldapCtx.search("", filter, ctrls); //$NON-NLS-1$
- } catch (NamingException ne) {
- this.config.getLogger().logError("LDAP search failed. Attempted to search context " //$NON-NLS-1$
- + ctxName + " using filter " + filter); //$NON-NLS-1$
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
- throw new ConnectorException(msg + " : " + ne.getExplanation()); //$NON-NLS-1$
- } catch(Exception e) {
- this.config.getLogger().logError("LDAP search failed. Attempted to search context " //$NON-NLS-1$
- + ctxName + " using filter " + filter); //$NON-NLS-1$
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
- throw new ConnectorException(e, msg);
- }
- }
-
- // GHH 20080326 - attempt to implement cancel here. First try to
- // close the searchEnumeration, then the search context.
- // We are very conservative when closing the enumeration
- // but less so when closing context, since it is safe to call close
- // on contexts multiple times
- @Override
- public void cancel() throws ConnectorException {
- close();
- }
-
- // GHH 20080326 - replaced existing implementation with the same
- // code as used by cancel method. First try to
- // close the searchEnumeration, then the search context
- // We are very conservative when closing the enumeration
- // but less so when closing context, since it is safe to call close
- // on contexts multiple times
- @Override
- public void close() throws ConnectorException {
- if (searchEnumeration != null) {
- try {
- searchEnumeration.close();
- } catch (Exception e) { } // catch everything, because NamingEnumeration has undefined behavior if it previously hit an exception
- }
- if (ldapCtx != null) {
- try {
- ldapCtx.close();
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.closeContextError",ne.getExplanation()); //$NON-NLS-1$
- this.config.getLogger().logError(msg);
- }
- }
- }
-
- /**
- * Fetch the next batch of data from the LDAP searchEnumerationr result.
- * @return the next Batch of results.
- */
- // GHH 20080326 - set all batches as last batch after an exception
- // is thrown calling a method on the enumeration. Per Javadoc for
- // javax.naming.NamingEnumeration, enumeration is invalid after an
- // exception is thrown - by setting last batch indicator we prevent
- // it from being used again.
- // GHH 20080326 - also added return of explanation for generic
- // NamingException
- public List next() throws ConnectorException {
- try {
- // The search has been executed, so process up to one batch of
- // results.
- List result = null;
- while (result == null && searchEnumeration != null && searchEnumeration.hasMore())
- {
- SearchResult searchResult = (SearchResult) searchEnumeration.next();
- result = getRow(searchResult);
- }
-
- return result;
- } catch (SizeLimitExceededException e) {
- this.config.getLogger().logWarning("Search results exceeded size limit. Results may be incomplete."); //$NON-NLS-1$
- searchEnumeration = null; // GHH 20080326 - NamingEnumartion's are no longer good after an exception so toss it
- return null; // GHH 20080326 - if size limit exceeded don't try to read more results
- } catch (NamingException ne) {
- final String msg = "Ldap error while processing next batch of results: " + ne.getExplanation(); //$NON-NLS-1$
- this.config.getLogger().logError(msg); // GHH 20080326 - changed to output explanation from LDAP server
- searchEnumeration = null; // GHH 20080326 - NamingEnumertion's are no longer good after an exception so toss it
- throw new ConnectorException(msg);
- }
- }
-
- /**
- * Create a row using the searchResult and add it to the supplied batch.
- * @param batch the supplied batch
- * @param result the search result
- */
- // GHH 20080326 - added fetching of DN of result, for directories that
- // do not include it as an attribute
- private List getRow(SearchResult result) throws ConnectorException {
- Attributes attrs = result.getAttributes();
- String resultDN = result.getNameInNamespace(); // added GHH 20080326
- ArrayList attributeList = searchDetails.getElementList();
- List row = new ArrayList();
-
- if (attrs != null && attrs.size()>0) {
- Iterator itr = attributeList.iterator();
- while(itr.hasNext()) {
- addResultToRow((Column)itr.next(), resultDN, attrs, row); // GHH 20080326 - added resultDN parameter to call
- }
- return row;
- }
- return null;
- }
-
- /**
- * Add Result to Row
- * @param modelElement the model element
- * @param attrs the attributes
- * @param row the row
- */
- // GHH 20080326 - added resultDistinguishedName to method signature. If
- // there is an element in the model named "DN" and there is no attribute
- // with this name in the search result, we return this new parameter
- // value for that column in the result
- // GHH 20080326 - added handling of ClassCastException when non-string
- // attribute is returned
- private void addResultToRow(Column modelElement, String resultDistinguishedName, Attributes attrs, List row) throws ConnectorException {
-
- String strResult;
- String modelAttrName = parser.getNameFromElement(modelElement);
- Class modelAttrClass = modelElement.getJavaType();
- if(modelAttrName == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.nullAttrError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
-
- Attribute resultAttr = attrs.get(modelAttrName);
-
- // If the attribute is not present, we return NULL.
- if(resultAttr == null) {
- // MPW - 2-20-07 - Changed from returning empty string to returning null.
- //row.add("");
- //logger.logTrace("Did not find a match for attribute named: " + modelAttrName);
- // GHH 20080326 - return DN from input parameter
- // if DN attribute is not present in search result
- if (modelAttrName.toUpperCase().equals("DN")) { //$NON-NLS-1$
- row.add(resultDistinguishedName);
- }
- else {
- row.add(null);
- }
- return;
- }
- // TODO: Currently, if an LDAP entry contains more than one matching
- // attribute, we only return the first.
- // Since attribute order is not guaranteed, this means that we may not
- // always return the exact same information.
- // Putting multi-valued attributes into a single row (or multiple rows) requires
- // some design decisions.
- // GHH 20080326 - first get attribute as generic object
- // so we can check to make sure it is a string separately - previously it was just put straight into a string.
- Object objResult = null;
- try {
- objResult = resultAttr.get();
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.attrValueFetchError",modelAttrName); //$NON-NLS-1$
- this.config.getLogger().logWarning(msg+" : "+ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg+" : "+ne.getExplanation()); //$NON-NLS-1$
- }
-
- // GHH 20080326 - if attribute is not a string, just
- // return an empty string.
- // TODO - allow return of non-strings (always byte[]) as
- // MM object. Perhaps also add directory-specific logic
- // to deserialize byte[] attributes into Java objects
- // when appropriate
- try {
- strResult = (String)objResult;
- } catch (ClassCastException cce) {
- strResult = ""; //$NON-NLS-1$
- }
-
- // MPW - 3.9.07 - Also return NULL when attribute is unset or empty string.
- // There is no way to differentiate between being unset and being the empty string.
- if(strResult.equals("")) { //$NON-NLS-1$
- strResult = null;
- }
-
- // MPW: 3-11-07: Added support for java.lang.Integer conversion.
- try {
- if(modelAttrClass.equals(Class.forName(Integer.class.getName()))) {
- try {
- // Throw an exception if class cast fails.
- if(strResult != null) {
- Integer intResult = new Integer(strResult);
- row.add(intResult);
- } else {
- row.add(null);
- }
- } catch(NumberFormatException nfe) {
- throw new ConnectorException(nfe, "Element " + modelAttrName + " is typed as Integer, " + //$NON-NLS-1$ //$NON-NLS-2$
- "but it's value (" + strResult + ") cannot be converted from string " + //$NON-NLS-1$ //$NON-NLS-2$
- "to Integer. Please change type to String, or modify the data."); //$NON-NLS-1$
- }
- // java.lang.String
- } else if(modelAttrClass.equals(Class.forName(String.class.getName()))) {
- row.add(strResult);
- // java.sql.Timestamp
- } else if(modelAttrClass.equals(Class.forName(java.sql.Timestamp.class.getName()))) {
- Map<String, String> p = modelElement.getProperties();
-
- String timestampFormat = p.get("Format"); //$NON-NLS-1$
- SimpleDateFormat dateFormat;
- if(timestampFormat == null) {
- timestampFormat = LDAPConnectorConstants.ldapTimestampFormat;
-
- }
- dateFormat = new SimpleDateFormat(timestampFormat);
- try {
- if(strResult != null) {
- Date dateResult = dateFormat.parse(strResult);
- Timestamp tsResult = new Timestamp(dateResult.getTime());
- row.add(tsResult);
- } else {
- row.add(null);
- }
- } catch(ParseException pe) {
- throw new ConnectorException(pe, "Timestamp could not be parsed. Please check to ensure the " //$NON-NLS-1$
- + " Format field for attribute " //$NON-NLS-1$
- + modelAttrName + " is configured using SimpleDateFormat conventions."); //$NON-NLS-1$
- }
-
- // TODO: Extend support for more types in the future.
- // Specifically, add support for byte arrays, since that's actually supported
- // in the underlying data source.
- } else {
- throw new ConnectorException("Base type " + modelAttrClass.toString() //$NON-NLS-1$
- + " is not supported in the LDAP connector. " //$NON-NLS-1$
- + " Please modify the base model to use a supported type."); //$NON-NLS-1$
- }
- } catch(ClassNotFoundException cne) {
- final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.supportedClassNotFoundError"); //$NON-NLS-1$
- throw new ConnectorException(cne, msg);
- }
- }
-
-
- /**
- * Active Directory and OpenLDAP supports PagedResultsControls, so I left
- * this method in here in case we decide to extend support for this control
- * in the future.
- */
-// private void setADRequestControls(int maxBatchSize) {
-// try {
-// ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(
-// maxBatchSize, Control.CRITICAL) });
-// } catch (NamingException ne) {
-// logger.logError("Failed to set page size for LDAP results. Please ensure that paged results controls are supported by the LDAP server implementation."); //$NON-NLS-1$
-// ne.printStackTrace();
-// } catch (IOException ioe) {
-// logger.logError("IO Exception while setting paged results control."); //$NON-NLS-1$
-// ioe.printStackTrace();
-// }
-// }
-}
Deleted: trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPUpdateExecution.java
===================================================================
--- trunk/connectors/connector-ldap/src/main/java/com/metamatrix/connector/ldap/LDAPUpdateExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/main/java/org/teiid/resource/cci/ldap/LDAPUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,455 +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 com.metamatrix.connector.ldap;
-
-import java.util.List;
-
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.BasicAttribute;
-import javax.naming.directory.BasicAttributes;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.ModificationItem;
-import javax.naming.ldap.InitialLdapContext;
-import javax.naming.ldap.LdapContext;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.ColumnReference;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Comparison;
-import org.teiid.connector.language.Condition;
-import org.teiid.connector.language.Delete;
-import org.teiid.connector.language.Expression;
-import org.teiid.connector.language.ExpressionValueSource;
-import org.teiid.connector.language.Insert;
-import org.teiid.connector.language.Literal;
-import org.teiid.connector.language.SetClause;
-import org.teiid.connector.language.Update;
-import org.teiid.connector.language.Comparison.Operator;
-import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-
-/**
- * Please see the user's guide for a full description of capabilties, etc.
- *
- * Description/Assumptions:
- * 1. Table's name in source defines the base DN (or context) for the search.
- * Example: Table.NameInSource=ou=people,dc=gene,dc=com
- * 2. Column's name in source defines the LDAP attribute name.
- * [Default] If no name in source is defined, then we attempt to use the column name
- * as the LDAP attribute name.
- * 3. Since all of the underlying LDAP methods for adding/deleting/updating
- * require specification of the LDAP distinguished name (DN) to change, for all
- * corresponding MetaMatrix operations the DN must be specified (as the sole
- * item in the WHERE clause for UPDATE and DELETE operations, and in the list
- * of attributes to assign values in an INSERT operation * Responsible for update/insert/delete operations against LDAP
- */
-public class LDAPUpdateExecution extends BasicExecution implements UpdateExecution {
- private RuntimeMetadata rm;
- private InitialLdapContext initialLdapContext;
- private LdapContext ldapCtx;
- private Command command;
- private LDAPManagedConnectionFactory config;
-
- public LDAPUpdateExecution(Command command, ExecutionContext ctx,
- RuntimeMetadata rm, InitialLdapContext ldapCtx, LDAPManagedConnectionFactory config) throws ConnectorException {
- this.rm = rm;
- this.initialLdapContext = ldapCtx;
- this.command = command;
- this.config = config;
- }
-
- /** execute generic update-class (either an update, delete, or insert)
- * operation and returns a count of affected rows. Since underlying
- * LDAP operations (and this connector) can modify at most one LDAP
- * leaf context at a time, this will always return 1. It will never
- * actually return 0, because if an operation fails, a
- * ConnectorException will be thrown instead.
- * Note that really it should return 0 if a delete is performed on
- * an entry that doesn't exist (but whose parent does exist), but
- * since the underlying LDAP operation will return success for such a
- * delete, we just blindly return 1. To return 0 would mean performing
- * a search for the entry first before deleting it (to confirm that it
- * did exist prior to the delete), so right now we sacrifice accuracy
- * here for the sake of efficiency.
- */
- @Override
- public void execute() throws ConnectorException {
- // first make a copy of the initial LDAP context we got from
- // the connection. The actual update-class operation will use
- // this copy. This will enable the close and cancel methods
- // to stop any LDAP operations we are making by calling the
- // close() method of the copy context, without closing our
- // real connection to the LDAP server
- try {
- ldapCtx = (LdapContext)this.initialLdapContext.lookup(""); //$NON-NLS-1$
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.createContextError",ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
-
- if (command instanceof Update) {
- executeUpdate();
- }
- else if (command instanceof Delete) {
- executeDelete();
- }
- else if (command instanceof Insert) {
- executeInsert();
- }
- else {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.incorrectCommandError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- }
-
- @Override
- public int[] getUpdateCounts() throws DataNotAvailableException,
- ConnectorException {
- return new int[] {1};
- }
-
-
- // Private method to actually do an insert operation. Per JNDI doc at
- // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html, JNDI method to add new entry to LDAP that does not contain a Java object is
- // DirContext.createSubContext(), so that is what is used here.
- //
- // The insert must include an element named "DN" (case insensitive)
- // which will be the fully qualified LDAP distinguished name of the
- // entry to add.
- //
- // Also, while we make no effort to prevent insert operations that
- // break these rules, the underlying LDAP operation will fail (and
- // pass back an explanatory message, which we will return in a
- // ConnectorException, in the following cases:
- // -if the parent context for this entry does not exist in the directory
- // -if the insert does not specify values for all required attributes
- // of the class. Since objectClass is required for all LDAP entries,
- // if it is not specified this condition will apply - and once it is
- // specified then all of the other required attributes for that
- // objectClass will of course also be required.
- //
- // Just as with the read support in the LDAPSyncQueryExecution class,
- // multi-value attributes are not supported by this implementation.
- //
- // TODO - maybe automatically specify objectClass based off of
- // Name/NameInSource RESTRICT property settings, like with read support
- private void executeInsert()
- throws ConnectorException {
-
- List<ColumnReference> insertElementList = ((Insert)command).getColumns();
- List<Expression> insertValueList = ((ExpressionValueSource)((Insert)command).getValueSource()).getValues();
- // create a new attribute list with case ignored in attribute
- // names
- Attributes insertAttrs = new BasicAttributes(true);
- Attribute insertAttr; // what we will use to populate the attribute list
- ColumnReference insertElement;
- String nameInsertElement;
- Object insertValue;
- String distinguishedName = null;
- // The IInsert interface uses separate List objects for
- // the element names and values to be inserted, limiting
- // the potential for code reuse in reading them (since all
- // other interfaces use ICriteria-based mechanisms for such
- // input).
- for (int i=0; i < insertElementList.size(); i++) {
- insertElement = insertElementList.get(i);
- // call utility class to get NameInSource/Name of element
- nameInsertElement = getNameFromElement(insertElement);
- // special handling for DN attribute - use it to set
- // distinguishedName value.
- if (nameInsertElement.toUpperCase().equals("DN")) { //$NON-NLS-1$
- insertValue = ((Literal)insertValueList.get(i)).getValue();
- if (insertValue == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.columnSourceNameDNNullError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- if (!(insertValue instanceof java.lang.String)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.columnSourceNameDNTypeError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- distinguishedName = (String)insertValue;
- }
- // for other attributes specified in the insert command,
- // create a new
- else {
- insertAttr = new BasicAttribute(nameInsertElement);
- insertValue = ((Literal)insertValueList.get(i)).getValue();
- insertAttr.add(insertValue);
- insertAttrs.put(insertAttr);
- }
- }
- // if the DN is not specified, we don't know enough to attempt
- // the LDAP add operation, so throw an exception
- if (distinguishedName == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.noInsertSourceNameDNError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- // just try to create a new LDAP entry using the DN and
- // attributes specified in the INSERT operation. If it isn't
- // legal, we'll get a NamingException back, whose explanation
- // we'll return in a ConnectorException
- try {
- ldapCtx.createSubcontext(distinguishedName, insertAttrs);
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.insertFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg);
- } catch (Exception e) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.insertFailedUnexpected",distinguishedName); //$NON-NLS-1$
- throw new ConnectorException(e, msg);
- }
- }
-
- // Private method to actually do a delete operation. Per JNDI doc at
- // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html,
- // a good JNDI method to delete an entry to LDAP is
- // DirContext.destroySubContext(), so that is what is used here.
- //
- // The delete criteria must include only an equals comparison
- // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
- // Note that the underlying LDAP operations here return successfully
- // even if the named entry doesn't exist (as long as its parent does
- // exist).
- private void executeDelete()
- throws ConnectorException {
-
- Condition criteria = ((Delete)command).getWhere();
-
- // since we have the exact same processing rules for criteria
- // for updates and deletes, we use a common private method to do this.
- // note that this private method will throw a ConnectorException
- // for illegal criteria, which we deliberately don't catch
- // so it gets passed on as is.
- String distinguishedName = getDNFromCriteria(criteria);
-
- // just try to delete an LDAP entry using the DN
- // specified in the DELETE operation. If it isn't
- // legal, we'll get a NamingException back, whose explanation
- // we'll return in a ConnectorException
- try {
- ldapCtx.destroySubcontext(distinguishedName);
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.deleteFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg);
- // don't remember why I added this generic catch of Exception,
- // but it does no harm...
- } catch (Exception e) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.deleteFailedUnexpected",distinguishedName); //$NON-NLS-1$
- throw new ConnectorException(e, msg);
- }
- }
-
- // Private method to actually do an update operation. Per JNDI doc at
- // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html,
- // the JNDI method to use to update an entry to LDAP is one of the
- // DirContext.modifyAttributes() methods that takes ModificationItem[]
- // as a parameter, so that is what is used here.
- // Note that this method does not allow for changing of the DN - to
- // implement that we would need to use Context.rename(). Since right
- // now we only call modifyAttributes(), and don't check for the DN
- // in the list of updates, we will attempt to update the DN using
- // modifyAttributes(), and let the LDAP server fail the request (and
- // send us the explanation for the failure, which is returned in
- // a ConnectorException)
- //
- // The update criteria must include only an equals comparison
- // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
- private void executeUpdate()
- throws ConnectorException {
-
- List<SetClause> updateList = ((Update)command).getChanges();
- Condition criteria = ((Update)command).getWhere();
-
- // since we have the exact same processing rules for criteria
- // for updates and deletes, we use a common private method to do this.
- // note that this private method will throw a ConnectorException
- // for illegal criteria, which we deliberately don't catch
- // so it gets passed on as is.
- String distinguishedName = getDNFromCriteria(criteria);
-
-
- // this will be the list of modifications to attempt. Since
- // we currently blindly try all the updates the query
- // specifies, right now this is the same size as the updateList.
- // When we start filtering out DN changes (which would need to
- // be performed separately using Context.rename()), we will
- // need to account for this in determining this list size.
- ModificationItem[] updateMods = new ModificationItem[updateList.size()];
- ColumnReference leftElement;
- Expression rightExpr;
- String nameLeftElement;
- Object valueRightExpr;
- // iterate through the supplied list of updates (each of
- // which is an ICompareCriteria with an IElement on the left
- // side and an IExpression on the right, per the Connector
- // API).
- for (int i=0; i < updateList.size(); i++) {
- SetClause setClause = updateList.get(i);
- // trust that connector API is right and left side
- // will always be an IElement
- leftElement = setClause.getSymbol();
- // call utility method to get NameInSource/Name for element
- nameLeftElement = getNameFromElement(leftElement);
- // get right expression - if it is not a literal we
- // can't handle that so throw an exception
- rightExpr = setClause.getValue();
- if (!(rightExpr instanceof Literal)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.valueNotLiteralError",nameLeftElement); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- valueRightExpr = ((Literal)rightExpr).getValue();
- // add in the modification as a replacement - meaning
- // any existing value(s) for this attribute will
- // be replaced by the new value. If the attribute
- // didn't exist, it will automatically be created
- // TODO - since null is a valid attribute
- // value, we don't do any special handling of it right
- // now. But maybe null should mean to delete an
- // attribute?
- updateMods[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(nameLeftElement, valueRightExpr));
- }
- // just try to update an LDAP entry using the DN and
- // attributes specified in the UPDATE operation. If it isn't
- // legal, we'll get a NamingException back, whose explanation
- // we'll return in a ConnectorException
- try {
- ldapCtx.modifyAttributes(distinguishedName, updateMods);
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.updateFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
- throw new ConnectorException(msg);
- // don't remember why I added this generic catch of Exception,
- // but it does no harm...
- } catch (Exception e) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.updateFailedUnexpected",distinguishedName); //$NON-NLS-1$
- throw new ConnectorException(e, msg);
- }
- }
-
- // private method for extracting the distinguished name from
- // the criteria, which must include only an equals comparison
- // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
- // most of this code is to check the criteria to make sure it is in
- // this form and throw an appropriate exception if it is not
- // since there is no way to specify this granularity of criteria
- // right now in the connector capabilities
- private String getDNFromCriteria(Condition criteria)
- throws ConnectorException {
- if (criteria == null) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaEmptyError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- if (!(criteria instanceof Comparison)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaNotSimpleError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- Comparison compareCriteria = (Comparison)criteria;
- if (compareCriteria.getOperator() != Operator.EQ) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaNotEqualsError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- Expression leftExpr = compareCriteria.getLeftExpression();
- if (!(leftExpr instanceof ColumnReference)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaLHSNotElementError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- // call utility method to get NameInSource/Name for element
- String nameLeftExpr = getNameFromElement((ColumnReference)leftExpr);
- if (!(nameLeftExpr.toUpperCase().equals("DN"))) { //$NON-NLS-1$
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaSrcColumnError",nameLeftExpr); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- Expression rightExpr = compareCriteria.getRightExpression();
- if (!(rightExpr instanceof Literal)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaRHSNotLiteralError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- Object valueRightExpr = ((Literal)rightExpr).getValue();
- if (!(valueRightExpr instanceof java.lang.String)) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaRHSNotStringError"); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- return (String)valueRightExpr;
- }
-
- // This is an exact copy of the method with the same name in
- // IQueryToLdapSearchParser - really should be in a utility class
- private String getNameFromElement(ColumnReference e) throws ConnectorException {
- String ldapAttributeName = null;
- String elementNameDirect = e.getName();
- if (elementNameDirect == null) {
- } else {
- }
- AbstractMetadataRecord mdObject = e.getMetadataObject();
- if (mdObject == null) {
- return ""; //$NON-NLS-1$
- }
- ldapAttributeName = mdObject.getNameInSource();
- if(ldapAttributeName == null || ldapAttributeName.equals("")) { //$NON-NLS-1$
- ldapAttributeName = mdObject.getName();
- // If name in source is not set, then fall back to the column name.
- }
- return ldapAttributeName;
- }
-
-
- // cancel here by closing the copy of the ldap context (if it was
- // initialized, which is only true if execute() was previously called)
- // calling close on already closed context is safe per
- // javax.naming.Context javadoc so we won't worry about this also
- // happening in our close method
- public void cancel() throws ConnectorException {
- close();
- }
-
- // close here by closing the copy of the ldap context (if it was
- // initialized, which is only true if execute() was previously called)
- // calling close on already closed context is safe per
- // javax.naming.Context javadoc so we won't worry about this also
- // happening in our close method
- public void close() throws ConnectorException {
- try {
- if(ldapCtx != null) {
- ldapCtx.close();
- }
- } catch (NamingException ne) {
- final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.closeContextError",ne.getExplanation()); //$NON-NLS-1$
- this.config.getLogger().logError(msg);
- }
- }
-
-}
-
-
-
-
-
-
-
-
-
-
Modified: trunk/connectors/connector-ldap/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-ldap/src/main/rar/META-INF/ra.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-ldap/src/main/rar/META-INF/ra.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,63 +34,13 @@
<license-required>true</license-required>
</license>
<resourceadapter>
- <resourceadapter-class>org.teiid.connector.basic.BasicResourceAdapter</resourceadapter-class>
+ <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
<outbound-resourceadapter>
<connection-definition>
- <managedconnectionfactory-class>com.metamatrix.connector.ldap.LDAPManagedConnectionFactory</managedconnectionfactory-class>
+ <managedconnectionfactory-class>org.teiid.resource.cci.ldap.LDAPManagedConnectionFactory</managedconnectionfactory-class>
<config-property>
- <description>{$display:"Connector Class",$advanced:"true"}</description>
- <config-property-name>ConnectorClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.ldap.LDAPConnector</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Connector Capabilities",$description:"The class to use to provide the Connector Capabilities",$advanced:"true"}</description>
- <config-property-name>CapabilitiesClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.ldap.LDAPConnectorCapabilities</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is Immutable",$description:"Is Immutable, True if the source never changes.",$advanced:"true"}</description>
- <config-property-name>Immutable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is XA Capable",$description:"True, if this connector supports XA Transactions",$advanced:"true"}</description>
- <config-property-name>XaCapable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Exception on Exceeding Max Rows",$description:"Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",$advanced:"true"}</description>
- <config-property-name>ExceptionOnMaxRows</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Maximum Result Rows",$description:"Maximum Result Rows allowed",$advanced:"true"}</description>
- <config-property-name>MaxResultRows</config-property-name>
- <config-property-type>java.lang.Integer</config-property-type>
- <config-property-value>-1</config-property-value>
- </config-property>
-
- <!-- LDAP Specific properties -->
-
- <config-property>
- <description>{$display:"Default Search Base DN",$description:"Default Base DN for LDAP Searches",$advanced:"true"}</description>
- <config-property-name>SearchDefaultBaseDN</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </config-property>
-
- <config-property>
<description>{$display:"Ldap Admin User DN",$description:"User DN for the LDAP admin account.",$required:"true"}</description>
<config-property-name>LdapAdminUserDN</config-property-name>
<config-property-type>java.lang.String</config-property-type>
@@ -104,13 +54,6 @@
</config-property>
<config-property>
- <description>{$display:"Restrict Searches To Named Object Class",$description:"Restrict Searches to objectClass named in the Name field for a table",$advanced:"true"}</description>
- <config-property-name>RestrictToObjectClass</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
<description>{$display:"Ldap Transaction Timeout (ms)",$description:"Timeout value for LDAP searches. Defaults to TCP timeout value."}</description>
<config-property-name>LdapTxnTimeoutInMillis</config-property-name>
<config-property-type>java.lang.Long</config-property-type>
@@ -122,19 +65,19 @@
<config-property-name>LdapUrl</config-property-name>
<config-property-type>java.lang.String</config-property-type>
<config-property-value>ldap://<ldapServer>:<389></config-property-value>
- </config-property>
+ </config-property>
<config-property>
- <description>{$display:"Default Search Scope",$description:"Default Scope for LDAP Searches",$allowed:["OBJECT_SCOPE","ONELEVEL_SCOPE","SUBTREE_SCOPE"],$required:"true"}</description>
- <config-property-name>SearchDefaultScope</config-property-name>
+ <description>{$display:"Ldap Context Factory",$description:"LDAP Context factory Class",$required:"true", readOnly="true"}</description>
+ <config-property-name>LdapContextFactory</config-property-name>
<config-property-type>java.lang.String</config-property-type>
- <config-property-value>SUBTREE_SCOPE</config-property-value>
- </config-property>
+ <config-property-value>com.sun.jndi.ldap.LdapCtxFactory</config-property-value>
+ </config-property>
- <connectionfactory-interface>org.teiid.connector.api.Connector</connectionfactory-interface>
- <connectionfactory-impl-class>org.teiid.connector.basic.WrappedConnector</connectionfactory-impl-class>
- <connection-interface>org.teiid.connector.api.Connection</connection-interface>
- <connection-impl-class>org.teiid.connector.basic.WrappedConnection</connection-impl-class>
+ <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>
Added: trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/i18n.properties
===================================================================
--- trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/i18n.properties (rev 0)
+++ trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,83 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+LDAPConnector.loggerNotFound=Logger not found in current environment.
+LDAPConnector.getConnectionFailed=Connection pool is not initialized properly. Cannot create a new connection.
+#
+LDAPConnection.urlPropNotFound=Ldap URL property not found.
+LDAPConnection.adminUserDNPropNotFound=Ldap Admin User DN property not found.
+LDAPConnection.adminUserPassPropNotFound=Ldap Admin password property not found.
+LDAPConnection.maxCriteriaParseError=Ldap Max Criteria property has an invalid format.
+LDAPConnection.maxCriteriaPropNotFound=Ldap Max Criteria property not found.
+LDAPConnection.contextInitFailed=LDAP context initialization failed. Please check connector properties, and verify against LDAP server.
+LDAPConnection.propertyFileParseFailed=The Properties file could not be parsed.
+LDAPConnection.directoryNamingError=Initializing LDAP directory context failed. Please check LDAP connection properties, including username and password: {0}
+LDAPConnection.directoryInitError=Initializing LDAP directory context failed.
+LDAPConnection.unsupportedExecMode=LDAPConnector does not support requested execution mode.
+LDAPConnection.contextCloseError=The Connection failed to close LDAP context: {0}
+#
+IQueryToLdapSearchParser.noTablesInFromError=Cannot parse query - no tables defined in FROM clause.
+IQueryToLdapSearchParser.multiItemsInFromError=Cannot parse query - multiple items in FROM clause not supported.
+IQueryToLdapSearchParser.baseContextNameError=Base context name (DN) not specified in Name In Source or connector properties.
+IQueryToLdapSearchParser.groupCountExceededError=Query contained from clause that did not have exactly and only one group. Query not supported.
+IQueryToLdapSearchParser.criteriaNotParsableError=Compound criteria operator was not parsable.
+IQueryToLdapSearchParser.timestampClassNotFoundError=Timestamp class was not found.
+IQueryToLdapSearchParser.unsupportedElementError=Encountered an element type that is not supported. Revise the capabilities.
+IQueryToLdapSearchParser.missingNISError=An element (or expression) found in the query's compare criteria was missing a NameInSource definition (or name). Please ensure the name in source is defined for each element.
+IQueryToLdapSearchParser.criteriaNotSupportedError=Encountered a criteria that is not supported.
+IQueryToLdapSearchParser.searchDetailsLoggingError=Error writing LDAP search details to log
+#
+LDAPSyncQueryExecution.execModeError=Synchronous query was called by connector, but request does not match. Cannot execute request.
+LDAPSyncQueryExecution.setControlsError=Failed to set standard sort controls. Please verify that the server supports sorting, and that the bind user has permission to use sort controls.
+LDAPSyncQueryExecution.createContextError=Failed to create LDAP search context from the specified context name. Check the table/group name in source to ensure the context exists.
+LDAPSyncQueryExecution.configAttrsError=Failed to configure attributes properly.
+LDAPSyncQueryExecution.execSearchError=Execute search failed. Please check logs for search details.
+LDAPSyncQueryExecution.nullBatchError=A null Batch was encountered.
+LDAPSyncQueryExecution.nullAttrError=Encountered null attribute name for a select symbol. Please check name in source for each column.
+LDAPSyncQueryExecution.attrValueFetchError=Failed to fetch attribute value for attribute {0}. Rowset cannot be constructed from incomplete LDAP results.
+LDAPSyncQueryExecution.supportedClassNotFoundError=Supported class not found.
+LDAPSyncQueryExecution.closeContextError=LDAP error occurred during attempt to close context : {0}
+#
+LDAPUpdateExecution.execModeError=Update was called by connector, but request does not match. Cannot execute request.
+LDAPUpdateExecution.createContextError=Failed to create copy of the initial LDAP context: {0}
+LDAPUpdateExecution.incorrectCommandError=Incorrect command type. Expecting INSERT, UPDATE, or DELETE.
+LDAPUpdateExecution.columnSourceNameDNNullError=value for column with source name DN is null - must be set to distinguishedName for new record
+LDAPUpdateExecution.columnSourceNameDNTypeError=value for column with source name DN is not a string - must be set to distinguishedName string for new record
+LDAPUpdateExecution.noInsertSourceNameDNError=no column in insert statement with source name DN - must be present and set to distinguishedName for new record
+LDAPUpdateExecution.insertFailed=Insert of {0} failed: {1}
+LDAPUpdateExecution.insertFailedUnexpected=Insert of {0} failed for unexpected reason
+LDAPUpdateExecution.deleteFailed=Delete of {0} failed: {1}
+LDAPUpdateExecution.deleteFailedUnexpected=Delete of {0} failed for unexpected reason
+LDAPUpdateExecution.updateFailed=Update of {0} failed: {1}
+LDAPUpdateExecution.updateFailedUnexpected=Update of {0} failed for unexpected reason
+LDAPUpdateExecution.valueNotLiteralError=specified value for attribute {0} is not a literal
+LDAPUpdateExecution.criteriaEmptyError=No criteria specified on update - must specify DN in WHERE clause
+LDAPUpdateExecution.criteriaNotSimpleError=criteria is not a simple comparison - expecting simple equals comparison on DN as only item in WHERE clause
+LDAPUpdateExecution.criteriaNotEqualsError=criteria is not an equals comparison - expecting simple equals comparison on DN as only item in WHERE clause
+LDAPUpdateExecution.criteriaLHSNotElementError=left side of criteria is not an element name - expecting simple equals comparison on DN as only item in WHERE clause
+LDAPUpdateExecution.criteriaSrcColumnError=criteria is on source column {0}, but should be on a source column named DN
+LDAPUpdateExecution.criteriaRHSNotLiteralError=right side of equals comparison against DN is not a literal - must be a string literal
+LDAPUpdateExecution.criteriaRHSNotStringError=right side of equals comparison against DN is not a string - must be a string literal
+LDAPUpdateExecution.closeContextError=LDAP error occurred during attempt to close context : {0}
+#
+LDAPSourceConnectionFactory.creatingConnection=LDAPSourceConnectionFactory is creating a new connection.
+
Property changes on: trunk/connectors/connector-ldap/src/main/resources/org/teiid/resource/cci/ldap/i18n.properties
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap (from rev 2083, trunk/connectors/connector-ldap/src/test/java/com/metamatrix/connector/ldap)
Deleted: trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestIQueryToLdapSearchParser.java
===================================================================
--- trunk/connectors/connector-ldap/src/test/java/com/metamatrix/connector/ldap/TestIQueryToLdapSearchParser.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestIQueryToLdapSearchParser.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,309 +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 com.metamatrix.connector.ldap;
-
-import static org.mockito.Mockito.*;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.naming.directory.Attribute;
-import javax.naming.directory.SearchControls;
-import javax.naming.ldap.SortKey;
-
-import junit.framework.TestCase;
-
-import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.MetadataStore;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-import org.teiid.connector.metadata.runtime.Schema;
-import org.teiid.connector.metadata.runtime.Table;
-import org.teiid.connector.metadata.runtime.Column.SearchType;
-import org.teiid.dqp.internal.datamgr.metadata.RuntimeMetadataImpl;
-import org.teiid.metadata.CompositeMetadataStore;
-import org.teiid.metadata.TransformationMetadata;
-
-import com.metamatrix.cdk.CommandBuilder;
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.query.metadata.QueryMetadataInterface;
-import com.metamatrix.query.unittest.RealMetadataFactory;
-
-/**
- * Test IQueryToLdapSearchParser.
- */
-/**
- * @author mdrilling
- *
- */
-public class TestIQueryToLdapSearchParser extends TestCase {
-
- public TestIQueryToLdapSearchParser(String name) {
- super(name);
- }
-
- /**
- * Get Resolved Command using SQL String and metadata.
- */
- public Command getCommand(String sql, QueryMetadataInterface metadata) {
- CommandBuilder builder = new CommandBuilder(metadata);
- return builder.getCommand(sql);
- }
-
- /**
- * Helper method for testing the provided LDAPSearchDetails against expected values
- * @param searchDetails the LDAPSearchDetails object
- * @param expectedContextName the expected context name
- * @param expectedContextFilter the expected context filter string
- * @param expectedAttrNameList list of expected attribute names
- * @param expectedCountLimit the expected count limit
- * @param expectedSearchScope the expected search scope
- * @param expectedSortKeys the expected sortKeys list.
- */
- public void helpTestSearchDetails(final LDAPSearchDetails searchDetails, final String expectedContextName,
- final String expectedContextFilter, final List expectedAttrNameList, final long expectedCountLimit,
- final int expectedSearchScope, final SortKey[] expectedSortKeys) {
-
- // Get all of the actual values
- String contextName = searchDetails.getContextName();
- String contextFilter = searchDetails.getContextFilter();
- List attrList = searchDetails.getAttributeList();
- long countLimit = searchDetails.getCountLimit();
- int searchScope = searchDetails.getSearchScope();
- SortKey[] sortKeys = searchDetails.getSortKeys();
-
- // Compare actual with Expected
- assertEquals(expectedContextName, contextName);
- assertEquals(expectedContextFilter, contextFilter);
-
- assertEquals(attrList.size(),expectedAttrNameList.size());
- Iterator iter = attrList.iterator();
- Iterator eIter = expectedAttrNameList.iterator();
- while(iter.hasNext()&&eIter.hasNext()) {
- String actualName = ((Attribute)iter.next()).getID();
- String expectedName = (String)eIter.next();
- assertEquals(actualName, expectedName);
- }
-
- assertEquals(expectedCountLimit, countLimit);
- assertEquals(expectedSearchScope, searchScope);
- assertEquals(expectedSortKeys, sortKeys);
- }
-
- /**
- * Test a Query without criteria
- */
- public void testSelectFrom1() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(objectClass=*)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- /**
- * Test a Query with a criteria
- */
- public void testSelectFromWhere1() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R%'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(cn=R%)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- /**
- * Test a Query with a criteria
- */
- public void testEscaping() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R*'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(cn=R\\2a)"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- public void testNot() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE not (Name like 'R%' or Name like 'S%')"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(&(!(cn=R*))(!(cn=S*)))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
-
- }
-
- public void testGT() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name > 'R'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(!(cn<=R))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
- }
-
- public void testLT() throws Exception {
- LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name < 'R'"); //$NON-NLS-1$
-
- //-----------------------------------
- // Set Expected SearchDetails Values
- //-----------------------------------
- String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
- String expectedContextFilter = "(!(cn>=R))"; //$NON-NLS-1$
-
- List expectedAttrNameList = new ArrayList();
- expectedAttrNameList.add("uid"); //$NON-NLS-1$
- expectedAttrNameList.add("cn"); //$NON-NLS-1$
-
- long expectedCountLimit = -1;
- int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
- SortKey[] expectedSortKeys = null;
-
- helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
- expectedCountLimit, expectedSearchScope, expectedSortKeys);
- }
-
- private LDAPSearchDetails helpGetSearchDetails(String queryString) throws ConnectorException {
- QueryMetadataInterface metadata = exampleLdap();
- RuntimeMetadata rm = new RuntimeMetadataImpl(metadata);
-
- LDAPManagedConnectionFactory config = mock(LDAPManagedConnectionFactory.class);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
-
- IQueryToLdapSearchParser searchParser = new IQueryToLdapSearchParser(rm, config);
-
- Select query = (Select)getCommand(queryString, metadata);
-
- LDAPSearchDetails searchDetails = searchParser.translateSQLQueryToLDAPSearch(query);
- return searchDetails;
- }
-
- public static QueryMetadataInterface exampleLdap() {
- MetadataStore metadataStore = new MetadataStore();
-
- // Create models
- Schema ldapModel = RealMetadataFactory.createPhysicalModel("LdapModel", metadataStore); //$NON-NLS-1$
-
- // Create physical groups
- Table table = RealMetadataFactory.createPhysicalGroup("People", ldapModel); //$NON-NLS-1$
- table.setNameInSource("ou=people,dc=metamatrix,dc=com"); //$NON-NLS-1$
-
- // Create physical elements
- String[] elemNames = new String[] {
- "UserID", "Name" //$NON-NLS-1$ //$NON-NLS-2$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
- };
-
- List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
-
- // Set name in source on each column
- String[] nameInSource = new String[] {
- "uid", "cn" //$NON-NLS-1$ //$NON-NLS-2$
- };
- for(int i=0; i<2; i++) {
- Column obj = cols.get(i);
- obj.setNameInSource(nameInSource[i]);
- }
-
- // Set column-specific properties
- for(int i=1; i<2; i++) {
- cols.get(i).setSearchType(SearchType.Unsearchable);
- }
-
- // Create the facade from the store
- return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, null);
- }
-}
-
Modified: trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestLDAPConnection.java
===================================================================
--- trunk/connectors/connector-ldap/src/test/java/com/metamatrix/connector/ldap/TestLDAPConnection.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-ldap/src/test/java/org/teiid/resource/cci/ldap/TestLDAPConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -20,11 +20,8 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.ldap;
+package org.teiid.resource.cci.ldap;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.stub;
-
import java.util.Hashtable;
import javax.naming.Context;
@@ -33,7 +30,8 @@
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorLogger;
+import org.teiid.resource.cci.ldap.LDAPConnectionImpl;
+import org.teiid.resource.cci.ldap.LDAPManagedConnectionFactory;
public class TestLDAPConnection {
@@ -48,14 +46,14 @@
@Test public void testInitialization() throws Exception {
- LDAPManagedConnectionFactory config = mock(LDAPManagedConnectionFactory.class);
- stub(config.getLdapUrl()).toReturn("ldap://foo");
- stub(config.getLdapAdminUserDN()).toReturn("admin");
- stub(config.getLdapAdminUserPassword()).toReturn("password");
+ LDAPManagedConnectionFactory config = new LDAPManagedConnectionFactory();
+ config.setLdapUrl("ldap://foo");
+ config.setLdapAdminUserDN("admin");
+ config.setLdapAdminUserPassword("password");
+ config.setLdapContextFactory(FakeFactory.class.getName());
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- new LDAPConnection(config, FakeFactory.class.getName());
+ new LDAPConnectionImpl(config);
}
}
Modified: trunk/connectors/connector-salesforce/pom.xml
===================================================================
--- trunk/connectors/connector-salesforce/pom.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,35 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <parent>
- <artifactId>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.0.0-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-salesforce</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Salesforce Connector</name>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-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>
+ <description>Integrates the query engine with Salesforce.com.</description>
+ <dependencies>
<dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-connector-api</artifactId>
- <scope>provided</scope>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-connector-api</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
+ <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>
+ <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>
@@ -58,7 +63,6 @@
<classifier>lib</classifier>
</configuration>
</execution>
-
</executions>
</plugin>
</plugins>
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Connector.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Connector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Connector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,95 +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 com.metamatrix.connector.salesforce;
-
-import javax.security.auth.Subject;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectionContext;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-
-public class Connector extends org.teiid.connector.basic.BasicConnector {
-
- private SalesForceManagedConnectionFactory connectorEnv;
- private boolean singleIdentity;
-
- // ///////////////////////////////////////////////////////////
- // Connector implementation
- // ///////////////////////////////////////////////////////////
- @Override
- public Connection getConnection() throws ConnectorException {
- getLogger().logTrace("Enter SalesforceSourceConnection.getConnection()");
- Connection connection = null;
- if (singleIdentity) {
- connection = new SalesforceConnection(connectorEnv);
- } else {
- // if the security domain is enabled, then subject is not null.
- Subject subject = ConnectionContext.getSubject();
- if(subject != null) {
- connection = new SalesforceConnection(subject, connectorEnv);
- } else {
- throw new ConnectorException("Unknown trusted payload type");
- }
- }
- getLogger().logTrace("Return SalesforceSourceConnection.getConnection()");
- return connection;
- }
-
- @Override
- public void initialize(ConnectorEnvironment env) throws ConnectorException {
- super.initialize(env);
-
- this.connectorEnv = (SalesForceManagedConnectionFactory)env;
-
- getLogger().logInfo("Started"); //$NON-NLS-1$
- getLogger().logInfo("Initialized"); //$NON-NLS-1$
- getLogger().logTrace("Initialization Properties: " + this.connectorEnv.toString()); //$NON-NLS-1$
-
- //validate that both are empty or both have values
- if(this.connectorEnv.getUsername() != null) {
- singleIdentity = true;
- }
-
- getLogger().logTrace("Return SalesforceSourceConnection.initialize()");
- }
-
-
- /////////////////////////////////////////////////////////////
- //Utilities
- /////////////////////////////////////////////////////////////
-
- private ConnectorLogger getLogger(){
- return this.config.getLogger();
- }
-
-
- @Override
- public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
- return SalesforceCapabilities.class;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Constants.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Constants.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Constants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,51 +0,0 @@
-package com.metamatrix.connector.salesforce;
-
-public interface Constants {
-
- public static final String PICKLIST_TYPE = "picklist"; //$NON-NLS-1$
-
- public static final String MULTIPICKLIST_TYPE = "multipicklist"; //$NON-NLS-1$
-
- public static final String COMBOBOX_TYPE = "combobox"; //$NON-NLS-1$
-
- public static final String ANYTYPE_TYPE = "anyType"; //$NON-NLS-1$
-
- public static final String REFERENCE_TYPE = "reference"; //$NON-NLS-1$
-
- public static final String STRING_TYPE = "string"; //$NON-NLS-1$
-
- public static final String BASE64_TYPE = "base64"; //$NON-NLS-1$
-
- public static final String BOOLEAN_TYPE = "boolean"; //$NON-NLS-1$
-
- public static final String CURRENCY_TYPE = "currency"; //$NON-NLS-1$
-
- public static final String TEXTAREA_TYPE = "textarea"; //$NON-NLS-1$
-
- public static final String INT_TYPE = "int"; //$NON-NLS-1$
-
- public static final String DOUBLE_TYPE = "double"; //$NON-NLS-1$
-
- public static final String PERCENT_TYPE = "percent"; //$NON-NLS-1$
-
- public static final String PHONE_TYPE = "phone"; //$NON-NLS-1$
-
- public static final String ID_TYPE = "id"; //$NON-NLS-1$
-
- public static final String DATE_TYPE = "date"; //$NON-NLS-1$
-
- public static final String DATETIME_TYPE = "datetime"; //$NON-NLS-1$
-
- public static final String URL_TYPE = "url"; //$NON-NLS-1$
-
- public static final String EMAIL_TYPE = "email"; //$NON-NLS-1$
-
- public static final String RESTRICTED_PICKLIST_TYPE = "restrictedpicklist"; //$NON-NLS-1$
-
- public static final String RESTRICTED_MULTISELECT_PICKLIST_TYPE = "restrictedmultiselectpicklist"; //$NON-NLS-1$
-
- public static final String SUPPORTS_QUERY = "Supports Query";
-
- public static final String SUPPORTS_RETRIEVE = "Supports Retrieve";
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Messages.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Messages.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Messages.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,41 +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 com.metamatrix.connector.salesforce;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-public class Messages {
-
- private static final String BUNDLE_NAME = "com.metamatrix.connector.salesforce.i18n"; //$NON-NLS-1$
-
- private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
-
- public static String getString(String key) {
- try {
- return RESOURCE_BUNDLE.getString(key);
- } catch (MissingResourceException e) {
- return '!' + key + '!';
- }
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/MetadataProcessor.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/MetadataProcessor.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/MetadataProcessor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,291 +0,0 @@
-package com.metamatrix.connector.salesforce;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.KeyRecord;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.Table;
-import org.teiid.connector.metadata.runtime.BaseColumn.NullType;
-import org.teiid.connector.metadata.runtime.Column.SearchType;
-
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.sforce.soap.partner.ChildRelationship;
-import com.sforce.soap.partner.DescribeGlobalResult;
-import com.sforce.soap.partner.DescribeGlobalSObjectResult;
-import com.sforce.soap.partner.DescribeSObjectResult;
-import com.sforce.soap.partner.Field;
-import com.sforce.soap.partner.FieldType;
-import com.sforce.soap.partner.PicklistEntry;
-
-public class MetadataProcessor {
- private MetadataFactory metadataFactory;
- private SalesforceConnection connection;
- private SalesForceManagedConnectionFactory connectorEnv;
-
- private Map<String, Table> tableMap = new HashMap<String, Table>();
- private List<Relationship> relationships = new ArrayList<Relationship>();
- private boolean hasUpdateableColumn = false;
- private List<Column> columns;
-
- // Audit Fields
- public static final String AUDIT_FIELD_CREATED_BY_ID = "CreatedById"; //$NON-NLS-1$
- public static final String AUDIT_FIELD_CREATED_DATE = "CreatedDate"; //$NON-NLS-1$
- public static final String AUDIT_FIELD_LAST_MODIFIED_BY_ID = "LastModifiedById"; //$NON-NLS-1$
- public static final String AUDIT_FIELD_LAST_MODIFIED_DATE = "LastModifiedDate"; //$NON-NLS-1$
- public static final String AUDIT_FIELD_SYSTEM_MOD_STAMP = "SystemModstamp"; //$NON-NLS-1$
-
- // Model Extensions
- static final String TABLE_SUPPORTS_CREATE = "Supports Create"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_DELETE = "Supports Delete"; //$NON-NLS-1$
- static final String TABLE_CUSTOM = "Custom"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_LOOKUP = "Supports ID Lookup"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_MERGE = "Supports Merge"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_QUERY = "Supports Query"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_REPLICATE = "Supports Replicate"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_RETRIEVE = "Supports Retrieve"; //$NON-NLS-1$
- static final String TABLE_SUPPORTS_SEARCH = "Supports Search"; //$NON-NLS-1$
-
- static final String COLUMN_DEFAULTED = "Defaulted on Create"; //$NON-NLS-1$
- static final String COLUMN_CUSTOM = "Custom"; //$NON-NLS-1$
- static final String COLUMN_CALCULATED = "Calculated"; //$NON-NLS-1$
- static final String COLUMN_PICKLIST_VALUES = "Picklist Values"; //$NON-NLS-1$
-
- public MetadataProcessor(SalesforceConnection connection, MetadataFactory metadataFactory, SalesForceManagedConnectionFactory env) {
- this.connection = connection;
- this.metadataFactory = metadataFactory;
- this.connectorEnv = env;
- }
-
- public void processMetadata() throws ConnectorException {
- DescribeGlobalResult globalResult = connection.getObjects();
- List<DescribeGlobalSObjectResult> objects = globalResult.getSobjects();
- for (DescribeGlobalSObjectResult object : objects) {
- addTable(object);
- }
- addRelationships();
- }
-
- private void addRelationships() throws ConnectorException {
- for (Iterator<Relationship> iterator = relationships.iterator(); iterator.hasNext();) {
- Relationship relationship = iterator.next();
- if (!this.connectorEnv.isModelAuditFields() && isAuditField(relationship.getForeignKeyField())) {
- continue;
- }
-
- Table parent = tableMap.get(NameUtil.normalizeName(relationship.getParentTable()));
- KeyRecord pk = parent.getPrimaryKey();
- if (null == pk) {
- throw new RuntimeException("ERROR !!primary key column not found!!"); //$NON-NLS-1$
- }
- ArrayList<String> columnNames = new ArrayList<String>();
- columnNames.add(pk.getName());
-
-
- Table child = tableMap.get(NameUtil.normalizeName(relationship.getChildTable()));
-
- Column col = null;
- columns = child.getColumns();
- for (Iterator colIter = columns.iterator(); colIter.hasNext();) {
- Column column = (Column) colIter.next();
- if(column.getName().equals(relationship.getForeignKeyField())) {
- col = column;
- }
- }
- if (null == col) throw new RuntimeException(
- "ERROR !!foreign key column not found!! " + child.getName() + relationship.getForeignKeyField()); //$NON-NLS-1$
-
-
- String columnName = "FK_" + parent.getName() + "_" + col.getName();
- ArrayList<String> columnNames2 = new ArrayList<String>();
- columnNames2.add(col.getName());
- metadataFactory.addForiegnKey(columnName, columnNames2, parent, child);
-
- }
-
-
- }
-
- public static boolean isAuditField(String name) {
- boolean result = false;
- if(name.equals(AUDIT_FIELD_CREATED_BY_ID) ||
- name.equals(AUDIT_FIELD_CREATED_DATE) ||
- name.equals(AUDIT_FIELD_LAST_MODIFIED_BY_ID) ||
- name.equals(AUDIT_FIELD_LAST_MODIFIED_DATE) ||
- name.equals(AUDIT_FIELD_SYSTEM_MOD_STAMP)) {
- result = true;
- }
- return result;
- }
-
- private void addTable(DescribeGlobalSObjectResult object) throws ConnectorException {
- DescribeSObjectResult objectMetadata = connection.getObjectMetaData(object.getName());
- String name = NameUtil.normalizeName(objectMetadata.getName());
- Table table = metadataFactory.addTable(name);
-
- table.setNameInSource(objectMetadata.getName());
- tableMap.put(name, table);
- getRelationships(objectMetadata);
-
- table.setProperty(TABLE_CUSTOM, String.valueOf(objectMetadata.isCustom()));
- table.setProperty(TABLE_SUPPORTS_CREATE, String.valueOf(objectMetadata.isCreateable()));
- table.setProperty(TABLE_SUPPORTS_DELETE, String.valueOf(objectMetadata.isDeletable()));
- table.setProperty(TABLE_SUPPORTS_MERGE, String.valueOf(objectMetadata.isMergeable()));
- table.setProperty(TABLE_SUPPORTS_QUERY, String.valueOf(objectMetadata.isQueryable()));
- table.setProperty(TABLE_SUPPORTS_REPLICATE, String.valueOf(objectMetadata.isReplicateable()));
- table.setProperty(TABLE_SUPPORTS_RETRIEVE, String.valueOf(objectMetadata.isRetrieveable()));
- table.setProperty(TABLE_SUPPORTS_SEARCH, String.valueOf(objectMetadata.isSearchable()));
-
- hasUpdateableColumn = false;
- addColumns(objectMetadata, table);
-
- // Some SF objects return true for isUpdateable() but have no updateable columns.
- if(hasUpdateableColumn && objectMetadata.isUpdateable()) {
- table.setSupportsUpdate(true);
- }
- }
-
- private void getRelationships(DescribeSObjectResult objectMetadata) {
- List<ChildRelationship> children = objectMetadata.getChildRelationships();
- if(children != null && children.size() != 0) {
- for (ChildRelationship childRelation : children) {
- Relationship newRelation = new RelationshipImpl();
- newRelation.setParentTable(objectMetadata.getName());
- newRelation.setChildTable(childRelation.getChildSObject());
- newRelation.setForeignKeyField(childRelation.getField());
- newRelation.setCascadeDelete(childRelation.isCascadeDelete());
- relationships.add(newRelation);
- }
- }
- }
-
- private void addColumns(DescribeSObjectResult objectMetadata, Table table) throws ConnectorException {
- List<Field> fields = objectMetadata.getFields();
- for (Field field : fields) {
- String normalizedName = NameUtil.normalizeName(field.getName());
- FieldType fieldType = field.getType();
- if(!this.connectorEnv.isModelAuditFields() && isAuditField(field.getName())) {
- continue;
- }
- String sfTypeName = fieldType.value();
- Column column = null;
- if(sfTypeName.equals(FieldType.STRING) || //string
- sfTypeName.equals(FieldType.COMBOBOX) || //"combobox"
- sfTypeName.equals(FieldType.REFERENCE) || //"reference"
- sfTypeName.equals(FieldType.PHONE) || //"phone"
- sfTypeName.equals(FieldType.ID) || //"id"
- sfTypeName.equals(FieldType.URL) || //"url"
- sfTypeName.equals(FieldType.EMAIL) || //"email"
- sfTypeName.equals(FieldType.ENCRYPTEDSTRING) || //"encryptedstring"
- sfTypeName.equals(FieldType.ANY_TYPE)) { //"anytype"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
- column.setNativeType(sfTypeName);
- if(sfTypeName.equals(FieldType.ID)) {
- column.setNullType(NullType.No_Nulls);
- ArrayList<String> columnNames = new ArrayList<String>();
- columnNames.add(field.getName());
- metadataFactory.addPrimaryKey(field.getName()+"_PK", columnNames, table);
- }
- }
- else if(sfTypeName.equals(FieldType.PICKLIST)) { // "picklist"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
- if(field.isRestrictedPicklist()) {
- column.setNativeType("restrictedpicklist");
- } else {
- column.setNativeType(sfTypeName);
- }
-
- column.setProperty(COLUMN_PICKLIST_VALUES, getPicklistValues(field));
- }
- else if(sfTypeName.equals(FieldType.MULTIPICKLIST)) { //"multipicklist"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
- if(field.isRestrictedPicklist()) {
- column.setNativeType("restrictedmultiselectpicklist");
- } else {
- column.setNativeType(sfTypeName);
- }
- column.setProperty(COLUMN_PICKLIST_VALUES, getPicklistValues(field));
- }
- else if(sfTypeName.equals(FieldType.BASE_64)) { //"base64"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.BLOB, table);
- column.setNativeType(sfTypeName);
- }
- else if(sfTypeName.equals(FieldType.BOOLEAN)) { //"boolean"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.BOOLEAN, table);
- column.setNativeType(sfTypeName);
- }
- else if(sfTypeName.equals(FieldType.CURRENCY)) { //"currency"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DOUBLE, table);
- column.setNativeType(sfTypeName);
- column.setCurrency(true);
- column.setScale(field.getScale());
- column.setPrecision(field.getPrecision());
- }
- else if(sfTypeName.equals(FieldType.TEXTAREA)) { //"textarea"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
- column.setNativeType(sfTypeName);
- column.setSearchType(SearchType.Unsearchable);
- }
- else if(sfTypeName.equals(FieldType.INT)) { //"int"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.INTEGER, table);
- column.setNativeType(sfTypeName);
- column.setPrecision(field.getPrecision());
- }
- else if(sfTypeName.equals(FieldType.DOUBLE) || //"double"
- sfTypeName.equals(FieldType.PERCENT)) { //"percent"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DOUBLE, table);
- column.setNativeType(sfTypeName);
- column.setScale(field.getScale());
- column.setPrecision(field.getPrecision());
- }
- else if(sfTypeName.equals(FieldType.DATE)) { //"date"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DATE, table);
- column.setNativeType(sfTypeName);
- }
- else if(sfTypeName.equals(FieldType.DATETIME)) { //"datetime"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.TIMESTAMP, table);
- column.setNativeType(sfTypeName);
- }
- else if(sfTypeName.equals(FieldType.TIME)) { //"time"
- column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.TIME, table);
- column.setNativeType(sfTypeName);
- }
- if(null == column) {
- connectorEnv.getLogger().logError("Unknown type returned by SalesForce: " + sfTypeName);
- continue;
- } else {
- column.setNameInSource(field.getName());
- column.setLength(field.getLength());
- if(field.isUpdateable()) {
- column.setUpdatable(true);
- hasUpdateableColumn = true;
- }
- column.setProperty(COLUMN_CALCULATED, String.valueOf(field.isCalculated()));
- column.setProperty(COLUMN_CUSTOM, String.valueOf(field.isCustom()));
- column.setProperty(COLUMN_DEFAULTED, String.valueOf(field.isDefaultedOnCreate()));
- }
-
- }
- }
-
- private String getPicklistValues(Field field) {
- StringBuffer picklistValues = new StringBuffer();
- if(null != field.getPicklistValues() && 0 != field.getPicklistValues().size()) {
- List<PicklistEntry> entries = field.getPicklistValues();
- for (Iterator<PicklistEntry> iterator = entries.iterator(); iterator.hasNext();) {
- PicklistEntry entry = iterator.next();
- picklistValues.append(entry.getValue());
- if(iterator.hasNext()) {
- picklistValues.append(',');
- }
- }
- }
- return picklistValues.toString();
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/NameUtil.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/NameUtil.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/NameUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,85 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- *
- * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
- *
- * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
- */
-package com.metamatrix.connector.salesforce;
-
-import org.teiid.connector.language.SQLReservedWords;
-
-public class NameUtil {
-
- public static String normalizeName( String nameIn ) {
- String normal = nameIn.trim();
- normal = removeDuplicate(normal);
- normal = removeSpaces(normal);
- normal = removeIllegalChars(normal);
- normal = removeTrailingUnderscore(normal);
- normal = removeLeadingUnderscore(normal);
- normal = checkReservedWords(normal);
- return normal;
-
- }
-
- /**
- * @param normal
- * @return
- */
- private static String checkReservedWords( String normal ) {
- if (SQLReservedWords.isReservedWord(normal)) {
- normal = normal + "_"; //$NON-NLS-1$
- }
- return normal;
- }
-
- private static String removeTrailingUnderscore( String normal ) {
- if (normal.endsWith("_")) { //$NON-NLS-1$
- return normal.substring(0, normal.lastIndexOf('_'));
- }
- return normal;
- }
-
- private static String removeIllegalChars( String normal ) {
- String edit = normal;
- edit = edit.replace('.', '_');
- edit = edit.replace('(', '_');
- edit = edit.replace(')', '_');
- edit = edit.replace('/', '_');
- edit = edit.replace('\\', '_');
- edit = edit.replace(':', '_');
- edit = edit.replace('\'', '_');
- edit = edit.replace('-', '_');
- edit = edit.replace("%", "percentage");//$NON-NLS-1$ //$NON-NLS-2$
- edit = edit.replace("#", "number");//$NON-NLS-1$ //$NON-NLS-2$
- edit = edit.replace("$", "_");//$NON-NLS-1$ //$NON-NLS-2$
- edit = edit.replace("{", "_");//$NON-NLS-1$ //$NON-NLS-2$
- edit = edit.replace("}", "_");//$NON-NLS-1$ //$NON-NLS-2$
- return edit;
- }
-
- private static String removeSpaces( String normal ) {
- return normal.replace(' ', '_');
- }
-
- private static String removeDuplicate( String normal ) {
- if (normal.indexOf('(') < 0 || normal.indexOf(')') != normal.length() - 1) return normal;
- String firstPart = normal.substring(0, normal.indexOf('(')).trim();
- String secondPart = normal.substring(normal.indexOf('(') + 1, normal.length() - 1).trim();
- if (firstPart.equals(secondPart) || secondPart.equals("null")) return firstPart; //$NON-NLS-1$
- return normal;
- }
-
- /**
- * @param normal
- * @return
- */
- private static String removeLeadingUnderscore( String normal ) {
- while (normal.indexOf('_') == 0) {
- normal = normal.substring(1);
- }
- return normal;
- }
-
-}
\ No newline at end of file
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Relationship.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Relationship.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Relationship.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,21 +0,0 @@
-package com.metamatrix.connector.salesforce;
-
-public interface Relationship {
-
- void setParentTable(String name);
-
- void setChildTable(String childSObject);
-
- void setForeignKeyField(String field);
-
- void setCascadeDelete(boolean cascadeDelete);
-
- public boolean isCascadeDelete();
-
- public String getChildTable();
-
- public String getForeignKeyField();
-
- public String getParentTable();
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/RelationshipImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/RelationshipImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/RelationshipImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,40 +0,0 @@
-package com.metamatrix.connector.salesforce;
-
-public class RelationshipImpl implements Relationship {
- boolean cascadeDelete;
- public String childTablename;
- public String parentTableName;
- public String foreignKeyField;
-
- public void setCascadeDelete(boolean delete) {
- cascadeDelete = delete;
- }
-
- public boolean isCascadeDelete() {
- return cascadeDelete;
- }
-
- public void setChildTable(String childTable) {
- childTablename = childTable;
- }
-
- public String getChildTable() {
- return childTablename;
- }
-
- public String getForeignKeyField() {
- return foreignKeyField;
- }
-
- public void setForeignKeyField(String foreignKeyField) {
- this.foreignKeyField = foreignKeyField;
- }
-
- public String getParentTable() {
- return parentTableName;
- }
-
- public void setParentTable(String parentTableName) {
- this.parentTableName = parentTableName;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForceManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForceManagedConnectionFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForceManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,101 +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 com.metamatrix.connector.salesforce;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import org.teiid.connector.basic.BasicManagedConnectionFactory;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-
-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 MetaMatrixRuntimeException("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 MetaMatrixRuntimeException("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;
- }
-
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("username=").append(this.username);
- sb.append(" ConnectorStateClass=").append(this.connectorStateClass);
- sb.append(" URL=").append(this.URL);
- return sb.toString();
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForcePlugin.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForcePlugin.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForcePlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,45 +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 com.metamatrix.connector.salesforce;
-
-import java.util.ResourceBundle;
-
-import com.metamatrix.core.BundleUtil;
-
-/**
- * For logging purposes
- */
-public class SalesForcePlugin {
-
- /**
- * The plug-in identifier of this plugin
- */
- public static final String PLUGIN_ID = "com.metamatrix.connector.salesforce" ; //$NON-NLS-1$
-
- /**
- * Provides access to the plugin's log and to it's resources.
- */
- private static final String BUNDLE_NAME = PLUGIN_ID + ".i18n"; //$NON-NLS-1$
- public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,BUNDLE_NAME,ResourceBundle.getBundle(BUNDLE_NAME));
-
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesforceCapabilities.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesforceCapabilities.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesforceCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,95 +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 com.metamatrix.connector.salesforce;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-
-public class SalesforceCapabilities extends BasicConnectorCapabilities {
-
- public int getMaxInCriteriaSize() {
- return 700;
- }
-
- public List getSupportedFunctions() {
- List<String> supportedFunctions = new ArrayList<String>();
- supportedFunctions.add("includes");
- supportedFunctions.add("excludes");
- return supportedFunctions;
- }
-
- public boolean supportsCompareCriteriaEquals() {
- return true;
- }
-
- public boolean supportsInCriteria() {
- return true;
- }
-
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- public boolean supportsRowLimit() {
- return true;
- }
-
- // http://jira.jboss.org/jira/browse/JBEDSP-306
- // Salesforce supports ORDER BY, but not on all column types
- public boolean supportsOrderBy() {
- return false;
- }
-
- @Override
- public boolean supportsAggregatesCountStar() {
- return true;
- }
-
- @Override
- public boolean supportsNotCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsOrCriteria() {
- return true;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return true;
- }
-
- @Override
- public SupportedJoinCriteria getSupportedJoinCriteria() {
- return SupportedJoinCriteria.KEY;
- }
-
- @Override
- public boolean supportsOuterJoins() {
- return true;
- }
-
-
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Util.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Util.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/Util.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,71 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package com.metamatrix.connector.salesforce;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-
-import org.teiid.connector.api.ConnectorException;
-
-
-public class Util {
-
- public static String stripQutes(String id) {
- if((id.startsWith("'") && id.endsWith("'"))) {
- id = id.substring(1,id.length()-1);
- } else if ((id.startsWith("\"") && id.endsWith("\""))) {
- id = id.substring(1,id.length()-1);
- }
- return id;
- }
-
- public static String addSingleQuotes(String text) {
- StringBuffer result = new StringBuffer();
- if(!text.startsWith("'")) {
- result.append('\'');
- }
- result.append(text);
- if(!text.endsWith("'")) {
- result.append('\'');
- }
- return result.toString();
- }
-
- public static void validateQueryLength(StringBuffer query) throws ConnectorException {
- if(query.length() >= 10000) {
- throw new ConnectorException(Messages.getString("Util.query.exceeds.max.length"));
- }
- }
-
- public static SimpleDateFormat getSalesforceDateTimeFormat() {
- return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
- }
-
- public static SimpleDateFormat getTimeZoneOffsetFormat() {
- return new SimpleDateFormat("Z");
- }
-
- public static DateFormat getSalesforceDateFormat() {
- return new SimpleDateFormat("yyyy-MM-dd");
- }
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/SalesforceConnection.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/SalesforceConnection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/SalesforceConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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 com.metamatrix.connector.salesforce.connection;
-
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.MetadataProvider;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.Messages;
-import com.metamatrix.connector.salesforce.MetadataProcessor;
-import com.metamatrix.connector.salesforce.SalesForceManagedConnectionFactory;
-import com.metamatrix.connector.salesforce.connection.impl.ConnectionImpl;
-import com.metamatrix.connector.salesforce.execution.DataPayload;
-import com.metamatrix.connector.salesforce.execution.DeleteExecutionImpl;
-import com.metamatrix.connector.salesforce.execution.DeletedResult;
-import com.metamatrix.connector.salesforce.execution.InsertExecutionImpl;
-import com.metamatrix.connector.salesforce.execution.ProcedureExecutionParentImpl;
-import com.metamatrix.connector.salesforce.execution.QueryExecutionImpl;
-import com.metamatrix.connector.salesforce.execution.UpdateExecutionImpl;
-import com.metamatrix.connector.salesforce.execution.UpdatedResult;
-import com.metamatrix.core.MetaMatrixRuntimeException;
-import com.sforce.soap.partner.DescribeGlobalResult;
-import com.sforce.soap.partner.DescribeSObjectResult;
-import com.sforce.soap.partner.QueryResult;
-import com.sforce.soap.partner.sobject.SObject;
-
-public class SalesforceConnection extends BasicConnection implements MetadataProvider {
-
- private SalesForceManagedConnectionFactory connectorEnv;
- private ConnectionImpl connection;
-
- public SalesforceConnection(Subject subject, SalesForceManagedConnectionFactory env) {
- throw new MetaMatrixRuntimeException("not supported yet..");
- }
-
- public SalesforceConnection(SalesForceManagedConnectionFactory env) throws ConnectorException {
- try {
- connectorEnv = env;
-
- long pingInterval = env.getSourceConnectionTestInterval();
-
- //600000 - 10 minutes
- int timeout = env.getSourceConnectionTimeout();
-
- connection = new ConnectionImpl(env.getUsername(), env.getPassword(), env.getURL(), pingInterval, env.getLogger(), timeout);
- } catch(Throwable t) {
- env.getLogger().logError("SalesforceConnection() ErrorMessage: " + t.getMessage());
- if(t instanceof ConnectorException) {
- // don't wrap it again
- throw (ConnectorException) t;
- }
- throw new ConnectorException(t);
- }
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new QueryExecutionImpl(command, this, metadata, executionContext, connectorEnv);
- }
-
- @Override
- public UpdateExecution createUpdateExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- UpdateExecution result = null;
- if(command instanceof org.teiid.connector.language.Delete) {
- result = new DeleteExecutionImpl(command, this, metadata, executionContext, connectorEnv);
- } else if (command instanceof org.teiid.connector.language.Insert) {
- result = new InsertExecutionImpl(command, this, metadata, executionContext, connectorEnv);
- } else if (command instanceof org.teiid.connector.language.Update) {
- result = new UpdateExecutionImpl(command, this, metadata, executionContext, connectorEnv);
- }
- return result;
-
- }
-
- @Override
- public ProcedureExecution createProcedureExecution(Call command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new ProcedureExecutionParentImpl(command, this, metadata, executionContext, connectorEnv);
- }
-
- @Override
- public void close() {
- }
-
- public QueryResult query(String queryString, int maxBatchSize, Boolean queryAll) throws ConnectorException {
- if(maxBatchSize > 2000) {
- maxBatchSize = 2000;
- connectorEnv.getLogger().logInfo(
- Messages.getString("SalesforceQueryExecutionImpl.reduced.batch.size"));
- }
- return connection.query(queryString, maxBatchSize, queryAll);
- }
-
- public QueryResult queryMore(String queryLocator, int batchSize) throws ConnectorException {
- return connection.queryMore(queryLocator, batchSize);
- }
-
- @Override
- public boolean isAlive() {
- return connection.isAlive();
- }
-
- public int delete(String[] ids) throws ConnectorException {
- return connection.delete(ids);
- }
-
- public int create(DataPayload data) throws ConnectorException {
- return connection.create(data);
- }
-
- public int update(List<DataPayload> updateDataList) throws ConnectorException {
- return connection.update(updateDataList);
- }
-
- public UpdatedResult getUpdated(String objectName, XMLGregorianCalendar startCalendar,
- XMLGregorianCalendar endCalendar) throws ConnectorException {
- return connection.getUpdated(objectName, startCalendar, endCalendar);
- }
-
- public DeletedResult getDeleted(String objectName, XMLGregorianCalendar startCalendar,
- XMLGregorianCalendar endCalendar) throws ConnectorException {
- return connection.getDeleted(objectName, startCalendar, endCalendar);
- }
-
- public QueryResult retrieve(String fieldList, String sObjectType, List<String> ids) throws ConnectorException {
- List<SObject> objects = connection.retrieve(fieldList, sObjectType, ids);
- QueryResult result = new QueryResult();
- result.getRecords().addAll(objects);
- result.setSize(objects.size());
- return result;
- }
-
- public DescribeGlobalResult getObjects() throws ConnectorException {
- return connection.getObjects();
- }
-
- public DescribeSObjectResult getObjectMetaData(String objectName) throws ConnectorException {
- return connection.getObjectMetaData(objectName);
- }
-
- @Override
- public void getConnectorMetadata(MetadataFactory metadataFactory)
- throws ConnectorException {
- MetadataProcessor processor = new MetadataProcessor(this,metadataFactory, connectorEnv);
- processor.processMetadata();
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/AbstractUpdateExecution.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/AbstractUpdateExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/AbstractUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,122 +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 com.metamatrix.connector.salesforce.execution;
-
-import java.util.ArrayList;
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Comparison;
-import org.teiid.connector.language.Condition;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.Util;
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.metamatrix.connector.salesforce.execution.visitors.IQueryProvidingVisitor;
-import com.sforce.soap.partner.QueryResult;
-import com.sforce.soap.partner.sobject.SObject;
-
-/**
- *
- * Parent class to the Update, Delete, and Insert execution classes.
- * Provisions the correct impl and contains some common code to
- * get IDs of Salesforce objects.
- *
- */
-public abstract class AbstractUpdateExecution extends BasicExecution implements UpdateExecution {
-
- protected SalesforceConnection connection;
- protected RuntimeMetadata metadata;
- protected ExecutionContext context;
- protected ConnectorEnvironment connectorEnv;
- protected Command command;
- protected int result;
-
- public AbstractUpdateExecution(Command command, SalesforceConnection salesforceConnection,
- RuntimeMetadata metadata, ExecutionContext context,
- ConnectorEnvironment connectorEnv) {
- this.connection = salesforceConnection;
- this.metadata = metadata;
- this.context = context;
- this.connectorEnv = connectorEnv;
- this.command = command;
- }
-
- @Override
- public void cancel() throws ConnectorException {
- }
-
- @Override
- public void close() throws ConnectorException {
- }
-
- @Override
- public int[] getUpdateCounts() throws DataNotAvailableException,
- ConnectorException {
- return new int[] {result};
- }
-
- public RuntimeMetadata getMetadata() {
- return metadata;
- }
-
- public ConnectorEnvironment getConnectorEnv() {
- return connectorEnv;
- }
-
- public SalesforceConnection getConnection() {
- return connection;
- }
-
- String[] getIDs(Condition criteria, IQueryProvidingVisitor visitor) throws ConnectorException {
- String[] Ids = null;
- if (visitor.hasOnlyIDCriteria()) {
- try {
- String Id = ((Comparison)criteria).getRightExpression().toString();
- Id = Util.stripQutes(Id);
- Ids = new String[] { Id };
- } catch (ClassCastException cce) {
- throw new RuntimeException(
- "Error: The delete criteria is not a CompareCriteria");
- }
-
- } else if (visitor.hasCriteria()) {
- String query = visitor.getQuery();
- QueryResult results = getConnection().query(query, context.getBatchSize(), Boolean.FALSE);
- if (null != results && results.getSize() > 0) {
- ArrayList<String> idList = new ArrayList<String>(results
- .getRecords().size());
- for (int i = 0; i < results.getRecords().size(); i++) {
- SObject sObject = results.getRecords().get(i);
- idList.add(sObject.getId());
- }
- Ids = idList.toArray(new String[0]);
- }
- }
- return Ids;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DataPayload.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DataPayload.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DataPayload.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,65 +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 com.metamatrix.connector.salesforce.execution;
-
-import java.util.List;
-
-import javax.xml.bind.JAXBElement;
-
-/**
- *
- * A bucket to pass data to the Salesforce connection.
- *
- */
-public class DataPayload {
-
- private String type;
- @SuppressWarnings("unchecked")
- private List<JAXBElement> messageElements;
- private String id;
-
- public void setType(String typeName) {
- type = typeName;
- }
-
- @SuppressWarnings("unchecked")
- public void setMessageElements(List<JAXBElement> elements) {
- this.messageElements = elements;
- }
-
- public String getType() {
- return type;
- }
-
- @SuppressWarnings("unchecked")
- public List<JAXBElement> getMessageElements() {
- return messageElements;
- }
-
- public void setID(String id) {
- this.id = id;
- }
-
- public String getID() {
- return id;
- }
-}
\ No newline at end of file
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeleteExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeleteExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeleteExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,53 +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 com.metamatrix.connector.salesforce.execution;
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Delete;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.metamatrix.connector.salesforce.execution.visitors.DeleteVisitor;
-
-public class DeleteExecutionImpl extends AbstractUpdateExecution {
-
-
- public DeleteExecutionImpl(Command command,
- SalesforceConnection salesforceConnection,
- RuntimeMetadata metadata, ExecutionContext context,
- ConnectorEnvironment connectorEnv) {
- super(command, salesforceConnection, metadata, context, connectorEnv);
- }
-
- @Override
- public void execute() throws ConnectorException {
- DeleteVisitor dVisitor = new DeleteVisitor(getMetadata());
- dVisitor.visitNode(command);
- String[] Ids = getIDs(((Delete)command).getWhere(), dVisitor);
- if(null != Ids && Ids.length > 0) {
- result = getConnection().delete(Ids);
- }
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedObject.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedObject.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedObject.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,22 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.util.Calendar;
-
-public class DeletedObject {
-
- String ID;
- Calendar deletedDate;
-
- public String getID() {
- return ID;
- }
- public void setID(String id) {
- ID = id;
- }
- public Calendar getDeletedDate() {
- return deletedDate;
- }
- public void setDeletedDate(Calendar deletedDate) {
- this.deletedDate = deletedDate;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedResult.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedResult.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/DeletedResult.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,36 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.util.Calendar;
-import java.util.List;
-
-public class DeletedResult {
-
- private Calendar latestDateCovered;
- private Calendar earliestDateAvailable;
- private List<DeletedObject> resultRecords;
-
- public Calendar getLatestDateCovered() {
- return latestDateCovered;
- }
-
- public void setLatestDateCovered(Calendar latestDateCovered) {
- this.latestDateCovered = latestDateCovered;
- }
-
-
- public Calendar getEarliestDateAvailable() {
- return earliestDateAvailable;
- }
-
- public void setEarliestDateAvailable(Calendar earliestDateAvailable) {
- this.earliestDateAvailable = earliestDateAvailable;
- }
-
- public void setResultRecords(List<DeletedObject> resultRecords) {
- this.resultRecords = resultRecords;
- }
-
- public List<DeletedObject> getResultRecords() {
- return resultRecords;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetDeletedExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetDeletedExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetDeletedExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,106 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.GregorianCalendar;
-import java.util.List;
-
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.language.Argument;
-import org.teiid.connector.language.Call;
-
-/**
- *
- * The structure of the getDeleted procedure is:
- * Salesforce object type: String: IN param
- * startDate: datatime: IN param
- * enddate: datetime: IN param
- * earliestDateAvailable: datetime: OUT param
- * latestDateCovered: datetime: OUT param
- * getUpdatedResult: resultset: OUT param
- *
- */
-
-public class GetDeletedExecutionImpl implements SalesforceProcedureExecution {
-
- private static final int EARLIESTDATEAVAILABLE = 4;
- private static final int RESULT = 5;
-
- private ProcedureExecutionParent parent;
-
- private DeletedResult deletedResult;
- private int resultIndex = 0;
- DatatypeFactory factory;
-
- public GetDeletedExecutionImpl(
- ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
- this.parent = procedureExecutionParent;
- try {
- factory = DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new ConnectorException(e.getMessage());
- }
- }
-
- @Override
- public void cancel() {
- // nothing to do here
-
- }
-
- @Override
- public void close() {
- // nothing to do here
-
- }
-
- @Override
- public void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
- Call command = parent.getCommand();
- List<Argument> params = command.getArguments();
-
- Argument object = params.get(OBJECT);
- String objectName = (String) object.getArgumentValue().getValue();
-
- Argument start = params.get(STARTDATE);
- Timestamp startTime = (Timestamp) start.getArgumentValue().getValue();
- GregorianCalendar tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
- tempCalendar.setTime(startTime);
- XMLGregorianCalendar startCalendar = factory.newXMLGregorianCalendar(tempCalendar);
-
- Argument end = params.get(ENDDATE);
- Timestamp endTime = (Timestamp) end.getArgumentValue().getValue();
- tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
- tempCalendar.setTime(endTime);
- XMLGregorianCalendar endCalendar = factory.newXMLGregorianCalendar(tempCalendar);
-
- deletedResult = parent.getConnection().getDeleted(objectName, startCalendar, endCalendar);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<?> getOutputParameterValues() {
- List result = new ArrayList();
- result.add(deletedResult.getLatestDateCovered());
- result.add(deletedResult.getEarliestDateAvailable());
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<?> next() {
- List result = null;
- if(deletedResult.getResultRecords() != null && resultIndex < deletedResult.getResultRecords().size()){
- result = new ArrayList(2);
- result.add(deletedResult.getResultRecords().get(resultIndex).getID());
- result.add(deletedResult.getResultRecords().get(resultIndex).getDeletedDate());
- resultIndex++;
- }
- return result;
- }
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetUpdatedExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetUpdatedExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/GetUpdatedExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,99 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.List;
-
-import javax.xml.datatype.DatatypeConfigurationException;
-import javax.xml.datatype.DatatypeFactory;
-import javax.xml.datatype.XMLGregorianCalendar;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.language.Argument;
-import org.teiid.connector.language.Call;
-
-/**
- *
- * The structure of the getUpdated procedure is:
- * Salesforce object type: String: IN param
- * startDate: datatime: IN param
- * enddate: datetime: IN param
- * latestDateCovered: datetime: OUT param
- * getUpdatedResult: resultset: OUT param
- *
- */
-
-public class GetUpdatedExecutionImpl implements SalesforceProcedureExecution {
-
- private static final int RESULT = 4;
-
- private ProcedureExecutionParent parent;
- private UpdatedResult updatedResult;
- private int idIndex = 0;
- DatatypeFactory factory;
-
- public GetUpdatedExecutionImpl(
- ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
- this.parent = procedureExecutionParent;
- try {
- factory = DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new ConnectorException(e.getMessage());
- }
- }
-
- @Override
- public void cancel() {
- // nothing to do here
- }
-
- @Override
- public void close() {
- // nothing to do here
- }
-
- @Override
- public void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
- Call command = parent.getCommand();
- List<Argument> params = command.getArguments();
-
- Argument object = params.get(OBJECT);
- String objectName = (String) object.getArgumentValue().getValue();
-
- Argument start = params.get(STARTDATE);
- Timestamp startTime = (Timestamp) start.getArgumentValue().getValue();
- GregorianCalendar tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
- tempCalendar.setTime(startTime);
- XMLGregorianCalendar startCalendar = factory.newXMLGregorianCalendar(tempCalendar);
-
- Argument end = params.get(ENDDATE);
- Timestamp endTime = (Timestamp) end.getArgumentValue().getValue();
- tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
- tempCalendar.setTime(endTime);
- XMLGregorianCalendar endCalendar = factory.newXMLGregorianCalendar(tempCalendar);
-
- updatedResult = parent.getConnection().getUpdated(objectName, startCalendar, endCalendar);
- }
-
- @Override
- public List<Calendar> getOutputParameterValues() {
- List<Calendar> result = new ArrayList<Calendar>(1);
- result.add(updatedResult.getLatestDateCovered());
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List next() {
- List result = null;
- if(updatedResult.getIDs() != null && idIndex < updatedResult.getIDs().size()){
- result = new ArrayList(1);
- result.add(updatedResult.getIDs().get(idIndex));
- idIndex++;
- }
- return result;
- }
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/InsertExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/InsertExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/InsertExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,53 +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 com.metamatrix.connector.salesforce.execution;
-
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Insert;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.metamatrix.connector.salesforce.execution.visitors.InsertVisitor;
-
-public class InsertExecutionImpl extends AbstractUpdateExecution {
-
- public InsertExecutionImpl(Command command,
- SalesforceConnection salesforceConnection,
- RuntimeMetadata metadata, ExecutionContext context,
- ConnectorEnvironment connectorEnv) {
- super(command, salesforceConnection, metadata, context, connectorEnv);
- }
-
- @Override
- public void execute() throws ConnectorException {
- InsertVisitor visitor = new InsertVisitor(getMetadata());
- visitor.visit((Insert)command);
- DataPayload data = new DataPayload();
- data.setType(visitor.getTableName());
- data.setMessageElements(visitor.getMessageElements());
- result = getConnection().create(data);
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParent.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParent.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParent.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,22 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-
-public interface ProcedureExecutionParent {
-
- public Call getCommand();
-
- public ExecutionContext getExecutionContext();
-
- public RuntimeMetadata getMetadata();
-
- public SalesforceConnection getConnection();
-
- public ConnectorEnvironment getConectorEnvironment();
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParentImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParentImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/ProcedureExecutionParentImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,105 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-
-public class ProcedureExecutionParentImpl implements ProcedureExecution, ProcedureExecutionParent {
-
- private Call command;
- private ExecutionContext executionContext;
- private RuntimeMetadata metadata;
- private SalesforceProcedureExecution execution;
- private SalesforceConnection connection;
- private ConnectorEnvironment connectorEnv;
-
- public ProcedureExecutionParentImpl(Call command,
- SalesforceConnection connection, RuntimeMetadata metadata, ExecutionContext executionContext, ConnectorEnvironment connectorEnv) {
- this.setCommand(command);
- this.setConnection(connection);
- this.setMetadata(metadata);
- this.setExecutionContext(executionContext);
- this.setConnectorEnvironment(connectorEnv);
- }
-
- @Override
- public List<?> getOutputParameterValues() throws ConnectorException {
- return execution.getOutputParameterValues();
- }
-
- @Override
- public List<?> next() throws ConnectorException, DataNotAvailableException {
- return execution.next();
- }
-
- @Override
- public void cancel() throws ConnectorException {
- execution.cancel();
- }
-
- @Override
- public void close() throws ConnectorException {
- execution.close();
- }
-
- @Override
- public void execute() throws ConnectorException {
- if(getCommand().getProcedureName().endsWith("getUpdated")) {
- execution = new GetUpdatedExecutionImpl(this);
- execution.execute(this);
- }
- else if(getCommand().getProcedureName().endsWith("getDeleted")) {
- execution = new GetDeletedExecutionImpl(this);
- execution.execute(this);
- }
- }
-
- public void setCommand(Call command) {
- this.command = command;
- }
-
- public Call getCommand() {
- return command;
- }
-
- private void setConnection(SalesforceConnection connection) {
- this.connection = connection;
- }
-
- public SalesforceConnection getConnection() {
- return connection;
- }
-
- private void setExecutionContext(ExecutionContext executionContext) {
- this.executionContext = executionContext;
- }
-
- public ExecutionContext getExecutionContext() {
- return executionContext;
- }
-
- private void setMetadata(RuntimeMetadata metadata) {
- this.metadata = metadata;
- }
-
- public RuntimeMetadata getMetadata() {
- return metadata;
- }
-
- private void setConnectorEnvironment(ConnectorEnvironment connectorEnv) {
- this.connectorEnv = connectorEnv;
- }
-
- public ConnectorEnvironment getConectorEnvironment() {
- return connectorEnv;
- }
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/QueryExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/QueryExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/QueryExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,376 +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 com.metamatrix.connector.salesforce.execution;
-
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Element;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.AggregateFunction;
-import org.teiid.connector.language.Join;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.language.TableReference;
-import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-import org.teiid.connector.metadata.runtime.Table;
-
-import com.metamatrix.connector.salesforce.Messages;
-import com.metamatrix.connector.salesforce.Util;
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.metamatrix.connector.salesforce.execution.visitors.JoinQueryVisitor;
-import com.metamatrix.connector.salesforce.execution.visitors.SelectVisitor;
-import com.sforce.soap.partner.QueryResult;
-import com.sforce.soap.partner.sobject.SObject;
-
-public class QueryExecutionImpl extends BasicExecution implements ResultSetExecution {
-
- private SalesforceConnection connection;
-
- private RuntimeMetadata metadata;
-
- private ExecutionContext context;
-
- private ConnectorEnvironment connectorEnv;
-
- private SelectVisitor visitor;
-
- private QueryResult results;
-
- private List<List<Object>> resultBatch;
-
- // Identifying values
- private String connectionIdentifier;
-
- private String connectorIdentifier;
-
- private String requestIdentifier;
-
- private String partIdentifier;
-
- private String logPreamble;
-
- private QueryExpression query;
-
- Map<String, Map<String,Integer>> sObjectToResponseField = new HashMap<String, Map<String,Integer>>();
-
- private int topResultIndex = 0;
-
- public QueryExecutionImpl(QueryExpression command, SalesforceConnection connection,
- RuntimeMetadata metadata, ExecutionContext context,
- ConnectorEnvironment connectorEnv) {
- this.connection = connection;
- this.metadata = metadata;
- this.context = context;
- this.connectorEnv = connectorEnv;
- this.query = command;
-
- connectionIdentifier = context.getConnectionIdentifier();
- connectorIdentifier = context.getConnectorIdentifier();
- requestIdentifier = context.getRequestIdentifier();
- partIdentifier = context.getPartIdentifier();
- }
-
- public void cancel() throws ConnectorException {
- connectorEnv.getLogger().logInfo(Messages.getString("SalesforceQueryExecutionImpl.cancel"));
- }
-
- public void close() throws ConnectorException {
- connectorEnv.getLogger().logInfo(Messages.getString("SalesforceQueryExecutionImpl.close"));
- }
-
- @Override
- public void execute() throws ConnectorException {
- connectorEnv.getLogger().logInfo(
- getLogPreamble() + "Incoming Query: " + query.toString());
- List<TableReference> from = ((Select)query).getFrom();
- String finalQuery;
- if(from.get(0) instanceof Join) {
- visitor = new JoinQueryVisitor(metadata);
- visitor.visitNode(query);
- finalQuery = visitor.getQuery().trim();
- connectorEnv.getLogger().logInfo(
- getLogPreamble() + "Executing Query: " + finalQuery);
-
- results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
- } else {
- visitor = new SelectVisitor(metadata);
- visitor.visitNode(query);
- if(visitor.canRetrieve()) {
- results = connection.retrieve(visitor.getRetrieveFieldList(),
- visitor.getTableName(), visitor.getIdInCriteria());
- } else {
- finalQuery = visitor.getQuery().trim();
- connectorEnv.getLogger().logInfo(
- getLogPreamble() + "Executing Query: " + finalQuery);
- results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public List next() throws ConnectorException, DataNotAvailableException {
- List<?> result;
- if (query.getProjectedQuery().getDerivedColumns().get(0)
- .getExpression() instanceof AggregateFunction) {
- result = Arrays.asList(results.getSize());
- results = null;
-
- } else {
- result = getRow(results);
- }
- return result;
- }
-
- private List<Object> getRow(QueryResult result) throws ConnectorException {
- List<Object> row;
- if(null == resultBatch) {
- loadBatch();
- }
- if(resultBatch.size() == topResultIndex) {
- row = null;
- } else {
- row = resultBatch.get(topResultIndex);
- topResultIndex++;
- if(resultBatch.size() == topResultIndex) {
- if(!result.isDone()) {
- loadBatch();
- }
- }
-
- }
- return row;
- }
-
- private void loadBatch() throws ConnectorException {
- if(null != resultBatch) { // if we have an old batch, then we have to get new results
- results = connection.queryMore(results.getQueryLocator(), context.getBatchSize());
- }
- resultBatch = new ArrayList<List<Object>>();
-
- for(int resultIndex = 0; resultIndex < results.getSize(); resultIndex++) {
- SObject sObject = results.getRecords().get(resultIndex);
- List<Object[]> result = getObjectData(sObject);
- for(Iterator<Object[]> i = result.iterator(); i.hasNext(); ) {
- resultBatch.add(Arrays.asList(i.next()));
- }
- }
- }
-
- private List<Object[]> getObjectData(SObject sObject) throws ConnectorException {
- List<Object> topFields = sObject.getAny();
- logAndMapFields(sObject.getType(), topFields);
- List<Object[]> result = new ArrayList<Object[]>();
- for(int i = 0; i < topFields.size(); i++) {
- Element element = (Element) topFields.get(i);
- QName qName = new QName(element.getNamespaceURI(), element.getLocalName());
- if(null != qName) {
- String type = qName.getLocalPart();
- if(type.equals("sObject")) {
- //SObject parent = (SObject)element.;
- //result.addAll(getObjectData(parent));
- } else if(type.equals("QueryResult")) {
- //QueryResult subResult = (QueryResult)element.getValue();
- //for(int resultIndex = 0; resultIndex < subResult.getSize(); resultIndex++) {
- // SObject subObject = subResult.getRecords().get(resultIndex);
- // result.addAll(getObjectData(subObject));
- //}
- }
- }
- }
- return extractDataFromFields(sObject, topFields, result);
-
- }
-
- private List<Object[]> extractDataFromFields(SObject sObject,
- List<Object> fields, List<Object[]> result) throws ConnectorException {
- Map<String,Integer> fieldToIndexMap = sObjectToResponseField.get(sObject.getType());
- for (int j = 0; j < visitor.getSelectSymbolCount(); j++) {
- Column element = visitor.getSelectSymbolMetadata(j);
- AbstractMetadataRecord parent = element.getParent();
- Table table;
- if(parent instanceof Table) {
- table = (Table)parent;
- } else {
- parent = parent.getParent();
- if(parent instanceof Table) {
- table = (Table)parent;
- } else {
- throw new ConnectorException("Could not resolve Table for column " + element.getName());
- }
- }
- if(table.getNameInSource().equals(sObject.getType())) {
- Integer index = fieldToIndexMap.get(element.getNameInSource());
- // id gets dropped from the result if it is not the
- // first field in the querystring. Add it back in.
- if (null == index) {
- if (element.getNameInSource().equalsIgnoreCase("id")) {
- setValueInColumn(j, sObject.getId(), result);
- } else {
- throw new ConnectorException("SalesforceQueryExecutionImpl.missing.field"
- + element.getNameInSource());
- }
- } else {
- Object cell;
- cell = getCellDatum(element, (Element)fields.get(index));
- setValueInColumn(j, cell, result);
- }
- }
- }
- return result;
- }
-
- private void setValueInColumn(int columnIndex, Object value, List<Object[]> result) {
- if(result.isEmpty()) {
- Object[] row = new Object[visitor.getSelectSymbolCount()];
- result.add(row);
- }
- Iterator<Object[]> iter = result.iterator();
- while (iter.hasNext()) {
- Object[] row = iter.next();
- row[columnIndex] = value;
- }
- }
-
- /**
- * Load the map of response field names to index.
- * @param fields
- * @throws ConnectorException
- */
- private void logAndMapFields(String sObjectName,
- List<Object> fields) throws ConnectorException {
- if (!sObjectToResponseField.containsKey(sObjectName)) {
- logFields(sObjectName, fields);
- Map<String, Integer> responseFieldToIndexMap;
- responseFieldToIndexMap = new HashMap<String, Integer>();
- for (int x = 0; x < fields.size(); x++) {
- Element element = (Element) fields.get(x);
- responseFieldToIndexMap.put(element.getLocalName(), x);
- }
- sObjectToResponseField.put(sObjectName, responseFieldToIndexMap);
- }
- }
-
- private void logFields(String sObjectName, List<Object> fields) throws ConnectorException {
- ConnectorLogger logger = connectorEnv.getLogger();
- logger.logDetail("SalesForce Object Name = " + sObjectName);
- logger.logDetail("FieldCount = " + fields.size());
- for(int i = 0; i < fields.size(); i++) {
- Element element;
- element = (Element) fields.get(i);
- logger.logDetail("Field # " + i + " is " + element.getLocalName());
- }
-
- }
-
- @SuppressWarnings("unchecked")
- private Object getCellDatum(Column element, Element elem)
- throws ConnectorException {
- if(!element.getNameInSource().equals(elem.getLocalName())) {
- throw new ConnectorException("SalesforceQueryExecutionImpl.column.mismatch1" + element.getNameInSource() +
- "SalesforceQueryExecutionImpl.column.mismatch2" + elem.getLocalName());
- }
- String value = (String) elem.getTextContent();
- Object result = null;
- Class type = element.getJavaType();
-
- if(type.equals(String.class)) {
- result = value;
- }
- else if (type.equals(Boolean.class)) {
- result = Boolean.valueOf(value);
- } else if (type.equals(Double.class)) {
- if (null != value) {
- if(value.isEmpty()) {
- result = null;
- } else {
- result = Double.valueOf(value);
- }
- }
- } else if (type.equals(Integer.class)) {
- if (null != value) {
- if(value.isEmpty()) {
- result = null;
- } else {
- result = Integer.valueOf(value);
- }
- }
- } else if (type.equals(java.sql.Date.class)) {
- if (null != value) {
- if(value.isEmpty()) {
- result = null;
- } else {
- result = java.sql.Date.valueOf(value);
- }
- }
- } else if (type.equals(java.sql.Timestamp.class)) {
- if (null != value) {
- if(value.isEmpty()) {
- result = null;
- } else try {
- Date date = Util.getSalesforceDateTimeFormat().parse(value);
- result = new Timestamp(date.getTime());
- } catch (ParseException e) {
- throw new ConnectorException(e, "SalesforceQueryExecutionImpl.datatime.parse" + value);
- }
- }
- } else {
- result = value;
- }
- return result;
- }
-
-
- private String getLogPreamble() {
- if (null == logPreamble) {
- StringBuffer preamble = new StringBuffer();
- preamble.append(connectorIdentifier);
- preamble.append('.');
- preamble.append(connectionIdentifier);
- preamble.append('.');
- preamble.append(requestIdentifier);
- preamble.append('.');
- preamble.append(partIdentifier);
- preamble.append(": ");
- logPreamble = preamble.toString();
- }
- return logPreamble;
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/SalesforceProcedureExecution.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/SalesforceProcedureExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/SalesforceProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,24 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorException;
-
-public interface SalesforceProcedureExecution {
-
- static final int OBJECT = 0;
- static final int STARTDATE = 1;
- static final int ENDDATE = 2;
- static final int LATESTDATECOVERED = 3;
-
- List<?> getOutputParameterValues();
-
- List<?> next();
-
- void cancel();
-
- void close();
-
- void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException;
-
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdateExecutionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdateExecutionImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdateExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,88 +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 com.metamatrix.connector.salesforce.execution;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.JAXBElement;
-import javax.xml.namespace.QName;
-
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.ColumnReference;
-import org.teiid.connector.language.Literal;
-import org.teiid.connector.language.SetClause;
-import org.teiid.connector.language.Update;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.connector.salesforce.Util;
-import com.metamatrix.connector.salesforce.connection.SalesforceConnection;
-import com.metamatrix.connector.salesforce.execution.visitors.UpdateVisitor;
-
-public class UpdateExecutionImpl extends AbstractUpdateExecution {
-
- @SuppressWarnings("unchecked")
- private static final Class stringClazz = new String().getClass();
-
- public UpdateExecutionImpl(Command command,
- SalesforceConnection salesforceConnection,
- RuntimeMetadata metadata, ExecutionContext context,
- ConnectorEnvironment connectorEnv) {
- super(command, salesforceConnection, metadata, context, connectorEnv);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void execute() throws ConnectorException {
- UpdateVisitor visitor = new UpdateVisitor(getMetadata());
- visitor.visit((Update)command);
- String[] Ids = getIDs(((Update)command).getWhere(), visitor);
-
- if (null != Ids && Ids.length > 0) {
- List<JAXBElement> elements = new ArrayList<JAXBElement>();
- for (SetClause clause : ((Update)command).getChanges()) {
- ColumnReference element = clause.getSymbol();
- Column column = element.getMetadataObject();
- String val = ((Literal) clause.getValue())
- .toString();
- JAXBElement messageElem = new JAXBElement(new QName(
- column.getNameInSource()), stringClazz, Util.stripQutes(val));
- elements.add(messageElem);
- }
-
- List<DataPayload> updateDataList = new ArrayList<DataPayload>();
- for (int i = 0; i < Ids.length; i++) {
- DataPayload data = new DataPayload();
- data.setType(visitor.getTableName());
- data.setID(Ids[i]);
- data.setMessageElements(elements);
- updateDataList.add(data);
- }
-
- result = getConnection().update(updateDataList);
- }
- }
-}
Deleted: trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdatedResult.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdatedResult.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/execution/UpdatedResult.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,26 +0,0 @@
-package com.metamatrix.connector.salesforce.execution;
-
-import java.util.Calendar;
-import java.util.List;
-
-public class UpdatedResult {
-
- private Calendar latestDateCovered;
- private List<String> IDs;
-
- public Calendar getLatestDateCovered() {
- return latestDateCovered;
- }
-
- public void setLatestDateCovered(Calendar latestDateCovered) {
- this.latestDateCovered = latestDateCovered;
- }
-
- public List<String> getIDs() {
- return IDs;
- }
-
- public void setIDs(List<String> list) {
- this.IDs = list;
- }
-}
Copied: trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce (from rev 2083, trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/impl)
Deleted: trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/ConnectionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/connection/impl/ConnectionImpl.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/ConnectionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,367 +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 com.metamatrix.connector.salesforce.connection.impl;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.xml.datatype.XMLGregorianCalendar;
-import javax.xml.ws.BindingProvider;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-
-import com.metamatrix.connector.salesforce.execution.DataPayload;
-import com.metamatrix.connector.salesforce.execution.DeletedObject;
-import com.metamatrix.connector.salesforce.execution.DeletedResult;
-import com.metamatrix.connector.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 ConnectionImpl {
- private SforceService sfService;
- private Soap sfSoap;
- private SessionHeader sh;
- private CallOptions co;
- private ConnectorLogger logger;
-
- private ObjectFactory partnerFactory = new ObjectFactory();
-
- PackageVersionHeader pvHeader = partnerFactory.createPackageVersionHeader();
-
- public ConnectionImpl(String username, String password, URL url, long pingInterval, ConnectorLogger logger, int timeout) throws ConnectorException {
- this.logger = logger;
- login(username, password, url, timeout);
- }
-
- String getUserName() throws ConnectorException {
- try {
- return sfSoap.getUserInfo(sh).getUserName();
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e.getMessage());
- }
- }
-
- Soap getBinding() {
- return sfSoap;
- }
-
- private void login(String username, String password, URL url, int timeout)
- throws ConnectorException {
- if (!isAlive()) {
- LoginResult loginResult = null;
- sfSoap = null;
- sfService = null;
- co = new CallOptions();
- co.setClient("RedHat/MetaMatrix/");
-
- 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 ConnectorException(e.getCause().getMessage());
- } catch (InvalidIdFault e) {
- throw new ConnectorException(e.getCause().getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e.getCause().getMessage());
- }
- logger.logTrace("Login was successful for username " + username);
-
- 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 ConnectorException(e.getMessage());
- }
- }
- }
-
-
- public boolean isAlive() {
- boolean result = true;
- if(sfSoap == null) {
- result = false;
- } else {
- try {
- sfSoap.getServerTimestamp(sh);
- } catch (Throwable t) {
- logger.logDetail("Caught Throwable in isAlive", t);
- result = false;
- }
- }
- return result;
- }
-
- public QueryResult query(String queryString, int batchSize, Boolean queryAll) throws ConnectorException {
- 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 ConnectorException(e, e.getMessage());
- } catch (MalformedQueryFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (InvalidIdFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- return qr;
- }
-
- public QueryResult queryMore(String queryLocator, int batchSize) throws ConnectorException {
- QueryOptions qo = partnerFactory.createQueryOptions();
- qo.setBatchSize(batchSize);
- try {
- return sfSoap.queryMore(queryLocator, sh);
- } catch (InvalidFieldFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
-
- }
-
- public int delete(String[] ids) throws ConnectorException {
- List<DeleteResult> results = null;
- try {
- results = sfSoap.delete(Arrays.asList(ids), sh);
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
-
- 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: ");
- 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 ConnectorException(errorMessages.toString());
- }
- return results.size();
- }
-
- public int create(DataPayload data) throws ConnectorException {
- 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 ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (InvalidIdFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- return analyzeResult(result);
- }
-
- public int update(List<DataPayload> updateDataList) throws ConnectorException {
- 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 ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (InvalidIdFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- return analyzeResult(result);
- }
-
- private int analyzeResult(List<SaveResult> results) throws ConnectorException {
- for (SaveResult result : results) {
- if(!result.isSuccess()) {
- throw new ConnectorException(result.getErrors().get(0).getMessage());
- }
- }
- return results.size();
- }
-
- public UpdatedResult getUpdated(String objectType, XMLGregorianCalendar startDate, XMLGregorianCalendar endDate) throws ConnectorException {
- GetUpdatedResult updated;
- try {
- updated = sfSoap.getUpdated(objectType, startDate, endDate, sh);
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- 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 ConnectorException {
- GetDeletedResult deleted;
- try {
- deleted = sfSoap.getDeleted(objectName, startCalendar, endCalendar, sh);
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- 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 List<SObject> retrieve(String fieldList, String sObjectType, List<String> ids) throws ConnectorException {
- try {
- return sfSoap.retrieve(fieldList, sObjectType, ids, sh);
- } catch (InvalidFieldFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (MalformedQueryFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (InvalidIdFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
-
- }
-
- public DescribeGlobalResult getObjects() throws ConnectorException {
- try {
- return sfSoap.describeGlobal(sh);
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- ConnectorException ce = new ConnectorException(e.getCause().getMessage());
- ce.initCause(e.getCause());
- throw ce;
- }
- }
-
- public DescribeSObjectResult getObjectMetaData(String objectName) throws ConnectorException {
- try {
- return sfSoap.describeSObject(objectName, sh);
- } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
- throw new ConnectorException(e, e.getMessage());
- } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
- throw new ConnectorException(e, e.getMessage());
- }
- }
-}
Copied: trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesForceManagedConnectionFactory.java (from rev 2083, trunk/connectors/connector-salesforce/src/main/java/com/metamatrix/connector/salesforce/SalesForceManagedConnectionFactory.java)
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesForceManagedConnectionFactory.java (rev 0)
+++ trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesForceManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,107 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci.salesforce;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
+import com.metamatrix.core.MetaMatrixRuntimeException;
+
+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 MetaMatrixRuntimeException("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 MetaMatrixRuntimeException("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 Object createConnectionFactory() throws ResourceException {
+ return new BasicConnectionFactory() {
+ @Override
+ public Connection getConnection() throws ResourceException {
+ return new SalesforceConnectionImpl(getUsername(), getPassword(), getURL(), getSourceConnectionTestInterval(), getSourceConnectionTimeout());
+ }
+ };
+ }
+}
Added: trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesforceConnectionImpl.java
===================================================================
--- trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesforceConnectionImpl.java (rev 0)
+++ trunk/connectors/connector-salesforce/src/main/java/org/teiid/resource/cci/salesforce/SalesforceConnectionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,383 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci.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.ConnectorException;
+import org.teiid.resource.adapter.salesforce.Messages;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.execution.DataPayload;
+import org.teiid.resource.adapter.salesforce.execution.DeletedObject;
+import org.teiid.resource.adapter.salesforce.execution.DeletedResult;
+import org.teiid.resource.adapter.salesforce.execution.UpdatedResult;
+import org.teiid.resource.spi.BasicConnection;
+
+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 ConnectorException {
+ login(username, password, url, timeout);
+ }
+
+ String getUserName() throws ConnectorException {
+ try {
+ return sfSoap.getUserInfo(sh).getUserName();
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e.getMessage());
+ }
+ }
+
+ Soap getBinding() {
+ return sfSoap;
+ }
+
+ private void login(String username, String password, URL url, int timeout)
+ throws ConnectorException {
+ if (!isAlive()) {
+ 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 ConnectorException(e.getCause().getMessage());
+ } catch (InvalidIdFault e) {
+ throw new ConnectorException(e.getCause().getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e.getCause().getMessage());
+ }
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Login was successful for username " + username);
+
+ 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 ConnectorException(e.getMessage());
+ }
+ }
+ }
+
+
+ public boolean isAlive() {
+ 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 ConnectorException {
+
+ if(batchSize > 2000) {
+ batchSize = 2000;
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, Messages.getString("SalesforceQueryExecutionImpl.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 ConnectorException(e, e.getMessage());
+ } catch (MalformedQueryFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (InvalidIdFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ return qr;
+ }
+
+ public QueryResult queryMore(String queryLocator, int batchSize) throws ConnectorException {
+ QueryOptions qo = partnerFactory.createQueryOptions();
+ qo.setBatchSize(batchSize);
+ try {
+ return sfSoap.queryMore(queryLocator, sh);
+ } catch (InvalidFieldFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidQueryLocatorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+
+ }
+
+ public int delete(String[] ids) throws ConnectorException {
+ List<DeleteResult> results = null;
+ try {
+ results = sfSoap.delete(Arrays.asList(ids), sh);
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+
+ 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: ");
+ 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 ConnectorException(errorMessages.toString());
+ }
+ return results.size();
+ }
+
+ public int create(DataPayload data) throws ConnectorException {
+ 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 ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (InvalidIdFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ return analyzeResult(result);
+ }
+
+ public int update(List<DataPayload> updateDataList) throws ConnectorException {
+ 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 ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (InvalidIdFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ return analyzeResult(result);
+ }
+
+ private int analyzeResult(List<SaveResult> results) throws ConnectorException {
+ for (SaveResult result : results) {
+ if(!result.isSuccess()) {
+ throw new ConnectorException(result.getErrors().get(0).getMessage());
+ }
+ }
+ return results.size();
+ }
+
+ public UpdatedResult getUpdated(String objectType, XMLGregorianCalendar startDate, XMLGregorianCalendar endDate) throws ConnectorException {
+ GetUpdatedResult updated;
+ try {
+ updated = sfSoap.getUpdated(objectType, startDate, endDate, sh);
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ 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 ConnectorException {
+ GetDeletedResult deleted;
+ try {
+ deleted = sfSoap.getDeleted(objectName, startCalendar, endCalendar, sh);
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ 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 ConnectorException {
+ 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 ConnectorException(e, e.getMessage());
+ } catch (MalformedQueryFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (InvalidIdFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+
+ }
+
+ public DescribeGlobalResult getObjects() throws ConnectorException {
+ try {
+ return sfSoap.describeGlobal(sh);
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ ConnectorException ce = new ConnectorException(e.getCause().getMessage());
+ ce.initCause(e.getCause());
+ throw ce;
+ }
+ }
+
+ public DescribeSObjectResult getObjectMetaData(String objectName) throws ConnectorException {
+ try {
+ return sfSoap.describeSObject(objectName, sh);
+ } catch (com.sforce.soap.partner.InvalidSObjectFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ } catch (com.sforce.soap.partner.UnexpectedErrorFault e) {
+ throw new ConnectorException(e, e.getMessage());
+ }
+ }
+
+ @Override
+ public void close() throws ResourceException {
+
+ }
+}
Modified: trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/main/rar/META-INF/ra.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,56 +34,13 @@
<license-required>true</license-required>
</license>
<resourceadapter>
- <resourceadapter-class>org.teiid.connector.basic.BasicResourceAdapter</resourceadapter-class>
+ <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
<outbound-resourceadapter>
<connection-definition>
- <managedconnectionfactory-class>com.metamatrix.connector.salesforce.SalesForceManagedConnectionFactory</managedconnectionfactory-class>
+ <managedconnectionfactory-class>org.teiid.resource.cci.salesforce.SalesForceManagedConnectionFactory</managedconnectionfactory-class>
<config-property>
- <description>{$display:"Connector Class",$advanced:"true"}</description>
- <config-property-name>ConnectorClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.salesforce.Connector</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Connector Capabilities",$description:"The class to use to provide the Connector Capabilities",$advanced:"true"}</description>
- <config-property-name>CapabilitiesClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.salesforce.SalesforceCapabilities</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is Immutable",$description:"Is Immutable, True if the source never changes.",$advanced:"true"}</description>
- <config-property-name>Immutable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is XA Capable",$description:"True, if this connector supports XA Transactions",$advanced:"true"}</description>
- <config-property-name>XaCapable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Exception on Exceeding Max Rows",$description:"Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",$advanced:"true"}</description>
- <config-property-name>ExceptionOnMaxRows</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Maximum Result Rows",$description:"Maximum Result Rows allowed",$advanced:"true"}</description>
- <config-property-name>MaxResultRows</config-property-name>
- <config-property-type>java.lang.Integer</config-property-type>
- <config-property-value>-1</config-property-value>
- </config-property>
-
- <!-- Salesforce Specific properties -->
- <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>
@@ -96,13 +53,6 @@
</config-property>
<config-property>
- <description>{$display:"Connector State Class",$description:"",$required:"true",$advanced:"true"}</description>
- <config-property-name>ConnectorStateClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.salesforce.ConnectorState</config-property-value>
- </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>
@@ -122,17 +72,10 @@
<config-property-value>120000</config-property-value>
</config-property>
- <config-property>
- <description>{$display:"Audit Model Fields",$advanced:"true"}</description>
- <config-property-name>ModelAuditFields</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <connectionfactory-interface>org.teiid.connector.api.Connector</connectionfactory-interface>
- <connectionfactory-impl-class>org.teiid.connector.basic.WrappedConnector</connectionfactory-impl-class>
- <connection-interface>org.teiid.connector.api.Connection</connection-interface>
- <connection-impl-class>org.teiid.connector.basic.WrappedConnection</connection-impl-class>
+ <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>
Deleted: trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/execution/visitors/TestVisitors.java
===================================================================
--- trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/execution/visitors/TestVisitors.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-salesforce/src/test/java/com/metamatrix/connector/salesforce/execution/visitors/TestVisitors.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,164 +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 com.metamatrix.connector.salesforce.execution.visitors;
-
-import static org.junit.Assert.*;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.junit.Test;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.MetadataStore;
-import org.teiid.connector.metadata.runtime.Schema;
-import org.teiid.connector.metadata.runtime.Table;
-import org.teiid.connector.metadata.runtime.Column.SearchType;
-import org.teiid.metadata.CompositeMetadataStore;
-import org.teiid.metadata.TransformationMetadata;
-
-import com.metamatrix.cdk.api.TranslationUtility;
-import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.query.metadata.QueryMetadataInterface;
-import com.metamatrix.query.unittest.RealMetadataFactory;
-
-public class TestVisitors {
-
- public static QueryMetadataInterface exampleSalesforce() {
- MetadataStore store = new MetadataStore();
- // Create models
- Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
-
- // Create Account group
- Table accounTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
- accounTable.setNameInSource("Account"); //$NON-NLS-1$
- accounTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
- // Create Account Columns
- String[] acctNames = new String[] {
- "ID", "Name", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
- String[] acctTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
- };
-
- List<Column> acctCols = RealMetadataFactory.createElements(accounTable, acctNames, acctTypes);
- acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
- acctCols.get(2).setSearchType(SearchType.Like_Only);
- // Set name in source on each column
- String[] accountNameInSource = new String[] {
- "id", "AccountName", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- };
- for(int i=0; i<2; i++) {
- Column obj = acctCols.get(i);
- obj.setNameInSource(accountNameInSource[i]);
- }
-
- // Create Contact group
- Table contactTable = RealMetadataFactory.createPhysicalGroup("Contact", salesforceModel); //$NON-NLS-1$
- contactTable.setNameInSource("Contact"); //$NON-NLS-1$
- contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
- // Create Contact Columns
- String[] elemNames = new String[] {
- "ContactID", "Name", "AccountId" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- String[] elemTypes = new String[] {
- DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
- };
-
- List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
- // Set name in source on each column
- String[] contactNameInSource = new String[] {
- "id", "ContactName", "accountid" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
- for(int i=0; i<2; i++) {
- Column obj = contactCols.get(i);
- obj.setNameInSource(contactNameInSource[i]);
- }
- return new TransformationMetadata(null, new CompositeMetadataStore(store), null, null);
- }
-
- private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
-
- @Test public void testOr() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testNot() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testCountStart() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testNotLike() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
-
- @Test public void testIN() throws Exception {
- Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertFalse(visitor.hasOnlyIDCriteria());
- assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
-
- }
-
- @Test public void testOnlyIDsIN() throws Exception {
- // this can resolve to a better performing retrieve call
- Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
- SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertTrue(visitor.hasOnlyIdInCriteria());
- assertEquals("Account", visitor.getTableName());
- assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
- assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());
- }
-
- @Test public void testJoin() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contact.Name FROM Contact LEFT OUTER JOIN Account ON Account.Id = Contact.AccountId"); //$NON-NLS-1$
- SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
- @Test public void testJoin2() throws Exception {
- Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contact.Name FROM Account LEFT OUTER JOIN Contact ON Account.Id = Contact.AccountId"); //$NON-NLS-1$
- SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
- visitor.visit(command);
- assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
- }
-
-}
Modified: trunk/connectors/connector-text/pom.xml
===================================================================
--- trunk/connectors/connector-text/pom.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,35 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <parent>
- <artifactId>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.0.0-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-text</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>Text Connector</name>
- <packaging>rar</packaging>
- <description>This connector reads data from text files.</description>
-
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-text</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Text Connector</name>
+ <packaging>rar</packaging>
+ <description>This connector reads data from text files.</description>
+
<dependencies>
<dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-connector-api</artifactId>
- <scope>provided</scope>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-connector-api</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>translator-text</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>javax.resource</groupId>
<artifactId>connector-api</artifactId>
<scope>provided</scope>
- </dependency>
+ </dependency>
</dependencies>
-
<build>
<plugins>
<plugin>
@@ -52,10 +57,8 @@
<classifier>lib</classifier>
</configuration>
</execution>
-
</executions>
</plugin>
</plugins>
- </build>
-
+ </build>
</project>
\ No newline at end of file
Copied: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text (from rev 2083, trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text)
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/StringToDateTranslator.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/StringToDateTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/StringToDateTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,228 +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 com.metamatrix.connector.text;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.StringTokenizer;
-
-
-/**
- * <p>This is a helper class for TextTranslators that can be used to translate
- * any String that is a representation of a date to a java.util.Date object.
- * This class is created by passing it a properties object that contains at least
- * one property. The value of this property is a String that can be a delimited list of
- * date format Strings. Date format Strings can be any format String that a
- * java.text.SimpleDateFormat can be created with. There is also an optional
- * property that defines the delimiter for the list of Date format Strings.
- * If this property is not specified then the entire String value of the DateFormatStrings
- * property will be used as the only format that this class can translate.</p>
- *
- * <p>After this class is created it can the be used to translate Strings into
- * java.util.Date object using the translateStringToDate(String) method.</p>
- */
-public class StringToDateTranslator {
-
- TextManagedConnectionFactory config;
-
- /**
- * The SimpleDateFormat objects that are used to translate dates for this
- * connector.
- */
- private List simpleDateFormats;
-
- /**
- * The List of date format Strings that define the patterns of the Strings
- * that this translator can translate.
- */
- private List dateFormatStrings;
-
- /**
- * This boolean determines whether this instance has any DateFormatters
- * to translate Strings with. It is cached for performance reasons.
- */
- private boolean hasFormatters=false;
-
- /**
- * <p>This class is created by passing it a properties object that contains at least
- * one property. The value of this property is a String that can be a delimited list of
- * date format Strings. Date format Strings can be any format String that a
- * java.text.SimpleDateFormat can be created with. There is also an optional
- * property that defines the delimiter for the list of Date format Strings.
- * If this property is not specified then the entire String value of the DateFormatStrings
- * property will be used as the only format that this class can translate.</p>
- *
- * <p>Note that the order of the list of date format strings is important
- * because the translator attempts to translate the String passed to it in the
- * order of the date format Strings in the delimited property value.</p>
- *
- * <p>After this class is created it can the be used to translate Strings into
- * java.util.Date object using the translateStringToDate(String) method.</p>
- *
- * <pre>
- * The properties that are required in construction of this class are as
- * follows:
- *
- * PropertyName: TextPropertyNames.DATE_RESULT_FORMATS
- * PropertyValue: Delimited list of date format Strings: ie MM/dd/yy' 'hh:mm:ss
- *
- * PropertyName: TextPropertyNames.DATE_RESULT_FORMATS_DELIMITER
- * PropertyValue: Delimiter for value of TextPropertyNames.DATE_RESULT_FORMATS
- * </pre>
- */
- public StringToDateTranslator(TextManagedConnectionFactory config) {
- this.config = config;
-
- String dateFormats = config.getDateResultFormats();
- String dateFormatsDelimiter = config.getDateResultFormatsDelimiter();
-
- if (!(dateFormatsDelimiter == null || dateFormatsDelimiter.trim().length() == 0)) {
- if (!(dateFormats == null || dateFormats.trim().length() == 0)) {
- createSimpleDateFormats(dateFormats, dateFormatsDelimiter);
- }
- } else if (!(dateFormats == null || dateFormats.trim().length() == 0)) {
- createSimpleDateFormat(dateFormats);
- }
-
- if (simpleDateFormats != null && simpleDateFormats.size() > 0) {
- hasFormatters = true;
- }
- }
-
- /**
- * This method is used to translate String representations of dates into
- * java.util.Date objects using a set of formats passed into this class at
- * creation time. Has formatters should always be called on this class
- * prior to the use of this method to determine whether or not there are any
- * formatters this class can use to translate the String value passed in.
- * If there are no formatters and this method is called, it will throw
- * a parse Exception.
- *
- * @param string the String to be parsed into a java.util.Date
- * @return the java.util.Date representation of the passed in String
- * @throws ParseException if the String passed in could not be parsed
- */
- public java.util.Date translateStringToDate(String string) throws ParseException{
- List parseExceptionList = new ArrayList();
- Iterator iterator = simpleDateFormats.iterator();
-
- while (iterator.hasNext()) {
- SimpleDateFormat formatter = (SimpleDateFormat)iterator.next();
- try {
- java.util.Date date = formatter.parse(string);
- return date;
- }catch(ParseException e) {
- parseExceptionList.add(e);
- // Do nothing here will try again with the next formatter
- }
- }
-
- // if we have reached this point without returning a Date, we
- // have been unsuccessful in parsing: throw an exception
-
- // This should always be the case, but just for safety:
- if (dateFormatStrings.size() == parseExceptionList.size()) {
- StringBuffer message = new StringBuffer();
- int counter = 0;
- Object[] params = new Object[] { string };
- message.append(TextPlugin.Util.getString("StringToDateTranslator.Attempts_to_parse_String__{0}_to_a_java.util.Date_failed_for_the_following_reasons___1", params)); //$NON-NLS-1$
-
- if (!hasFormatters()) {
- message.append(TextPlugin.Util.getString("StringToDateTranslator.There_is_no_format_Strings_found_in_this_formatter_object._n_2", params)); //$NON-NLS-1$
- }
-
- Iterator exceptionsIterator = parseExceptionList.iterator();
- Iterator formatStringsIterator = dateFormatStrings.iterator();
- while (exceptionsIterator.hasNext()) {
- String format = (String)formatStringsIterator.next();
- String exceptionMessage = ((ParseException)exceptionsIterator.next()).getMessage();
- Object[] params2 = new Object[] { ""+counter, format, exceptionMessage }; //$NON-NLS-1$
- message.append(TextPlugin.Util.getString("StringToDateTranslator.Parse_Attempt__{0}_using_format__{1}_failed_for_the_following_reason__{2}_4", params2)); //$NON-NLS-1$
- counter++;
- }
-
- throw new ParseException(message.toString(),0);
- }
- Object params3 = new Object[] { string, dateFormatStrings };
- throw new ParseException(TextPlugin.Util.getString("StringToDateTranslator.Failed_to_convert_String__{0}_to_a_Date_using_one_of_the_following_format_Strings_that_are_specified_in_the_properties_for_this_Connector__{1}_1", params3), 0); //$NON-NLS-1$
- }
-
- /**
- * This method is used to check the status of this translator object.
- * It will return true if this translator has any 'formatters' to do parsing
- * of Strings in the translateStringToDate() method. This method should
- * always be called prior to using the translateStringToDate() method.
- * If there are no formatters for the instance of this class, all calls to
- * the translateStringToDate() method will throw a ParseException.
- *
- * @return true if this class has formatters to parse Strings to Dates
- */
- public boolean hasFormatters() {
- return hasFormatters;
- }
-
- /**
- * This method is a helper method that will instantiate the formatters that
- * this object uses to translate Strings into Dates.
- *
- * @param dateFormats the delimited String of date format templates to
- * be used to create the date formatters for this object.
- * @param dateFormatsDelimiter the delimiter used to delimit the dateFormats
- * String that is also passed into this method.
- */
- private void createSimpleDateFormats(String dateFormats, String dateFormatsDelimiter) {
- simpleDateFormats = new ArrayList();
- dateFormatStrings = new ArrayList();
- StringTokenizer tokenizer = new StringTokenizer(dateFormats, dateFormatsDelimiter);
-
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- this.config.getLogger().logTrace("Creating simple Date format for formatting String: " +token); //$NON-NLS-1$
-
- dateFormatStrings.add(token);
- SimpleDateFormat formatter = new SimpleDateFormat(token.trim());
- simpleDateFormats.add(formatter);
- }
- }
-
- /**
- * This method is as helper method that will create a single date formatter
- * from the date format template String that is passed into it.
- *
- * @param dateFormats the String that is the template for translating
- * Strings into java.util.Date objects
- */
- private void createSimpleDateFormat(String dateFormats) {
- simpleDateFormats = new ArrayList();
- dateFormatStrings = new ArrayList();
- this.config.getLogger().logTrace("Creating simple Date format for formatting String: " +dateFormats); //$NON-NLS-1$
-
- SimpleDateFormat formatter = new SimpleDateFormat(dateFormats);
- dateFormatStrings.add(dateFormats);
- simpleDateFormats.add(formatter);
- }
-
-}
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextCapabilities.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextCapabilities.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,31 +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 com.metamatrix.connector.text;
-
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-
-public class TextCapabilities extends BasicConnectorCapabilities {
-
- static TextCapabilities INSTANCE = new TextCapabilities();
-
-}
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnection.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextConnection.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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 com.metamatrix.connector.text;
-
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.MetadataProvider;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-import org.teiid.connector.metadata.runtime.Table;
-
-
-/**
- * Implementation of Connection interface for text connection.
- */
-public class TextConnection extends BasicConnection implements MetadataProvider {
-
- // metadata props -- Map<groupName --> Map<propName, propValue>
- Map <String, Properties> metadataProps;
-
- // connector props
- private TextManagedConnectionFactory config;
-
- /**
- * Constructor.
- * @param env
- */
- TextConnection(TextManagedConnectionFactory env, Map metadataProps) {
- this.config = env;
- this.metadataProps = metadataProps;
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new TextSynchExecution(this.config, (Select)command, this.metadataProps);
- }
-
- @Override
- public void close() {
- metadataProps = null;
- }
-
- @Override
- public void getConnectorMetadata(MetadataFactory metadataFactory) throws ConnectorException {
- for (Map.Entry<String, Properties> entry : this.metadataProps.entrySet()) {
- Properties p = entry.getValue();
- String columns = p.getProperty(TextPropertyNames.COLUMNS);
- if (columns == null) {
- continue;
- }
- String types = p.getProperty(TextPropertyNames.TYPES);
- String[] columnNames = columns.trim().split(","); //$NON-NLS-1$
- String[] typeNames = null;
- if (types != null) {
- typeNames = types.trim().split(","); //$NON-NLS-1$
- if (typeNames.length != columnNames.length) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnector.column_mismatch", entry.getKey())); //$NON-NLS-1$
- }
- }
- Table table = metadataFactory.addTable(entry.getKey().substring(entry.getKey().indexOf('.') + 1));
- for (int i = 0; i < columnNames.length; i++) {
- String type = typeNames == null?TypeFacility.RUNTIME_NAMES.STRING:typeNames[i].trim().toLowerCase();
- Column column = metadataFactory.addColumn(columnNames[i].trim(), type, table);
- column.setNameInSource(String.valueOf(i));
- column.setNativeType(TypeFacility.RUNTIME_NAMES.STRING);
- }
- }
- }
-}
Added: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionFactory.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionFactory.java (rev 0)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,317 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci.text;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.text.TextDescriptorPropertyNames;
+import org.teiid.resource.adapter.text.TextUtil;
+import org.teiid.resource.spi.BasicConnectionFactory;
+
+public class TextConnectionFactory extends BasicConnectionFactory {
+ private static final long serialVersionUID = 1838645911208083797L;
+ private TextManagedConnectionFactory mcf;
+ private Map<String, Properties> metadataProps = new HashMap<String, Properties>();
+ private int srcFiles = 0;
+ private int srcFileErrs = 0;
+ private String parentDirectory;
+
+ public TextConnectionFactory(TextManagedConnectionFactory mcf) throws ConnectorException {
+ this.mcf = mcf;
+ initMetaDataProps();
+ }
+
+ @Override
+ public Connection getConnection() throws ResourceException {
+ return new TextConnectionImpl(this.metadataProps);
+ }
+
+
+ private void initMetaDataProps() throws ConnectorException {
+ reinitFileCounts();
+ try {
+ readDescriptor(this.mcf.getDescriptorFile(), this.mcf.isPartialStartupAllowed());
+ reinitFileCounts();
+ } catch (ConnectorException ce) {
+ // If partial startup is not allowed, throw the exception
+ if(!this.mcf.isPartialStartupAllowed() ) {
+ reinitFileCounts();
+ throw ce;
+ // If partial startup is allowed, only throw exception if no files connected
+ } else if(this.srcFileErrs==this.srcFiles) {
+ reinitFileCounts();
+ throw ce;
+ }
+ }
+ }
+
+ private void reinitFileCounts() {
+ this.srcFiles=0;
+ this.srcFileErrs=0;
+ }
+
+ /**
+ * Read Descriptor file and get properties info for acessing the file.
+ * @param descriptorFile String standing for the name of descriptor file.
+ * @throws ConnectorException throws if error occurs
+ */
+ private void readDescriptor(String descriptorFile, boolean startPartial)
+ throws ConnectorException {
+
+ // Verify required items
+ if (descriptorFile == null || descriptorFile.trim().length() == 0) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_name_is_not_specified._2")); //$NON-NLS-1$
+ }
+ // Save first exception if there are multiple
+ ConnectorException connExcep = null;
+
+ BufferedReader br = null;
+ try {
+ br = getReader(descriptorFile);
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Reading descriptor file: " + descriptorFile); //$NON-NLS-1$
+
+ String line = null;
+ // Walk through records, finding matches
+ while(true) {
+ line = br.readLine();
+ if (line == null) {
+ break;
+ }
+
+ // Skip blank lines
+ if (line.length() == 0) {
+ continue;
+ }
+
+ // populate the map with metadata information for the given line. If readAll option is chosen,
+ // keep trying to read until everything is tried, then throw the first exception encountered.
+ try {
+ getMetadata(line);
+ } catch (ConnectorException e) {
+ if(!startPartial) {
+ throw e;
+ } else if (connExcep==null) {
+ connExcep=e;
+ }
+ }
+
+ }
+ // throw first exception if readAll was set
+ if(connExcep!=null) throw connExcep;
+
+ } catch (IOException e) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, e, TextPlugin.Util.getString("TextConnection.Error_while_reading_text_file__{0}_1", new Object[] {e.getMessage()})); //$NON-NLS-1$
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.Error_trying_to_establish_connection_5")); //$NON-NLS-1$
+ } finally {
+ if (br != null) {
+ try {br.close();} catch (Exception ee) {}
+ }
+ }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Successfully read metadata information from the descriptor file " + descriptorFile); //$NON-NLS-1$
+ }
+
+ /**
+ * Read the property string and populate the properties with info needed to access data files.
+ */
+ private void getMetadata(String propStr) throws ConnectorException {
+ try {
+ int index = 0;
+
+ // Property String --> <Fully_Qualified_Group>.location=<location of actual file>
+ int eqIndex = propStr.indexOf("=", index); //$NON-NLS-1$
+ String propString = propStr.substring(index, eqIndex);
+
+ if (!propString.equals(" ")) { //$NON-NLS-1$
+ propString = propString.trim();
+ }
+
+ int lastIndex = propString.lastIndexOf('.');
+
+ // group name
+ String groupName = propString.substring(0, lastIndex).toUpperCase();
+ // property name
+ String propertyName = propString.substring(lastIndex + 1).toUpperCase();
+
+ // Properties read from descriptor, which are properties for a given group
+ Properties props = metadataProps.get(groupName);
+ if (props == null) {
+ props = new Properties();
+ }
+
+ // Adjust index past '='
+ index = eqIndex + 1;
+
+ // Read property value
+ String propertyValue = propStr.substring(index).trim();
+
+ if (propertyName.equals(TextDescriptorPropertyNames.LOCATION)) {
+ srcFiles++;
+ // Verify required items
+ if (propertyValue == null || propertyValue.trim().length() == 0) {
+ srcFileErrs++;
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Text_file_name_is_not_specified_for_the_group___{0}_2", new Object[] {groupName})); //$NON-NLS-1$
+ }
+ try {
+ checkFile(propertyValue, props, groupName);
+ } catch (ConnectorException e) {
+ if (this.parentDirectory == null) {
+ throw e;
+ }
+ srcFileErrs--;
+ try {
+ checkFile(parentDirectory + "/" + propertyValue, props, groupName); //$NON-NLS-1$
+ } catch (ConnectorException e1) {
+ throw e;
+ }
+ }
+ } else if (propertyName.equals(TextDescriptorPropertyNames.HEADER_LINES)) {
+ try {
+ Integer.parseInt(propertyValue);
+ } catch (NumberFormatException e) {
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3", new Object[] {e.getMessage()})); //$NON-NLS-1$
+ }
+ } else if (propertyName.equals(TextDescriptorPropertyNames.HEADER_ROW)) {
+ try {
+ Integer.parseInt(propertyValue);
+ } catch (NumberFormatException e) {
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3", new Object[] {e.getMessage()})); //$NON-NLS-1$
+ }
+ } else if (!(propertyName.equals(TextDescriptorPropertyNames.COLUMNS) || propertyName.equals(TextDescriptorPropertyNames.TYPES) || propertyName.equals(TextDescriptorPropertyNames.TYPES) || propertyName.equals(TextDescriptorPropertyNames.TYPES) || propertyName.equals(TextDescriptorPropertyNames.TYPES) || propertyName.equals(TextDescriptorPropertyNames.DELIMITER) || propertyName.equals(TextDescriptorPropertyNames.QUALIFIER))) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.The_property_{0}_for_the_group_{1}_is_invalid._4", new Object[] {propertyName, groupName})); //$NON-NLS-1$
+ }
+
+ // Check for tab as a delimiter and use correct string
+ if (propertyValue != null && propertyValue.equals("\\t")) { //$NON-NLS-1$
+ propertyValue = "\t"; //$NON-NLS-1$
+ }
+
+ if (propertyValue != null && !propertyValue.equals("")) { //$NON-NLS-1$
+ // Add property
+ props.put(propertyName, propertyValue);
+ metadataProps.put(groupName, props);
+ }
+ } catch (Exception e) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Error_parsing_property_string_{0}__{1}_6", new Object[] {propStr, e.getMessage()})); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * This method gets the reader object for the descriptorfile present either on the local file system or the web.
+ * @param fileLocation String standing for the fileLocation either in file system or web.
+ * @return BufferReader for the file
+ */
+ private BufferedReader getReader(String fileLocation) throws ConnectorException {
+ BufferedReader br = null;
+ // Construct file and make sure it exists and is readable
+ File descfile = new File(fileLocation);
+ if (descfile.isFile()) {
+ if (!descfile.exists()) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_9", new Object[] {fileLocation})); //$NON-NLS-1$
+ } else if (!descfile.canRead()) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_{0}_found_but_does_not_have_Read_permissions_10", new Object[] {fileLocation})); //$NON-NLS-1$
+ }
+ this.parentDirectory = descfile.getParent();
+ try {
+ br = new BufferedReader(new FileReader(descfile));
+
+ } catch (FileNotFoundException fe) {
+ throw new ConnectorException(fe,TextPlugin.Util.getString("TextConnection.Couldn__t_find_the_file_of_name_{0}_11", new Object[] {descfile})); //$NON-NLS-1$
+ }
+ } else {
+ try {
+ URL url = new URL(fileLocation);
+ // create the connection to the URL
+ URLConnection conn = url.openConnection();
+ // establish the connection to the URL
+ conn.connect();
+ // get the stream from the connection
+ InputStreamReader inSR = new InputStreamReader(conn.getInputStream());
+ // place the stream into a buffered reader
+ br = new BufferedReader(inSR);
+ } catch (IOException e) {
+ throw new ConnectorException(e,TextPlugin.Util.getString("TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_12", new Object[] {fileLocation})); //$NON-NLS-1$
+ }
+ }
+ return br;
+ }
+
+ /**
+ * Check if the file or url of the given name exists and populate properties.
+ */
+ private void checkFile(String fileName, Properties props, String groupName)
+ throws ConnectorException {
+
+ // Construct file and make sure it exists and is readable
+ File datafile = new File(fileName);
+
+ File[] files= TextUtil.getFiles(fileName);
+
+
+ // determine if the wild card is used to indicate all files
+ // of the specified extension
+ if (files == null && TextUtil.usesWildCard(fileName)) {
+ srcFileErrs++;
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
+ }
+ if (files != null && files.length > 0) {
+ props.setProperty(TextDescriptorPropertyNames.FILE_LOCATION, fileName);
+ } else if (datafile.isFile()){
+ if (!datafile.exists()) {
+ srcFileErrs++;
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
+ }
+ else if (!datafile.canRead()) {
+ srcFileErrs++;
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Data_file_{0}_found_but_does_not_have_Read_permissions_8", new Object[] {fileName})); //$NON-NLS-1$
+ }
+ props.setProperty(TextDescriptorPropertyNames.FILE_LOCATION, fileName);
+ } else {
+ try {
+ URL url = new URL(fileName);
+ // create the connection to the URL
+ URLConnection conn = url.openConnection();
+ // establish the connection to the URL
+ conn.connect();
+ props.setProperty(TextDescriptorPropertyNames.URL_LOCATION, fileName);
+ } catch (IOException e) {
+ srcFileErrs++;
+ throw new ConnectorException(e,TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
+ }
+ }
+ }
+}
Property changes on: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionImpl.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionImpl.java (rev 0)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnectionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,311 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.cci.text;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.resource.ResourceException;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.text.TextConnection;
+import org.teiid.resource.adapter.text.TextDescriptorPropertyNames;
+import org.teiid.resource.adapter.text.TextPlugin;
+import org.teiid.resource.adapter.text.TextUtil;
+import org.teiid.resource.spi.BasicConnection;
+
+import com.metamatrix.core.util.StringUtil;
+
+
+/**
+ * Implementation of Connection interface for text connection.
+ */
+public class TextConnectionImpl extends BasicConnection implements TextConnection{
+
+ private Map<String, Properties> metadataProps;
+ private ArrayList readerQueue = new ArrayList();
+ private int readerQueueIndex = 0;
+ private String headerMsg;
+ private String firstLine = null;
+
+ // current Reader object
+ private BufferedReader currentreader = null;
+
+ // Line num in the text file
+ private int lineNum = 0;
+
+
+ public TextConnectionImpl(Map<String, Properties> props) {
+ this.metadataProps = props;
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ if (readerQueue.size() > 0) {
+ for (Iterator it=readerQueue.iterator(); it.hasNext();) {
+ BufferedReader br = (BufferedReader) it.next();
+ try {
+ br.close();
+ } catch (IOException err) {
+ }
+
+ }
+ }
+ readerQueue.clear();
+ }
+
+ @Override
+ public Map<String, Properties> getMetadataProperties() {
+ return metadataProps;
+ }
+
+ private List<Reader> createReaders(String tableName) throws ConnectorException {
+ try {
+ createReaders(this.metadataProps.get(tableName), tableName);
+ } catch (IOException e) {
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Unable_get_Reader", new Object[] {tableName, e.getMessage() })); //$NON-NLS-1$
+
+ }
+ return readerQueue;
+ }
+
+ /**
+ * This method gets the reader object for the textfile present either on
+ * the local file system or the web.
+ * @param props Group's metadata properites string
+ * @return BufferReader Object
+ */
+ private void createReaders(Properties props, String groupName) throws IOException, ConnectorException {
+ if(readerQueue != null && readerQueue.size() > 0) {
+ return ;
+ }
+
+ if(props == null) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Error_obtain_properties_for_group", groupName)); //$NON-NLS-1$
+ }
+
+ String fileName = props.getProperty(TextDescriptorPropertyNames.FILE_LOCATION);
+
+
+ if(fileName != null) {
+ File datafile = new File(fileName);
+ File[] files= TextUtil.getFiles(fileName);
+
+
+ // determine if the wild card is used to indicate all files
+ // of the specified extension
+ if (files != null && files.length > 0) {
+ for (int i = 0; i<files.length; i++) {
+ File f = files[i];
+ addReader(f.getName(), f);
+ }
+
+ } else {
+ addReader(fileName, datafile);
+ }
+ } else {
+ String urlName = props.getProperty(TextDescriptorPropertyNames.URL_LOCATION);
+ if(urlName==null) {
+ Object[] params = new Object[] { groupName };
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Unable_get_Reader_for_group", params)); //$NON-NLS-1$
+ }
+
+ // create the URL object
+ URL url = new URL(urlName);
+ // create the connection to the URL
+ URLConnection conn = url.openConnection();
+ // establish the connection to the URL
+ conn.connect();
+ // get the stream from the connection
+ InputStreamReader inSR = new InputStreamReader(conn.getInputStream());
+ // place the stream into a buffered reader
+ addReader(fileName, inSR);
+ }
+
+ }
+
+ private void addReader(String fileName, File datafile) throws IOException {
+
+ FileInputStream fis = new FileInputStream(datafile);
+ InputStreamReader inSR = new InputStreamReader(fis);
+
+ BufferedReader r = new BufferedReader(inSR);
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Reading file: " + fileName); //$NON-NLS-1$
+ readerQueue.add(r);
+ }
+
+ private void addReader(String fileName, InputStreamReader inSr) {
+ BufferedReader r = new BufferedReader(inSr);
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Reading URL: " + fileName); //$NON-NLS-1$
+ readerQueue.add(r);
+ }
+
+ /**
+ * Gets the current reader, looking at the next
+ * one in the list if the current one is null.
+ *
+ * If HEADER_LINES is greater than 0, an attempt is made to
+ * read the column headers from the file. If HEADER_ROW is
+ * less than 1, row HEADER_LINES is used as the row that may
+ * contain column names. If HEADER_ROW is greater than 1,
+ * row HEADER_ROW is used as the row that may contain column
+ * names.
+ *
+ * @throws ConnectorException
+ */
+ private String nextLine(String tableName) throws ConnectorException {
+ if (currentreader == null && readerQueueIndex < readerQueue.size()) {
+ // reader queue index is advanced only by the nextReader()
+ // method. Don't do it here.
+ currentreader = (BufferedReader)readerQueue.get(readerQueueIndex);
+ }
+ /* Retrieve connector properties so that we can find a
+ * header row if necessary.
+ */
+ Properties groupProps = this.metadataProps.get(tableName);
+ String line = null;
+ String location = groupProps.getProperty(TextDescriptorPropertyNames.LOCATION);
+ String qualifier = groupProps.getProperty(TextDescriptorPropertyNames.QUALIFIER);
+ String topLines = groupProps.getProperty(TextDescriptorPropertyNames.HEADER_LINES);
+ String headerLine = groupProps.getProperty(TextDescriptorPropertyNames.HEADER_ROW);
+
+ int numTop = 0;
+ int headerRowNum = 0;
+ if (topLines != null && topLines.length() > 0)
+ numTop = Integer.parseInt(topLines);
+ if (headerLine != null && headerLine.length() > 0)
+ headerRowNum = Integer.parseInt(headerLine);
+
+ /* Check to see if the value for HEADER_ROW is greater than
+ * the number of lines to skip. If it is, it is invalid and
+ * we will use HEADER_LINES instead.
+ */
+ if ( headerRowNum > numTop ) {
+ Object[] params = new Object[] { TextDescriptorPropertyNames.HEADER_ROW, new Integer(headerRowNum), new Integer(numTop) };
+ String msg = TextPlugin.Util.getString("TextSynchExecution.Property_contains_an_invalid_value_Using_value", params); //$NON-NLS-1$
+ // TODO: We should include the group name in the log message.
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, msg);
+
+ headerRowNum = numTop;
+ }
+ try {
+ // set hasQualifier flag
+ boolean hasQualifier = false;
+ if (qualifier != null && qualifier.length() > 0)
+ hasQualifier = true;
+
+ // Walk through rows looking for header row
+ while (currentreader != null) {
+ line = currentreader.readLine();
+ // Hit the end of file or the file is empty then
+ // try next reader
+ if (line == null) {
+ advanceToNextReader();
+ lineNum = 0;
+ return nextLine(tableName);
+ }
+
+ // check if we have a qualifier defined
+ // if yes check that all qualifiers have been terminated
+ // if not then append the next line (if available)
+ if (hasQualifier) {
+ while (StringUtil.occurrences(line, qualifier) % 2 != 0) {
+ String nextLine = currentreader.readLine();
+ if (nextLine != null)
+ line = line + StringUtil.LINE_SEPARATOR + nextLine;
+ else {
+ Object[] params = new Object[] { line };
+ String msg = TextPlugin.Util.getString("TextSynchExecution.Text_has_no_determined_ending_qualifier", params); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ }
+ }
+ lineNum++;
+
+ // Skip blank lines
+ if (line.length() == 0) continue;
+
+ // Attempt to retrieve column names from header row
+ // or last row of header lines.
+ if ((headerRowNum > 0 && headerRowNum == lineNum) || (numTop == lineNum)) {
+ // This is the header row; check if null to avoid the second or clause
+ if (headerMsg == null) {
+ headerMsg = line;
+ }
+ continue;
+ } else if (numTop >= lineNum) {
+ continue;
+ }
+ return line;
+ }
+ } catch (Throwable e) {
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Error_reading_text_file", new Object[] { location, e.getMessage() })); //$NON-NLS-1$
+ }
+ // we are done reading..
+ return null;
+ }
+
+ /**
+ * Indicate that we are done with the current reader and we should
+ * advance to the next reader.
+ */
+ private void advanceToNextReader(){
+ currentreader = null;
+ readerQueueIndex++;
+ }
+
+ @Override
+ public String getHeaderLine(String tableName) throws ConnectorException {
+ if (this.headerMsg != null) {
+ return this.headerMsg;
+ }
+ createReaders(tableName);
+ this.firstLine = nextLine(tableName);
+ return this.headerMsg;
+ }
+
+ @Override
+ public String getNextLine(String tableName) throws ConnectorException {
+ // make sure the reader are created
+ createReaders(tableName);
+ if (this.firstLine != null) {
+ String copy = this.firstLine;
+ this.firstLine = null;
+ return copy;
+ }
+ return nextLine(tableName);
+ }
+}
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnector.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextConnector.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,331 +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 com.metamatrix.connector.text;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.basic.BasicConnector;
-
-
-/**
- * Implementation of text connector.
- */
-public class TextConnector extends BasicConnector {
-
- private TextManagedConnectionFactory config;
- private int srcFiles = 0;
- private int srcFileErrs = 0;
- private Map<String, Properties> metadataProps = new HashMap<String, Properties>();
- private String parentDirectory;
-
- @Override
- public void initialize(ConnectorEnvironment env) throws ConnectorException {
- super.initialize(env);
-
- this.config = (TextManagedConnectionFactory)env;
-
- initMetaDataProps();
-
- // test connection
- TextConnection test = new TextConnection(this.config, metadataProps);
- test.close();
- }
-
-
- public Connection getConnection() throws ConnectorException {
- return new TextConnection(this.config, metadataProps);
- }
-
- private void initMetaDataProps() throws ConnectorException {
- reinitFileCounts();
- try {
- readDescriptor(this.config.getDescriptorFile(),this.config.isPartialStartupAllowed());
- reinitFileCounts();
- } catch (ConnectorException ce) {
- // If partial startup is not allowed, throw the exception
- if(!this.config.isPartialStartupAllowed() ) {
- reinitFileCounts();
- throw ce;
- // If partial startup is allowed, only throw exception if no files connected
- } else if(this.srcFileErrs==this.srcFiles) {
- reinitFileCounts();
- throw ce;
- }
- }
- }
-
-
- private void reinitFileCounts() {
- this.srcFiles=0;
- this.srcFileErrs=0;
- }
-
- /**
- * Read Descriptor file and get properties info for acessing the file.
- * @param descriptorFile String standing for the name of descriptor file.
- * @throws ConnectorException throws if error occurs
- */
- private void readDescriptor(String descriptorFile, boolean startPartial)
- throws ConnectorException {
-
- // Verify required items
- if (descriptorFile == null || descriptorFile.trim().length() == 0) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_name_is_not_specified._2")); //$NON-NLS-1$
- }
- // Save first exception if there are multiple
- ConnectorException connExcep = null;
-
- BufferedReader br = null;
- try {
- br = getReader(descriptorFile);
- this.config.getLogger().logInfo("Reading descriptor file: " + descriptorFile); //$NON-NLS-1$
-
- String line = null;
- // Walk through records, finding matches
- while(true) {
- line = br.readLine();
- if (line == null) {
- break;
- }
-
- // Skip blank lines
- if (line.length() == 0) {
- continue;
- }
-
- // populate the map with metadata information for the given line. If readAll option is chosen,
- // keep trying to read until everything is tried, then throw the first exception encountered.
- try {
- getMetadata(line);
- } catch (ConnectorException e) {
- if(!startPartial) {
- throw e;
- } else if (connExcep==null) {
- connExcep=e;
- }
- }
-
- }
- // throw first exception if readAll was set
- if(connExcep!=null) throw connExcep;
-
- } catch (IOException e) {
- this.config.getLogger().logError(TextPlugin.Util.getString("TextConnection.Error_while_reading_text_file__{0}_1", new Object[] {e.getMessage()}), e); //$NON-NLS-1$
- throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.Error_trying_to_establish_connection_5")); //$NON-NLS-1$
- } finally {
- if (br != null) {
- try {br.close();} catch (Exception ee) {}
- }
- }
- this.config.getLogger().logDetail("Successfully read metadata information from the descriptor file " + descriptorFile); //$NON-NLS-1$
- }
-
- /**
- * Read the property string and populate the properties with info needed to access data files.
- */
- private void getMetadata(String propStr) throws ConnectorException {
- try {
- int index = 0;
-
- // Property String --> <Fully_Qualified_Group>.location=<location of actual file>
- int eqIndex = propStr.indexOf("=", index); //$NON-NLS-1$
- String propString = propStr.substring(index, eqIndex);
-
- if (!propString.equals(" ")) { //$NON-NLS-1$
- propString = propString.trim();
- }
-
- int lastIndex = propString.lastIndexOf('.');
-
- // group name
- String groupName = propString.substring(0, lastIndex).toUpperCase();
- // property name
- String propertyName = propString.substring(lastIndex + 1).toUpperCase();
-
- // Properties read from descriptor, which are properties for a given group
- Properties props = metadataProps.get(groupName);
- if (props == null) {
- props = new Properties();
- }
-
- // Adjust index past '='
- index = eqIndex + 1;
-
- // Read property value
- String propertyValue = propStr.substring(index).trim();
-
- if (propertyName.equals(TextPropertyNames.LOCATION)) {
- srcFiles++;
- // Verify required items
- if (propertyValue == null || propertyValue.trim().length() == 0) {
- srcFileErrs++;
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Text_file_name_is_not_specified_for_the_group___{0}_2", new Object[] {groupName})); //$NON-NLS-1$
- }
- try {
- checkFile(propertyValue, props, groupName);
- } catch (ConnectorException e) {
- if (this.parentDirectory == null) {
- throw e;
- }
- srcFileErrs--;
- try {
- checkFile(parentDirectory + "/" + propertyValue, props, groupName); //$NON-NLS-1$
- } catch (ConnectorException e1) {
- throw e;
- }
- }
- } else if (propertyName.equals(TextPropertyNames.HEADER_LINES)) {
- try {
- Integer.parseInt(propertyValue);
- } catch (NumberFormatException e) {
- throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3", new Object[] {e.getMessage()})); //$NON-NLS-1$
- }
- } else if (propertyName.equals(TextPropertyNames.HEADER_ROW)) {
- try {
- Integer.parseInt(propertyValue);
- } catch (NumberFormatException e) {
- throw new ConnectorException(e, TextPlugin.Util.getString("TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3", new Object[] {e.getMessage()})); //$NON-NLS-1$
- }
- } else if (!(propertyName.equals(TextPropertyNames.COLUMNS) || propertyName.equals(TextPropertyNames.TYPES) || propertyName.equals(TextPropertyNames.TYPES) || propertyName.equals(TextPropertyNames.TYPES) || propertyName.equals(TextPropertyNames.TYPES) || propertyName.equals(TextPropertyNames.DELIMITER) || propertyName.equals(TextPropertyNames.QUALIFIER))) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.The_property_{0}_for_the_group_{1}_is_invalid._4", new Object[] {propertyName, groupName})); //$NON-NLS-1$
- }
-
- // Check for tab as a delimiter and use correct string
- if (propertyValue != null && propertyValue.equals("\\t")) { //$NON-NLS-1$
- propertyValue = "\t"; //$NON-NLS-1$
- }
-
- if (propertyValue != null && !propertyValue.equals("")) { //$NON-NLS-1$
- // Add property
- props.put(propertyName, propertyValue);
- metadataProps.put(groupName, props);
- }
- } catch (Exception e) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Error_parsing_property_string_{0}__{1}_6", new Object[] {propStr, e.getMessage()})); //$NON-NLS-1$
- }
-
- }
-
- /**
- * Check if the file or url of the given name exists and populate properties.
- */
- private void checkFile(String fileName, Properties props, String groupName)
- throws ConnectorException {
-
- // Construct file and make sure it exists and is readable
- File datafile = new File(fileName);
-
- File[] files= TextUtil.getFiles(fileName);
-
-
- // determine if the wild card is used to indicate all files
- // of the specified extension
- if (files == null && TextUtil.usesWildCard(fileName)) {
- srcFileErrs++;
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
- }
- if (files != null && files.length > 0) {
- props.setProperty(TextPropertyNames.FILE_LOCATION, fileName);
- } else if (datafile.isFile()){
- if (!datafile.exists()) {
- srcFileErrs++;
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
- }
- else if (!datafile.canRead()) {
- srcFileErrs++;
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Data_file_{0}_found_but_does_not_have_Read_permissions_8", new Object[] {fileName})); //$NON-NLS-1$
- }
- props.setProperty(TextPropertyNames.FILE_LOCATION, fileName);
- } else {
- try {
- URL url = new URL(fileName);
- // create the connection to the URL
- URLConnection conn = url.openConnection();
- // establish the connection to the URL
- conn.connect();
- props.setProperty(TextPropertyNames.URL_LOCATION, fileName);
- } catch (IOException e) {
- srcFileErrs++;
- throw new ConnectorException(e,TextPlugin.Util.getString("TextConnection.fileDoesNotExistForGroup", new Object[] {fileName, groupName})); //$NON-NLS-1$
- }
- }
-
- }
-
- /**
- * This method gets the reader object for the descriptorfile present either on the local file system or the web.
- * @param fileLocation String standing for the fileLocation either in file system or web.
- * @return BufferReader for the file
- */
- private BufferedReader getReader(String fileLocation) throws ConnectorException {
- BufferedReader br = null;
- // Construct file and make sure it exists and is readable
- File descfile = new File(fileLocation);
- if (descfile.isFile()) {
- if (!descfile.exists()) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_9", new Object[] {fileLocation})); //$NON-NLS-1$
- } else if (!descfile.canRead()) {
- throw new ConnectorException(TextPlugin.Util.getString("TextConnection.Descriptor_file_{0}_found_but_does_not_have_Read_permissions_10", new Object[] {fileLocation})); //$NON-NLS-1$
- }
- this.parentDirectory = descfile.getParent();
- try {
- br = new BufferedReader(new FileReader(descfile));
-
- } catch (FileNotFoundException fe) {
- throw new ConnectorException(fe,TextPlugin.Util.getString("TextConnection.Couldn__t_find_the_file_of_name_{0}_11", new Object[] {descfile})); //$NON-NLS-1$
- }
- } else {
- try {
- URL url = new URL(fileLocation);
- // create the connection to the URL
- URLConnection conn = url.openConnection();
- // establish the connection to the URL
- conn.connect();
- // get the stream from the connection
- InputStreamReader inSR = new InputStreamReader(conn.getInputStream());
- // place the stream into a buffered reader
- br = new BufferedReader(inSR);
- } catch (IOException e) {
- throw new ConnectorException(e,TextPlugin.Util.getString("TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_12", new Object[] {fileLocation})); //$NON-NLS-1$
- }
- }
- return br;
- }
-
-
-
-
-}
Modified: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextManagedConnectionFactory.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -19,58 +19,36 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
-import org.teiid.connector.basic.BasicManagedConnectionFactory;
+import javax.resource.ResourceException;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
public class TextManagedConnectionFactory extends BasicManagedConnectionFactory{
private static final long serialVersionUID = -1495488034205703625L;
-
private String descriptorFile;
- private boolean partialStartupAllowed = true;
- private boolean enforceColumnCount = false;
- private String dateResultFormatsDelimiter;
- private String dateResultFormats;
-
+ private boolean partialStartupAllowed;
+
+ @Override
+ public Object createConnectionFactory() throws ResourceException {
+ return new TextConnectionFactory(this);
+ }
+
public String getDescriptorFile() {
return descriptorFile;
}
public void setDescriptorFile(String descriptorFile) {
this.descriptorFile = descriptorFile;
- }
-
+ }
+
public boolean isPartialStartupAllowed() {
return partialStartupAllowed;
}
public void setPartialStartupAllowed(Boolean partialStartupAllowed) {
this.partialStartupAllowed = partialStartupAllowed.booleanValue();
- }
-
- public boolean isEnforceColumnCount() {
- return enforceColumnCount;
- }
-
- public void setEnforceColumnCount(Boolean enforceColumnCount) {
- this.enforceColumnCount = enforceColumnCount.booleanValue();
- }
-
- public String getDateResultFormatsDelimiter() {
- return dateResultFormatsDelimiter;
- }
-
- public void setDateResultFormatsDelimiter(String dateResultFormatsDelimiter) {
- this.dateResultFormatsDelimiter = dateResultFormatsDelimiter;
- }
-
- public String getDateResultFormats() {
- return dateResultFormats;
- }
-
- public void setDateResultFormats(String dateResultFormats) {
- this.dateResultFormats = dateResultFormats;
- }
-
+ }
}
Modified: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPlugin.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextPlugin.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -20,24 +20,14 @@
* 02110-1301 USA.
*/
-package com.metamatrix.connector.text;
+package org.teiid.resource.cci.text;
import java.util.ResourceBundle;
import com.metamatrix.core.BundleUtil;
-/**
- * TextPlugin
- * <p>Used here in <code>text</code> to have access to the new
- * logging framework.</p>
- */
-public class TextPlugin { // extends Plugin {
+public class TextPlugin {
- /**
- * The plug-in identifier of this plugin
- * (value <code>"com.metamatrix.dqp"</code>).
- */
- public static final String PLUGIN_ID = "com.metamatrix.connector.text" ; //$NON-NLS-1$
+ public static final String PLUGIN_ID = "org.teiid.resource.cci.text" ; //$NON-NLS-1$
- public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,
- PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
}
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPropertyNames.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextPropertyNames.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextPropertyNames.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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 com.metamatrix.connector.text;
-
-/**
- * Property names used in the text connector.
- */
-public class TextPropertyNames {
- public static final String DESCRIPTOR_FILE = "DescriptorFile"; //$NON-NLS-1$
- public static final String PARTIAL_STARTUP_ALLOWED = "PartialStartupAllowed"; //$NON-NLS-1$
- public static final String LOCATION = "LOCATION"; //$NON-NLS-1$
- public static final String FILE_LOCATION = "FILE"; //$NON-NLS-1$
- public static final String URL_LOCATION = "URL"; //$NON-NLS-1$
- public static final String DELIMITER = "DELIMITER"; //$NON-NLS-1$
- public static final String QUALIFIER = "QUALIFIER"; //$NON-NLS-1$
- public static final String HEADER_LINES = "SKIPHEADERLINES"; //$NON-NLS-1$
- public static final String COLUMNS = "COLUMNS"; //$NON-NLS-1$
- public static final String TYPES = "TYPES"; //$NON-NLS-1$
-
- /**
- * If HEADER_LINES is non-zero this property defines which row of HEADER_LINES
- * can be used as the header row. The value is 1-based and must be < HEADER_LINES.
- * @since 5.0.3
- */
- public static final String HEADER_ROW = "HEADERLINE"; //$NON-NLS-1$
- /**
- * This property can be used to specify specific date formats for String
- * type results that need to be converted into java.util.Date objects for
- * joins or comparisons. This property will be a String of formats
- * seperated by the DATE_RESULT_FORMATS_DELIMTER property value. No spaces
- * are allowed between these property values and their delimiters.
- */
- public static final String DATE_RESULT_FORMATS = "DateResultFormats"; //$NON-NLS-1$
-
- /**
- * This is the delimiter for the String property value of the DATE_RESULT_FORMATS
- * property.
- */
- public static final String DATE_RESULT_FORMATS_DELIMITER = "DateResultFormatsDelimiter"; //$NON-NLS-1$
-
-
- /**
- * This property can be used to force the edit that ensures the number of
- * columns in the text file matches the number of columns modeled.
- */
- public static final String COLUMN_CNT_MUST_MATCH_MODEL = "EnforceColumnCount"; //$NON-NLS-1$
-
-}
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextSynchExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,869 +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 com.metamatrix.connector.text;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.URL;
-import java.net.URLConnection;
-import java.sql.Date;
-import java.sql.Time;
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.ColumnReference;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.DerivedColumn;
-import org.teiid.connector.language.NamedTable;
-import org.teiid.connector.language.Select;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.Table;
-
-import com.metamatrix.core.util.StringUtil;
-
-/**
- * The essential part that executes the query. It keeps all the execution
- * states.
- */
-public class TextSynchExecution extends BasicExecution implements ResultSetExecution {
- // Command to be executed
- private Select cmd;
-
- // metadata properties
- private Map metadataProps;
-
- private TextManagedConnectionFactory config;
-
- // metadata properties for a given group
- private Properties groupProps = null;
-
- // Translator for String to Data translation
- private StringToDateTranslator stringToDateTranslator;
-
- /**
- * Current index to readerQueue
- */
- private int readerQueueIndex = 0;
- /**
- * Queue of readers that have yet to be read from.
- */
- private ArrayList readerQueue = new ArrayList();
- // current Reader object
- private BufferedReader currentreader = null;
-
- // Line num in the text file
- private int lineNum = 0;
-
- // List of column widths specified
- private List colWidths = new ArrayList();
-
- // the number of modeled columsn should match the
- // number of colums parsed from the file
- private int numModeledColumns = 0;
-
- // If a header row is to be used, this is where the
- // column names will be saved
- private List headerRow = null;
-
- //whether this execution is canceled
- private volatile boolean canceled;
-
- private int rowsProduced = 0;
-
- private int[] cols;
-
- /**
- * Constructor.
- * @param cmd
- * @param txtConn
- */
- public TextSynchExecution(TextManagedConnectionFactory config, Select query, Map <String, Properties> metaProps) {
- this.config = config;
- this.metadataProps = metaProps;
- this.cmd = query;
- }
-
- @Override
- public void execute() throws ConnectorException {
- //translate request
- Object translatedRequest = translateRequest(cmd);
-
- // submit request
- Object response = submitRequest(translatedRequest);
-
- // translate results
- translateResults(response, cmd);
-
- cols = getSelectCols(cmd.getDerivedColumns());
- }
-
- @Override
- public List next() throws ConnectorException, DataNotAvailableException {
- if (canceled) {
- throw new ConnectorException("Execution cancelled"); //$NON-NLS-1$
- }
- Select query = cmd;
-
- Class[] types = query.getColumnTypes();
-
- String location = groupProps.getProperty(TextPropertyNames.LOCATION);
- String delimiter = groupProps.getProperty(TextPropertyNames.DELIMITER);
- String qualifier = groupProps.getProperty(TextPropertyNames.QUALIFIER);
- String topLines = groupProps.getProperty(TextPropertyNames.HEADER_LINES);
-
- // set hasQualifier flag
- boolean hasQualifier = false;
- if (qualifier != null && qualifier.length() > 0) {
- hasQualifier = true;
- }
-
- int numTop = 0;
- if(topLines != null) {
- numTop = Integer.parseInt(topLines);
- }
-
- try {
- while (true) {
- BufferedReader br = getCurrentReader();
- if (br == null) {
- return null;
- }
-
- String line = br.readLine();
-
- // Hit the end of file or the file is empty then
- // try next reader
- if(line == null) {
- advanceToNextReader();
- lineNum = 0;
- continue;
- }
-
- // check if we have a qualifier defined
- // if yes check that all qualifiers have been terminated
- // if not then append the next line (if available)
- if (hasQualifier) {
- while (StringUtil.occurrences(line, qualifier)%2!=0) {
- String nextLine = br.readLine();
- if (nextLine != null) {
- line = line + StringUtil.LINE_SEPARATOR + nextLine;
- } else {
- Object[] params = new Object[] { line };
-
- String msg = TextPlugin.Util.getString("TextSynchExecution.Text_has_no_determined_ending_qualifier", params); //$NON-NLS-1$
- this.config.getLogger().logError(msg);
-
- throw new ConnectorException( msg);
- }
- }
- }
- lineNum++;
-
- //Skip blank lines and any remaining header lines
- if ( line.length() == 0 || numTop >= lineNum ) continue;
-
- // Get record from file for one row
- List record = getRecord(line, delimiter, qualifier, colWidths);
-
- ++rowsProduced;
- // Save selected columns into query results
-
- if (this.config.isEnforceColumnCount() && record.size() != numModeledColumns) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Input_column_cnt_incorrect", new Object[] { new Integer(numModeledColumns), new Integer(record.size()) }));
- }
-
- return getRow(record, cols, types);
- }
- } catch(ConnectorException ce) {
- throw ce;
- } catch(Throwable e) {
- throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Error_reading_text_file", new Object[] { location, e.getMessage() })); //$NON-NLS-1$
- }
- }
-
- /**
- * Gets the current reader, looking at the next
- * one in the list if the current one is null.
- *
- * If HEADER_LINES is greater than 0, an attempt is made to
- * read the column headers from the file. If HEADER_ROW is
- * less than 1, row HEADER_LINES is used as the row that may
- * contain column names. If HEADER_ROW is greater than 1,
- * row HEADER_ROW is used as the row that may contain column
- * names.
- *
- * @throws ConnectorException
- *
- * @since vhalbert 5.0.1
- */
- private BufferedReader getCurrentReader() throws ConnectorException {
- if (currentreader == null && readerQueueIndex < readerQueue.size()) {
- // reader queue index is advanced only by the nextReader()
- // method. Don't do it here.
- currentreader = (BufferedReader)readerQueue.get(readerQueueIndex);
-
- /* Retrieve connector properties so that we can find a
- * header row if necessary.
- */
- String line = null;
- String location = groupProps.getProperty(TextPropertyNames.LOCATION);
- String delimiter = groupProps.getProperty(TextPropertyNames.DELIMITER);
- String qualifier = groupProps.getProperty(TextPropertyNames.QUALIFIER);
- String topLines = groupProps.getProperty(TextPropertyNames.HEADER_LINES);
- String headerLine = groupProps.getProperty(TextPropertyNames.HEADER_ROW);
-
- int numTop = 0;
- int headerRowNum = 0;
- if (topLines != null && topLines.length() > 0)
- numTop = Integer.parseInt(topLines);
- if (headerLine != null && headerLine.length() > 0)
- headerRowNum = Integer.parseInt(headerLine);
-
- if (numTop > 0) {
- /* Check to see if the value for HEADER_ROW is greater than
- * the number of lines to skip. If it is, it is invalid and
- * we will use HEADER_LINES instead.
- */
- if ( headerRowNum > numTop ) {
- Object[] params = new Object[] { TextPropertyNames.HEADER_ROW, new Integer(headerRowNum), new Integer(numTop) };
- String msg = TextPlugin.Util.getString("TextSynchExecution.Property_contains_an_invalid_value_Using_value", params); //$NON-NLS-1$
- // TODO: We should include the group name in the log message.
- this.config.getLogger().logWarning(msg);
-
- headerRowNum = numTop;
- }
- try {
- // set hasQualifier flag
- boolean hasQualifier = false;
- if (qualifier != null && qualifier.length() > 0)
- hasQualifier = true;
-
- // Walk through rows looking for header row
- while (currentreader != null) {
- line = currentreader.readLine();
- // Hit the end of file or the file is empty then
- // try next reader
- if (line == null) {
- advanceToNextReader();
- lineNum = 0;
- return getCurrentReader();
- }
-
- // check if we have a qualifier defined
- // if yes check that all qualifiers have been terminated
- // if not then append the next line (if available)
- if (hasQualifier) {
- while (StringUtil.occurrences(line, qualifier) % 2 != 0) {
- String nextLine = currentreader.readLine();
- if (nextLine != null)
- line = line + StringUtil.LINE_SEPARATOR + nextLine;
- else {
- Object[] params = new Object[] { line };
- String msg = TextPlugin.Util.getString("TextSynchExecution.Text_has_no_determined_ending_qualifier", params); //$NON-NLS-1$
- throw new ConnectorException(msg);
- }
- }
- }
- lineNum++;
-
- // Skip blank lines
- if (line.length() == 0) continue;
-
- // Attempt to retrieve column names from header row
- // or last row of header lines.
- if ((headerRowNum > 0 && headerRowNum == lineNum)
- || (numTop == lineNum)) {
- // This is the header row
- headerRow = getRecord(line, delimiter, qualifier, colWidths);
- break;
- } else if (numTop >= lineNum) continue;
- }
- } catch (Throwable e) {
- throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Error_reading_text_file", new Object[] { location, e.getMessage() })); //$NON-NLS-1$
- }
- }
-
- }
- return currentreader;
- }
-
- /**
- * Indicate that we are done with the current reader and we should
- * advance to the next reader.
- *
- * @since vhalbert 5.0.1
- */
- private void advanceToNextReader(){
- currentreader = null;
- readerQueueIndex++;
- }
-
- public void close() {
- if (readerQueue.size() > 0) {
- for (Iterator it=readerQueue.iterator(); it.hasNext();) {
- BufferedReader br = (BufferedReader) it.next();
- try {
- br.close();
- } catch (IOException err) {
- }
-
- }
- }
- readerQueue.clear();
- this.config.getLogger().logInfo("TextSynchExecution is successfully closed."); //$NON-NLS-1$
- }
-
- public void cancel() {
- canceled = true;
- }
-
- /**
- * Translate command.
- * @param request ICommand as request
- * @return Object translated request
- * @throws ConnectorException if error occurs
- */
- protected Object translateRequest(Command request) throws ConnectorException {
- if (request == null) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Request_is_null")); //$NON-NLS-1$
- }
-
- if (cmd == null) {
- Object[] params = new Object[] { cmd };
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Error_translating_request", params)); //$NON-NLS-1$
- }
-
- // Get the columns widths for all the elements in the group.
- Select query = (Select) request;
-
- /* Defect 13371
- * Can't use the select columns to get the columns widths because we may not be selecting all the columns. Instead,
- * we need to get all the child elements of the group being queried, and get the columns widths of each one of them.
- */
- NamedTable group = (NamedTable)query.getFrom().get(0);
- try {
- /* We need to create the reader queue before we
- * attempt to create the request as we may need
- * column names from the header row.
- */
- String groupName = group.getMetadataObject().getFullName();
- Map metadataMap = metadataProps;
- groupProps = (Properties) metadataMap.get(groupName.toUpperCase());
-
- if(groupProps == null) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Error_obtain_properties_for_group", groupName)); //$NON-NLS-1$
- }
- try {
- createReaders(groupProps,groupName);
- } catch (IOException ex) {
- Object[] params = new Object[] { groupName, ex.getMessage() };
- throw new ConnectorException(ex, TextPlugin.Util.getString("TextSynchExecution.Unable_get_Reader", params)); //$NON-NLS-1$
- }
- List<Column> elements = group.getMetadataObject().getColumns();
- numModeledColumns = elements.size();
- int[] colWidthArray = new int[elements.size()];
- for (int i = 0; i < colWidthArray.length; i++) {
- Column element = elements.get(i);
- colWidthArray[getColumn(element)] = element.getLength();
- }
- for (int i = 0; i < colWidthArray.length; i++) {
- colWidths.add(new Integer(colWidthArray[i]));
- }
- } catch (ConnectorException e) {
- Object[] params = new Object[] { query, e.getMessage() };
- throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Cannot_be_translated_by_the_TextTranslator.", params)); //$NON-NLS-1$
- }
-
- return request;
- }
-
- /**
- * Submit request and get back the metadata necessary for accessing the text file.
- * @param req
- * @return Object
- */
- protected Object submitRequest(Object req) {
- return metadataProps;
- }
-
- /**
- * Translate results.
- * @param response
- * @param cmd
- * @throws ConnectorException
- * @throws ConnectorException
- */
- protected void translateResults(Object response, Command cmd) throws ConnectorException, ConnectorException {
- if(!(response instanceof Map)) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Not_of_type_Map")); //$NON-NLS-1$
- }
-
- // get the group metadataID for group present on the command
- List groups = ((Select) cmd).getFrom();
- NamedTable symbol = (NamedTable) groups.get(0);
- Table group = symbol.getMetadataObject();
-
- String groupName = group.getFullName();
-
- Map metadataMap = (Map) response;
-
- if(this.config.getDateResultFormats() != null) {
- stringToDateTranslator = new StringToDateTranslator(this.config);
- }
-
- groupProps = (Properties) metadataMap.get(groupName.toUpperCase());
- if(groupProps == null) {
- Object[] params = new Object[] { groupName };
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Error_obtain_properties_for_group", params)); //$NON-NLS-1$
- }
-
- performQuery(groupProps,groupName);
- }
-
- /**
- * Helper method for #translateResults(ICommand).
- * @param props Metadata properties for a specific group
- * @throws ConnectorException occurs if IOException happens
- */
- private void performQuery(Properties props,String groupName) throws ConnectorException {
- try {
- createReaders(props,groupName);
- } catch (IOException ex) {
- Object[] params = new Object[] { groupName, ex.getMessage() };
- throw new ConnectorException(ex, TextPlugin.Util.getString("TextSynchExecution.Unable_get_Reader", params)); //$NON-NLS-1$
- }
- }
-
- /**
- * This method gets the reader object for the textfile present either on
- * the local file system or the web.
- * @param props Group's metadata properites string
- * @return BufferReader Object
- */
- private void createReaders(Properties props,String groupName) throws IOException, ConnectorException {
- if(readerQueue != null && readerQueue.size() > 0) {
- return ;
- }
- String fileName = props.getProperty(TextPropertyNames.FILE_LOCATION);
-
-
- if(fileName != null) {
- File datafile = new File(fileName);
- File[] files= TextUtil.getFiles(fileName);
-
-
- // determine if the wild card is used to indicate all files
- // of the specified extension
- if (files != null && files.length > 0) {
- for (int i = 0; i<files.length; i++) {
- File f = files[i];
- addReader(f.getName(), f);
- }
-
- } else {
-
- addReader(fileName, datafile);
-// new BufferedReader(new FileReader(datafile));
-// logger.logInfo("Reading file: " + fileName); //$NON-NLS-1$
-
- }
- } else {
- String urlName = props.getProperty(TextPropertyNames.URL_LOCATION);
- if(urlName==null) {
- Object[] params = new Object[] { groupName };
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Unable_get_Reader_for_group", params)); //$NON-NLS-1$
- }
-
- // create the URL object
- URL url = new URL(urlName);
- // create the connection to the URL
- URLConnection conn = url.openConnection();
- // establish the connection to the URL
- conn.connect();
- // get the stream from the commection
- InputStreamReader inSR = new InputStreamReader(conn.getInputStream());
- // place the stream into a buffered reader
- addReader(fileName, inSR);
-// BufferedReader reader = new BufferedReader(inSR);
-// logger.logInfo("Reading URL: " + urlName); //$NON-NLS-1$
-
- }
-
- }
-
- private void addReader(String fileName, File datafile) throws IOException {
-
- FileInputStream fis = new FileInputStream(datafile);
- InputStreamReader inSR = new InputStreamReader(fis);
-
- BufferedReader r = new BufferedReader(inSR);
- //new FileReader(datafile));
- this.config.getLogger().logInfo("Reading file: " + fileName); //$NON-NLS-1$
- readerQueue.add(r);
- }
-
- private void addReader(String fileName, InputStreamReader inSr) {
- BufferedReader r = new BufferedReader(inSr);
- this.config.getLogger().logInfo("Reading URL: " + fileName); //$NON-NLS-1$
- readerQueue.add(r);
- }
-
- /**
- * Convert selected column names to columns.
- * @param vars List of DataNodeIDs
- * @return Column numbers corresponding to vars
- */
- private int[] getSelectCols(List vars) throws ConnectorException{
- int[] cols = new int[vars.size()];
- for(int i=0; i<vars.size(); i++) {
- cols[i] = getColumn((DerivedColumn)vars.get(i));
- }
- return cols;
- }
-
- /**
- * Get column number in Source by ISelectSymbol
- *
- * An Element is created from the symbol and this method
- * invokes getColumn(Element).
- *
- * @param symbol Identifier to look up the column
- * @return int The column corresponding to that id
- * @throws ConnectorException
- */
- private int getColumn(DerivedColumn symbol) throws ConnectorException{
- return this.getColumn(getElementFromSymbol(symbol));
- }
-
- /**
- * Helper method for getting runtime {@link org.teiid.connector.metadata.runtime.Element} from a
- * {@link org.teiid.connector.language.DerivedColumn}.
- * @param symbol Input ISelectSymbol
- * @return Element returned metadata runtime Element
- */
- private Column getElementFromSymbol(DerivedColumn symbol) {
- ColumnReference expr = (ColumnReference) symbol.getExpression();
- return expr.getMetadataObject();
- }
-
- /**
- * Get column number in Source by Element
- *
- * An attempt is made to parse an int from the Name In Source
- * for the Element. If this fails it is assumed that
- * Name In Source is blank or contains an identifier
- * name. If blank, the Element.getMetadataID().getName()
- * is used otherwise, Name In Source is used.
- * @param elem
- * @return int
- * @throws ConnectorException
- */
- private int getColumn(Column elem) throws ConnectorException{
- String colStr = elem.getNameInSource();
- try {
- // If Name In Source is numeric, it is a column number
- return Integer.parseInt(colStr);
- } catch(NumberFormatException e) {
- // Name In Source was not numeric, so look for a column with a heading matching Name In Source
- if ( colStr == null ) {
- colStr = elem.getName();
- }
- if ( headerRow == null ) getCurrentReader();
- if ( headerRow != null ) {
- for ( int i = 0; i < headerRow.size(); i++ ) {
- if ( colStr.compareToIgnoreCase((String)headerRow.get(i) )==0) return i;
- }
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Column_not_found_in_header_row", new Object[] {colStr, elem.getFullName() } )); //$NON-NLS-1$
- }
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Invalid_column_number", new Object[] {colStr, elem.getFullName() } ) ); //$NON-NLS-1$
- }
- }
-
- /**
- * Open the file, read it, and parse it into memory.
- * @param line the line is being read
- * @param delimiter
- * @param qualifier
- * @param colWidths List of column widths
- * @return List of column values inside the line
- * @throws Exception
- */
- private List getRecord(String line, String delimiter, String qualifier, List colWidths) throws Exception {
- if(delimiter != null) {
- return parseDelimitedLine(line, delimiter, qualifier);
- }
- return parseFixedWidthLine(line, colWidths);
- }
-
- /**
- * @param line line's length will not be 0
- * @return List of parsed columns
- */
- private List parseDelimitedLine(String line, String delimiter, String qualifier) throws Exception {
- // the case with no qualifier
- if (qualifier == null || qualifier.trim().length()==0) {
- // parse on delimiters
- List strs = new ArrayList();
-
- int index = -1;
- while(true) {
- int newIndex = line.indexOf(delimiter, index);
- if(newIndex >= 0) {
- if(index >= 0) {
- // middle column
- addUnqualifiedColumnToList(strs, line.substring(index, newIndex));
- } else {
- // first column
- addUnqualifiedColumnToList(strs, line.substring(0, newIndex));
- }
- index = newIndex+1;
- } else if(index >= 0) {
- // end of line
- addUnqualifiedColumnToList(strs, line.substring(index));
- break;
- } else {
- // only one column
- addUnqualifiedColumnToList(strs, line);
- break;
- }
- }
- return strs;
-
- }
- // the case with qualifier
-
- char delimChar = delimiter.charAt(0);
- char qualChar = qualifier.charAt(0);
- char spaceChar = " ".charAt(0); //$NON-NLS-1$
-
- List columns = new ArrayList();
- int charIndex = 0;
- int totalChars = line.length();
-
- while(charIndex < totalChars) {
- // Read character
- char c = line.charAt(charIndex);
-
- if(c == delimChar) {
- addUnqualifiedColumnToList(columns, null);
- charIndex++; // past delimiter
-
- } else if(c == qualChar) {
- int endQualIndex = charIndex;
- while(true) {
- endQualIndex = line.indexOf(qualChar, endQualIndex+1);
- if(endQualIndex < 0) {
- Object[] params = new Object[] { ""+(columns.size()+1), line }; //$NON-NLS-1$
- // changed to Connectorexception so that the exception is thrown to the user
- // and becomes known a problem, rather than just
- // keeping it internally to the server
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Text_has_no_ending_qualifier", params)); //$NON-NLS-1$
- }
- // skipping escaped qualifier charachters
- if(line.length() > endQualIndex+1) {
- if(line.charAt(endQualIndex+1) == qualChar) {
- endQualIndex = endQualIndex+1;
- continue;
- }
- }
- // quoted column
- columns.add(line.substring(charIndex+1, endQualIndex));
- charIndex = endQualIndex+1; // past quoted column
-
- // Check for extra characters between quote and delimiter
- if(charIndex < totalChars && line.charAt(charIndex) != delimChar) {
- Object[] params = new Object[] { ""+(columns.size()+1), line }; //$NON-NLS-1$
- String msg = TextPlugin.Util.getString("TextSynchExecution.Text_file_must_have_delimiter", params);//$NON-NLS-1$
- // changed to Connectorexception so that the exception is thrown to the user
- // and becomes known a problem, rather than just
- // keeping it internally to the server
- throw new ConnectorException(msg);
-
- }
-
- charIndex++; // past delimiter
- break;
- }
-
- // skip any space between the delimiter
- // and the qualifier
- } else if(c == spaceChar) {
- charIndex++;
-
- } else {
- int endColIndex = line.indexOf(delimChar, charIndex);
- if(endColIndex < 0) {
- // last unquoted column
- addUnqualifiedColumnToList(columns, line.substring(charIndex));
-
- // We know the line is done so we should exit the loop here.
- // If we didn't exit the loop and just advanced the charIndex,
- // we would trip the "line ends in <delim>" case below, which
- // is not valid as we have not ended in a delimiter
- break;
- }
- // middle unquoted column
- addUnqualifiedColumnToList(columns, line.substring(charIndex, endColIndex));
- charIndex = endColIndex+1;
- }
-
- // line ends in <delimiter>
- if(charIndex == totalChars) {
- addUnqualifiedColumnToList(columns, null);
- }
-
- }
-
- return columns;
- }
-
- /**
- * Add column value, if null or length is 0, then add null.
- * @param
- * @param
- */
- private static void addUnqualifiedColumnToList(List list, String col) {
- if(col == null || col.length() == 0) {
- list.add(null);
- } else {
- list.add(col);
- }
- }
-
- /**
- *
- * @param line
- * @param colWidths
- * @return List
- * @throws ConnectorException
- */
- private List parseFixedWidthLine(String line, List colWidths) throws ConnectorException {
- int length = line.length();
- List fields = new ArrayList(colWidths.size());
- Iterator iter = colWidths.iterator();
- int current = 0;
- while(iter.hasNext()) {
- try {
- int width = ((Integer)iter.next()).intValue();
- if(width <= 0) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Column_length_must_be_positive")); //$NON-NLS-1$
- }
-
- int end = current + width;
- if(end > length) {
- end = length;
- }
-
- String colValue = line.substring(current, end).trim();
- if(colValue.length() == 0) {
- fields.add(null);
- } else {
- fields.add(colValue);
- }
- current += width;
- } catch(Exception e) {
- // ignore and fill column with null
- fields.add(null);
- }
- }
-
- return fields;
- }
-
- /**
- * Save selected columns from record into results.
- * @param batch batch to contain the record
- * @param record the record of one row
- * @param columns Columns to save in results
- * @param types Class of all columns' types
- */
- private List getRow(List record, int[] columns, Class[] types) throws ConnectorException {
- List newRecord = new ArrayList(columns.length);
- for(int i=0; i<columns.length; i++) {
- int column = columns[i];
- String value = (String) record.get(column);
- Class type = types[i];
- newRecord.add(convertString(value, type));
- }
- return newRecord;
- }
-
- /**
- * Convert String to Object of correct type.
- * @param value Input Value
- * @param type Input type
- * @return Object translated Object from String
- */
- private Object convertString(String value, Class type) throws ConnectorException {
- if (value==null) {
- return null;
- }
-
- if (type == TypeFacility.RUNTIME_TYPES.STRING) {
- return value;
- }
-
- if (java.util.Date.class.isAssignableFrom(type)) {
- //check defaults first
- try {
- return Timestamp.valueOf(value);
- } catch (IllegalArgumentException e) {
-
- }
- try {
- return Date.valueOf(value);
- } catch (IllegalArgumentException e) {
-
- }
- try {
- return Time.valueOf(value);
- } catch (IllegalArgumentException e) {
-
- }
- //check for overrides
- if (stringToDateTranslator!=null && stringToDateTranslator.hasFormatters()) {
- try {
- return new Timestamp(stringToDateTranslator.translateStringToDate(value).getTime());
- }catch(ParseException ex) {
- throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Unable_translate_String_to_Date", new Object[] { ex.getMessage() })); //$NON-NLS-1$
- }
- }
- }
- return value;
- }
-
-}
-
Deleted: trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextUtil.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/com/metamatrix/connector/text/TextUtil.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/cci/text/TextUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,65 +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 com.metamatrix.connector.text;
-
-import java.io.File;
-
-import com.metamatrix.core.util.FileUtils;
-
-
-/**
- * @since 4.3
- */
-public class TextUtil {
-
- public static boolean usesWildCard(String location) {
- if (location == null) return false;
-
- File datafile = new File(location);
- String fname = datafile.getName();
-
- // determine if the wild card is used to indicate all files
- // of the specified extension
- if (fname.indexOf("*") >= 0) { //$NON-NLS-1$
- return true;
- }
- return false;
- }
- public static File[] getFiles(String location) {
- if (location == null) return null;
-
- File datafile = new File(location);
- String fname = datafile.getName();
-
- // determine if the wild card is used to indicate all files
- // of the specified extension
- if (fname.indexOf("*") >= 0) { //$NON-NLS-1$
-
- File parentDir = datafile.getParentFile();
- String ext = FileUtils.getExtension(fname);
- return FileUtils.findAllFilesInDirectoryHavingExtension(parentDir.getAbsolutePath(), "." + ext); //$NON-NLS-1$
- }
- return null;
-
- }
-}
Modified: trunk/connectors/connector-text/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-text/src/main/rar/META-INF/ra.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/main/rar/META-INF/ra.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,57 +34,13 @@
<license-required>true</license-required>
</license>
<resourceadapter>
- <resourceadapter-class>org.teiid.connector.basic.BasicResourceAdapter</resourceadapter-class>
+ <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
<outbound-resourceadapter>
<connection-definition>
- <managedconnectionfactory-class>com.metamatrix.connector.text.TextManagedConnectionFactory</managedconnectionfactory-class>
+ <managedconnectionfactory-class>org.teiid.resource.cci.text.TextManagedConnectionFactory</managedconnectionfactory-class>
<config-property>
- <description>{$display:"Connector Class",$advanced:"true"}</description>
- <config-property-name>ConnectorClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.text.TextConnector</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Connector Capabilities",$description:"The class to use to provide the Connector Capabilities",$advanced:"true"}</description>
- <config-property-name>CapabilitiesClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>com.metamatrix.connector.text.TextCapabilities</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is Immutable",$description:"Is Immutable, True if the source never changes.",$advanced:"true"}</description>
- <config-property-name>Immutable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is XA Capable",$description:"True, if this connector supports XA Transactions",$advanced:"true"}</description>
- <config-property-name>XaCapable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Exception on Exceeding Max Rows",$description:"Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",$advanced:"true"}</description>
- <config-property-name>ExceptionOnMaxRows</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Maximum Result Rows",$description:"Maximum Result Rows allowed",$advanced:"true"}</description>
- <config-property-name>MaxResultRows</config-property-name>
- <config-property-type>java.lang.Integer</config-property-type>
- <config-property-value>-1</config-property-value>
- </config-property>
-
- <!-- Text Connector Specific properties -->
-
- <config-property>
<description>{$display:"Text File Descriptor",$required:"true"}</description>
<config-property-name>DescriptorFile</config-property-name>
<config-property-type>java.lang.String</config-property-type>
@@ -97,31 +53,11 @@
<config-property-value>true</config-property-value>
</config-property>
- <config-property>
- <description>{$display:"Enforce Column Count",$description:"This forces the number of columns in text file to match what was modeled"}</description>
- <config-property-name>EnforceColumnCount</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Date Result Formats Delimiter",$advanced:"true"}</description>
- <config-property-name>DateResultFormatsDelimiter</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </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>
- <config-property>
- <description>{$display:"Date Result Formats",$advanced:"true"}</description>
- <config-property-name>DateResultFormats</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </config-property>
-
-
- <connectionfactory-interface>org.teiid.connector.api.Connector</connectionfactory-interface>
- <connectionfactory-impl-class>org.teiid.connector.basic.WrappedConnector</connectionfactory-impl-class>
- <connection-interface>org.teiid.connector.api.Connection</connection-interface>
- <connection-impl-class>org.teiid.connector.basic.WrappedConnection</connection-impl-class>
-
</connection-definition>
<transaction-support>NoTransaction</transaction-support>
Copied: trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/text/i18n.properties (from rev 2083, trunk/connectors/connector-text/src/main/resources/com/metamatrix/connector/text/i18n.properties)
===================================================================
--- trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/text/i18n.properties (rev 0)
+++ trunk/connectors/connector-text/src/main/resources/org/teiid/resource/cci/text/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,71 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+StringToDateTranslator.Attempts_to_parse_String__{0}_to_a_java.util.Date_failed_for_the_following_reasons___1=Attempts to parse String: {0} to a java.util.Date failed for the following reasons:
+StringToDateTranslator.There_is_no_format_Strings_found_in_this_formatter_object._n_2=There is no format Strings found in this formatter object.\n
+StringToDateTranslator.Parse_Attempt__{0}_using_format__{1}_failed_for_the_following_reason__{2}_4=Parse Attempt: {0} using format: {1} failed for the following reason: {2}
+StringToDateTranslator.Failed_to_convert_String__{0}_to_a_Date_using_one_of_the_following_format_Strings_that_are_specified_in_the_properties_for_this_Connector__{1}_1=Failed to convert String: {0} to a Date using one of the following format Strings that are specified in the properties for this Connector: {1}
+TextConnection.Descriptor_file_name_is_not_specified._2=Descriptor file name is not specified.
+TextConnection.Error_trying_to_establish_connection_5=Error trying to establish connection
+TextConnection.Error_while_reading_text_file__{0}_1=Error while reading text file: {0}
+TextConnection.Text_file_name_is_not_specified_for_the_group___{0}_2=Text file name is not specified for the group : {0}
+TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3=The value for the property should be an integer. {0}
+TextConnection.The_property_{0}_for_the_group_{1}_is_invalid._4=The property {0} for the group {1} is invalid.
+TextConnection.Error_parsing_property_string_{0}_5=Error parsing property string {0}
+TextConnection.Error_parsing_property_string_{0}__{1}_6=Error parsing property string {0}: {1}
+TextConnection.fileDoesNotExistForGroup=Data file not found at this location: {0}, for group {1}
+TextConnection.Data_file_{0}_found_but_does_not_have_Read_permissions_8=Data file {0} found but does not have Read permissions
+TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_9=Descriptor file does not exist at this location: {0}
+TextConnection.Descriptor_file_{0}_found_but_does_not_have_Read_permissions_10=Descriptor file {0} found but does not have Read permissions
+TextConnection.Couldn__t_find_the_file_of_name_{0}_11=Couldn''t find the file of name {0}
+TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_12=Descriptor file does not exist at this location: {0}
+TextSynchExecution.Request_is_null=The Request is null.
+TextSynchExecution.No_element_in_Select=There are no element in the Select clause.
+TextSynchExecution.Not_of_type_Map=Response submitted for the request is not of type Map as expected.
+TextSynchExecution.Error_reading_text_file=Error while reading text file: {0}: {1}
+TextSynchExecution.Error_translating_request=Error translating request: Command not supported. {0}
+TextSynchExecution.Cannot_be_translated_by_the_TextTranslator.=''{0}'' cannot be translated by the TextTranslator. {1}
+TextSynchExecution.Error_obtain_properties_for_group=Error trying to obtain connector metadata properties for {0}. Group properties are not specified in the descriptor file.
+TextSynchExecution.Unable_get_Reader=Unable to get the Reader for group {0}, exception: {1}
+TextSynchExecution.Unable_get_Reader_for_group=Unable to get the Reader for group {0}. Source file undefined - check log for errors.
+TextSynchExecution.Cant_read_column_number=Cannot read column number from name in source for element. {0}
+TextSynchExecution.Invalid_column_number=Column {0} not found for element {1} and no header row is defined. If a header row cannot be defined, element {1} must define a numeric column number for its name in source property.
+TextSynchExecution.Column_not_found_in_header_row=Column {0} not found for element {1}. Verify column name \"{0}\" is defined in the header row of the text file and that the header row number is correctly defined in the descriptor file.
+TextSynchExecution.Can_read_column_number=Cannot read column number from name in source for element. {0}
+TextSynchExecution.Text_has_no_ending_qualifier=Text file has no ending qualifier in column {0}: [{1}]
+TextSynchExecution.Text_file_must_have_delimiter=Text file must have delimiter after ending qualifier in column {0}: [{1}]
+TextSynchExecution.Column_length_must_be_positive=Error trying to query the text file, column length must be a positive value.
+TextSynchExecution.Got_unknown_type_of_criteria=Got unknown type of criteria: {0}
+TextSynchExecution.Functions_not_supported._14=The criteria: {0} could not be applied to the results. Functions not supported.
+TextSynchExecution.Values_of_different_types=The following criteria cannot be executed because values are of different types: {0}
+TextSynchExecution.Unknown_compare_criteria_type=Unknown compare criteria type: {0}
+TextSynchExecution.Joins_and_Functions_not_supported._18=The criteria: {0} could not be translated by the TextConnectorTranslator. Joins and Functions not supported.
+TextSynchExecution.The_expression_cannot_be_used_as_criteria=The expression: {0} cannot be used as a criteria value in a query against a text file.
+TextSynchExecution.Functions_in_criteria_not_supported._20=The criteria: {0} cannot be translated by the TextConnectorTranslator. Functions in criteria not supported.
+TextSynchExecution.Functions_in_set_criteria_not_supported._21=The criteria: {0} cannot be translated by the TextConnectorTranslator. Functions in set criteria not supported.
+TextSynchExecution.Unable_translate_String_to_Date=Unable to translate String to Date using the format specified. {0}
+TextSynchExecution.Unable_get_Tranform=Unable to get the Tranform from String to {0}
+TextSynchExecution.Unable_to_transform_value=Unable to transform value {0} to Object of type {1}
+TextSynchExecution.Input_column_cnt_incorrect=Expected input file to have {0} columns based on model, but found {1}. This could be caused by misplaced quotes, causing multiple columns to be treated as one.
+TextSynchExecution.Text_has_no_determined_ending_qualifier=Text file has no matching ending qualifier in row {0}
+TextSynchExecution.Property_contains_an_invalid_value_Using_value=Property {0} contains an invalid value of {1}. Using value {2}.
+TextConnector.column_mismatch=Specified types and columns do not match for text table {0}
\ No newline at end of file
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestMultiFileTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestMultiFileTextSynchExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestMultiFileTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,10 +27,10 @@
import java.util.List;
import java.util.Set;
-import org.teiid.connector.api.ConnectorException;
-
import junit.framework.TestCase;
+import org.teiid.resource.ConnectorException;
+
import com.metamatrix.cdk.api.ConnectorHost;
import com.metamatrix.core.util.UnitTestUtil;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -46,7 +46,7 @@
public void testSubmitRequest() throws Exception {
String sql = "SELECT ID FROM Library"; //$NON-NLS-1$
try {
- Util.getConnectorHostWithFakeMetadata(BAD_COUNT_FILE).executeCommand(sql);
+ Util.getConnectorHostWithFakeMetadata().executeCommand(sql, Util.createConnectionFactory(BAD_COUNT_FILE));
fail("Should have failed due to extra column defined in .csv file");//$NON-NLS-1$
} catch (ConnectorException e) {
assertEquals("Expected input file to have 3 columns based on model, but found 4. This could be caused by misplaced quotes, causing multiple columns to be treated as one.", e.getMessage()); //$NON-NLS-1$
@@ -56,7 +56,7 @@
public void testNextBatch3() throws Exception {
String sql = "SELECT ID FROM Library WHERE Author = 'Blind'"; //$NON-NLS-1$
try {
- Util.getConnectorHostWithFakeMetadata(BAD_COUNT_FILE).executeCommand(sql);
+ Util.getConnectorHostWithFakeMetadata().executeCommand(sql, Util.createConnectionFactory(BAD_COUNT_FILE));
fail("Should have failed due to extra column defined in .csv file");//$NON-NLS-1$
} catch (ConnectorException e) {
assertEquals("Expected input file to have 3 columns based on model, but found 4. This could be caused by misplaced quotes, causing multiple columns to be treated as one.", e.getMessage()); //$NON-NLS-1$
@@ -65,9 +65,9 @@
public void testNextBatch2() throws Exception {
String sql = "SELECT ID, PDate, Author FROM Library"; //$NON-NLS-1$
- ConnectorHost host = Util.getConnectorHostWithFakeMetadata(DEFAULT_DESC_FILE);
+ ConnectorHost host = Util.getConnectorHostWithFakeMetadata();
int expectedRows = 4;
- List results = host.executeCommand(sql);
+ List results = host.executeCommand(sql, Util.createConnectionFactory(DEFAULT_DESC_FILE));
assertEquals("Get batch size doesn't match expected one. ", expectedRows, results.size()); //$NON-NLS-1$
// expected values
@@ -103,7 +103,7 @@
*/
public void testDefect13066() throws Exception {
String sql = "SELECT TRADEID FROM SummitData.SUMMITDATA"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFileTest_1.vdb", "SummitData_Descriptor.txt", sql, 500, 4139); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFileTest_1.vdb", UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt", sql, 500, 4139); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -113,7 +113,7 @@
*/
public void testDefect13368() throws Exception {
String sql = "SELECT RATE, DESK FROM SummitData.SUMMITDATA"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFileTest_1.vdb", "SummitData_Descriptor.txt", sql, 5, 4139); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFileTest_1.vdb", UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt", sql, 5, 4139); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -123,18 +123,18 @@
*/
public void testDefect13371() throws Exception {
String sql = " SELECT SUMMITEXTRACTCDM.START, SUMMITEXTRACTCDM.SUMMIT_ID, SUMMITEXTRACTCDM.CURRENCY, SUMMITEXTRACTCDM.AMOUNT, SUMMITEXTRACTCDM.MATURITY, SUMMITEXTRACTCDM.RATE, SUMMITEXTRACTCDM.DESK, SUMMITEXTRACTCDM.CDM_ID FROM SUMMITEXTRACTCDM"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFiles.vdb", "SummitExtractCDM_Descriptor.txt", sql, 500, 52); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFiles.vdb", UnitTestUtil.getTestDataPath() + "/SummitExtractCDM_Descriptor.txt", sql, 500, 52); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testDefect11402() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/** test case 4151 */
public void testCase4151() throws Exception {
String sql = "SELECT COLA, COLB, COLC FROM ThreeColString_Text.testfile"; //$NON-NLS-1$
- Util.helpTestExecution("case4151/MM_00004151.vdb", "testfile-descriptor.txt", sql, 15000, 5); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("case4151/MM_00004151.vdb", UnitTestUtil.getTestDataPath() + "/testfile-descriptor.txt", sql, 15000, 5); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestRowHeaderTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestRowHeaderTextSynchExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestRowHeaderTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,12 +22,14 @@
package com.metamatrix.connector.text;
-import org.teiid.connector.api.ConnectorException;
-
import junit.framework.TestCase;
+import org.teiid.resource.ConnectorException;
+import com.metamatrix.core.util.UnitTestUtil;
+
+
public class TestRowHeaderTextSynchExecution extends TestCase {
public TestRowHeaderTextSynchExecution(String name) {
@@ -41,7 +43,7 @@
*/
public void testRowHeader() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -51,7 +53,7 @@
*/
public void testRowHeader2() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_NoNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -61,7 +63,7 @@
*/
public void testRowHeader3() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_AlphaNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -72,7 +74,7 @@
*/
public void testRowHeader4() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_AlphaDiffNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -82,7 +84,7 @@
*/
public void testRowHeader5() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_NoNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor_HeaderRowTest.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor_HeaderRowTest.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -92,7 +94,7 @@
*/
public void testRowHeader6() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_AlphaDiffNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor_HeaderRowTest.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor_HeaderRowTest.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -102,7 +104,7 @@
*/
public void testRowHeader7() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_NoNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor3.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor3.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -112,7 +114,7 @@
*/
public void testRowHeader8() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_SpaceNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -124,7 +126,7 @@
public void testRowHeader_Error() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_AlphaNameInSource"; //$NON-NLS-1$
try {
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
fail("Should have received ConnectorException due to an invalid header row being defined."); //$NON-NLS-1$
} catch (ConnectorException ce ) {
assertEquals("'SELECT PARTS_AlphaNameInSource.Part_Id, PARTS_AlphaNameInSource.Part_Name, PARTS_AlphaNameInSource.Part_Color, PARTS_AlphaNameInSource.Part_Weight FROM PARTS_AlphaNameInSource' cannot be translated by the TextTranslator. Column Part_Id not found for element Parts.PARTS_AlphaNameInSource.Part_Id. Verify column name \"Part_Id\" is defined in the header row of the text file and that the header row number is correctly defined in the descriptor file.", ce.getMessage()); //$NON-NLS-1$
@@ -141,7 +143,7 @@
*/
public void testRowHeader_Error2() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS_NoNameInSource"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor4.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnection.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnection.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,13 +23,14 @@
package com.metamatrix.connector.text;
import java.util.Map;
-import java.util.Properties;
import junit.framework.TestCase;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.text.TextConnectionFactory;
+import org.teiid.resource.cci.text.TextConnectionImpl;
+import org.teiid.resource.cci.text.TextManagedConnectionFactory;
import com.metamatrix.core.util.UnitTestUtil;
@@ -45,20 +46,14 @@
}
public void testDefect10371() throws Exception {
- Properties props = new Properties();
- String descFile = UnitTestUtil.getTestDataPath() + "/EmployeeTestDataSalary.txt"; //$NON-NLS-1$
- props.put(TextPropertyNames.DESCRIPTOR_FILE, descFile);
-
+ String descFile = UnitTestUtil.getTestDataPath() + "/EmployeeTestDataSalary.txt"; //$NON-NLS-1$
TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
Mockito.stub(config.getDescriptorFile()).toReturn(descFile);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- TextConnector txr = new TextConnector();
- txr.initialize(config);
+ TextConnectionFactory tcf = new TextConnectionFactory(config);
+ TextConnectionImpl conn = (TextConnectionImpl)tcf.getConnection();
- TextConnection conn = (TextConnection)txr.getConnection();
-
- Map actualProps = conn.metadataProps;
+ Map actualProps = conn.getMetadataProperties();
assertNotNull(actualProps);
}
@@ -66,33 +61,28 @@
* Test partial startup property - test default - should default to allow partial startup
*/
public void testCase4284Default() throws Exception {
- Properties props = new Properties();
String descFile = UnitTestUtil.getTestDataPath() + "/testDescriptorDelimited.txt"; //$NON-NLS-1$
TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
Mockito.stub(config.getDescriptorFile()).toReturn(descFile);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
Mockito.stub(config.isPartialStartupAllowed()).toReturn(true);
- TextConnector txr = new TextConnector();
- txr.initialize(config);
+ TextConnectionFactory tcf = new TextConnectionFactory(config);
+ assertNotNull(tcf.getConnection());
}
/**
* Test partial startup property - disallow partial startup
*/
public void testCase4284DisallowPartial() throws Exception {
- Properties props = new Properties();
String descFile = UnitTestUtil.getTestDataPath() + "/testDescriptorDelimited.txt"; //$NON-NLS-1$
TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
Mockito.stub(config.getDescriptorFile()).toReturn(descFile);
Mockito.stub(config.isPartialStartupAllowed()).toReturn(false);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- TextConnector txr = new TextConnector();
try {
- txr.initialize(config);
+ new TextConnectionFactory(config);
fail("expected exception"); //$NON-NLS-1$
} catch (ConnectorException e) {
String m1 = "Error parsing property string text.library2.location"; //$NON-NLS-1$
@@ -110,16 +100,14 @@
* Test partial startup property - allow partial startup
*/
public void testCase4284AllowPartial() throws Exception {
- Properties props = new Properties();
String descFile = UnitTestUtil.getTestDataPath() + "/testDescriptorDelimited.txt"; //$NON-NLS-1$
TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
Mockito.stub(config.getDescriptorFile()).toReturn(descFile);
Mockito.stub(config.isPartialStartupAllowed()).toReturn(true);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- TextConnector txr = new TextConnector();
- txr.initialize(config);
+ TextConnectionFactory tcf = new TextConnectionFactory(config);
+ assertNotNull(tcf.getConnection());
}
}
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnector.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,12 +30,12 @@
import java.util.Properties;
import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.MetadataProvider;
import org.teiid.connector.metadata.runtime.Datatype;
import org.teiid.connector.metadata.runtime.MetadataFactory;
import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.resource.adapter.text.TextExecutionFactory;
+import org.teiid.resource.cci.MetadataProvider;
+import org.teiid.resource.cci.text.TextConnectionFactory;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.util.UnitTestUtil;
@@ -43,31 +43,11 @@
/**
*/
public class TestTextConnector {
- private static final String DESC_FILE = UnitTestUtil.getTestDataPath() + "/testDescriptorDelimited.txt"; //$NON-NLS-1$
- public TextConnector helpSetUp(String descFile) throws Exception {
- Properties props = new Properties();
- props.put(TextPropertyNames.DESCRIPTOR_FILE, descFile);
-
- TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
- Mockito.stub(config.getDescriptorFile()).toReturn(descFile);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- Mockito.stub(config.isPartialStartupAllowed()).toReturn(true);
-
- TextConnector connector = new TextConnector();
- connector.initialize(config);
- return connector;
- }
-
- // descriptor and data file both are files
- @Test public void testGetConnection() throws Exception{
- TextConnector connector = helpSetUp(DESC_FILE);
- TextConnection conn = (TextConnection) connector.getConnection();
- assertNotNull(conn);
- }
-
@Test public void testGetMetadata() throws Exception{
- TextConnector connector = helpSetUp(UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt"); //$NON-NLS-1$
+ TextConnectionFactory tcf = Util.createConnectionFactory(UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt"); //$NON-NLS-1$
+ TextExecutionFactory connector = new TextExecutionFactory();
+
Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
datatypes.put(DataTypeManager.DefaultDataTypes.STRING, new Datatype());
datatypes.put(DataTypeManager.DefaultDataTypes.BIG_INTEGER, new Datatype());
@@ -76,7 +56,7 @@
MetadataFactory metadata = new MetadataFactory("SummitData", datatypes, new Properties()); //$NON-NLS-1$
- ((MetadataProvider)connector.getConnection()).getConnectorMetadata(metadata);
+ ((MetadataProvider)connector).getConnectorMetadata(metadata, tcf);
assertEquals(0, metadata.getMetadataStore().getSchemas().values().iterator().next().getProcedures().size());
Table group = metadata.getMetadataStore().getSchemas().values().iterator().next().getTables().get("summitdata"); //$NON-NLS-1$
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextSynchExecution.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextSynchExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/TestTextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -43,9 +43,9 @@
public void testNextBatch2() throws Exception {
String sql = "SELECT ID, PDate, Author FROM Library"; //$NON-NLS-1$
- ConnectorHost host = Util.getConnectorHostWithFakeMetadata(DEFAULT_DESC_FILE);
+ ConnectorHost host = Util.getConnectorHostWithFakeMetadata();
int expectedRows = 2;
- List results = host.executeCommand(sql);
+ List results = host.executeCommand(sql, Util.createConnectionFactory(DEFAULT_DESC_FILE));
assertEquals("Get batch size doesn't match expected one. ", expectedRows, results.size()); //$NON-NLS-1$
// expected values
@@ -74,7 +74,7 @@
*/
public void testDefect13066() throws Exception {
String sql = "SELECT TRADEID FROM SummitData.SUMMITDATA"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFileTest_1.vdb", "SummitData_Descriptor.txt", sql, 500, 4139); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFileTest_1.vdb", UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt", sql, 500, 4139); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -84,7 +84,7 @@
*/
public void testDefect13368() throws Exception {
String sql = "SELECT RATE, DESK FROM SummitData.SUMMITDATA"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFileTest_1.vdb", "SummitData_Descriptor.txt", sql, 5, 4139); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFileTest_1.vdb", UnitTestUtil.getTestDataPath() + "/SummitData_Descriptor.txt", sql, 5, 4139); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
@@ -94,18 +94,18 @@
*/
public void testDefect13371() throws Exception {
String sql = " SELECT SUMMITEXTRACTCDM.START, SUMMITEXTRACTCDM.SUMMIT_ID, SUMMITEXTRACTCDM.CURRENCY, SUMMITEXTRACTCDM.AMOUNT, SUMMITEXTRACTCDM.MATURITY, SUMMITEXTRACTCDM.RATE, SUMMITEXTRACTCDM.DESK, SUMMITEXTRACTCDM.CDM_ID FROM SUMMITEXTRACTCDM"; //$NON-NLS-1$
- Util.helpTestExecution("summitData/TextFiles.vdb", "SummitExtractCDM_Descriptor.txt", sql, 500, 52); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("summitData/TextFiles.vdb", UnitTestUtil.getTestDataPath() + "/SummitExtractCDM_Descriptor.txt", sql, 500, 52); //$NON-NLS-1$ //$NON-NLS-2$
}
public void testDefect11402() throws Exception {
String sql = "SELECT Part_ID, Part_Name, Part_Color, Part_Weight from PARTS.PARTS"; //$NON-NLS-1$
- Util.helpTestExecution("TextParts/TextParts.vdb", "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("TextParts/TextParts.vdb", UnitTestUtil.getTestDataPath() + "/TextParts/PartsDescriptor.txt", sql, 15000, 21); //$NON-NLS-1$ //$NON-NLS-2$
}
/** test case 4151 */
public void testCase4151() throws Exception {
String sql = "SELECT COLA, COLB, COLC FROM ThreeColString_Text.testfile"; //$NON-NLS-1$
- Util.helpTestExecution("case4151/MM_00004151.vdb", "testfile-descriptor.txt", sql, 15000, 5); //$NON-NLS-1$ //$NON-NLS-2$
+ Util.helpTestExecution("case4151/MM_00004151.vdb", UnitTestUtil.getTestDataPath() + "/testfile-descriptor.txt", sql, 15000, 5); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Modified: trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/Util.java
===================================================================
--- trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/Util.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/connectors/connector-text/src/test/java/com/metamatrix/connector/text/Util.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,13 +28,17 @@
import junit.framework.Assert;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorLogger;
import org.teiid.connector.metadata.runtime.Column;
import org.teiid.connector.metadata.runtime.MetadataStore;
import org.teiid.connector.metadata.runtime.Schema;
import org.teiid.connector.metadata.runtime.Table;
import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.adapter.text.TextConnection;
+import org.teiid.resource.adapter.text.TextExecutionFactory;
+import org.teiid.resource.cci.text.TextConnectionFactory;
+import org.teiid.resource.cci.text.TextConnectionImpl;
+import org.teiid.resource.cci.text.TextManagedConnectionFactory;
import com.metamatrix.cdk.api.ConnectorHost;
import com.metamatrix.cdk.api.TranslationUtility;
@@ -43,35 +47,33 @@
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.unittest.RealMetadataFactory;
+@SuppressWarnings("nls")
public class Util {
static void helpTestExecution(String vdb, String descriptorFile, String sql, int maxBatchSize, int expectedRowCount) throws Exception {
- descriptorFile = UnitTestUtil.getTestDataPath() + File.separator + descriptorFile;
-
- TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
- Mockito.stub(config.getDescriptorFile()).toReturn(descriptorFile);
- Mockito.stub(config.isPartialStartupAllowed()).toReturn(true);
- Mockito.stub(config.getDateResultFormats()).toReturn("yyyy-MM-dd,hh:mm:ss,hh:mm,dd/mm/yyyy");
- Mockito.stub(config.getDateResultFormatsDelimiter()).toReturn(",");
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
+ TextExecutionFactory connector = new TextExecutionFactory();
+ connector.setDateResultFormats("yyyy-MM-dd,hh:mm:ss,hh:mm,dd/mm/yyyy"); //$NON-NLS-1$
+ connector.setDateResultFormatsDelimiter(",");
- ConnectorHost host = new ConnectorHost(new TextConnector(), config, UnitTestUtil.getTestDataPath() + File.separator + vdb);
- List results = host.executeCommand(sql);
+ ConnectorHost host = new ConnectorHost(connector, UnitTestUtil.getTestDataPath() + File.separator + vdb);
+ List results = host.executeCommand(sql, createConnectionFactory(descriptorFile));
Assert.assertEquals("Total row count doesn't match expected size. ", expectedRowCount, results.size()); //$NON-NLS-1$
}
-
- public static ConnectorHost getConnectorHostWithFakeMetadata(String descriptorFile) throws Exception {
+
+ public static TextConnectionFactory createConnectionFactory(String descriptorFile) throws Exception {
TextManagedConnectionFactory config = Mockito.mock(TextManagedConnectionFactory.class);
Mockito.stub(config.getDescriptorFile()).toReturn(descriptorFile);
Mockito.stub(config.isPartialStartupAllowed()).toReturn(true);
- Mockito.stub(config.getDateResultFormats()).toReturn("yyyy-MM-dd,hh:mm:ss,hh:mm,dd/mm/yyyy");
- Mockito.stub(config.getDateResultFormatsDelimiter()).toReturn(",");
- Mockito.stub(config.isEnforceColumnCount()).toReturn(true);
+ return new TextConnectionFactory(config);
+ }
+
+ public static ConnectorHost getConnectorHostWithFakeMetadata() throws Exception {
+ TextExecutionFactory connector = new TextExecutionFactory();
+ connector.setDateResultFormats("yyyy-MM-dd,hh:mm:ss,hh:mm,dd/mm/yyyy"); //$NON-NLS-1$
+ connector.setDateResultFormatsDelimiter(",");
+ connector.setEnforceColumnCount(true);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
-
-
- ConnectorHost host = new ConnectorHost(new TextConnector(), config, new TranslationUtility(exampleText()));
+ ConnectorHost host = new ConnectorHost(connector, new TranslationUtility(exampleText()));
return host;
}
Copied: trunk/connectors/sandbox/translator-yahoo (from rev 2083, trunk/connectors/sandbox/connector-yahoo)
Modified: trunk/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- trunk/connectors/sandbox/connector-yahoo/pom.xml 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/sandbox/translator-yahoo/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,58 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <parent>
- <artifactId>sandbox</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <version>7.0.0-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-yahoo</artifactId>
- <groupId>org.jboss.teiid.connectors.sandbox</groupId>
- <name>Yahoo Connector</name>
- <description>Test connector used to query ticker symbols from Yahoo website</description>
- <packaging>rar</packaging>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-connector-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>
+ <parent>
+ <artifactId>sandbox</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <version>7.0.0-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-connector-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
+ <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>
Added: trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/TickerCollectorVisitor.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/TickerCollectorVisitor.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/TickerCollectorVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,104 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.resource.adapter.yahoo;
+
+import java.util.*;
+
+import org.teiid.connector.language.*;
+import org.teiid.connector.visitor.framework.HierarchyVisitor;
+import org.teiid.resource.ConnectorException;
+
+
+/**
+ */
+public class TickerCollectorVisitor extends HierarchyVisitor {
+
+ private Set tickers = new HashSet();
+ private ConnectorException exception;
+
+ /**
+ *
+ */
+ public TickerCollectorVisitor() {
+ super();
+ }
+
+ public void reset() {
+ tickers = new HashSet();
+ }
+
+ public Set getTickers() {
+ return this.tickers;
+ }
+
+ public ConnectorException getException() {
+ return this.exception;
+ }
+
+ /*
+ * @see com.metamatrix.data.visitor.LanguageObjectVisitor#visit(com.metamatrix.data.language.ICompareCriteria)
+ */
+ public void visit(Comparison obj) {
+ Expression expr = obj.getRightExpression();
+ addTickerFromExpression(expr);
+ }
+
+ /*
+ * @see com.metamatrix.data.visitor.LanguageObjectVisitor#visit(com.metamatrix.data.language.IInCriteria)
+ */
+ public void visit(In obj) {
+ List exprs = obj.getRightExpressions();
+ Iterator iter = exprs.iterator();
+ while(iter.hasNext()) {
+ Expression expr = (Expression) iter.next();
+ addTickerFromExpression(expr);
+ }
+ }
+
+ private void addTickerFromExpression(Expression expr) {
+ if(expr instanceof Literal) {
+ Literal literal = (Literal) expr;
+ if(literal.getType() == String.class) {
+ String ticker = (String) literal.getValue();
+ this.tickers.add(ticker.toUpperCase());
+ } else {
+ this.exception = new ConnectorException(YahooPlugin.Util.getString("TickerCollectorVisitor.Unexpected_type", literal.getType().getName())); //$NON-NLS-1$
+ }
+ } else {
+ this.exception = new ConnectorException(YahooPlugin.Util.getString("TickerCollectorVisitor.Unexpected_expression", expr)); //$NON-NLS-1$
+ }
+
+ }
+
+
+ public static Set getTickers(Condition crit) throws ConnectorException {
+ TickerCollectorVisitor visitor = new TickerCollectorVisitor();
+ crit.acceptVisitor(visitor);
+
+ if(visitor.getException() != null) {
+ throw visitor.getException();
+ }
+ return visitor.getTickers();
+ }
+
+}
Added: trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooCapabilities.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooCapabilities.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.yahoo;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+
+/**
+ * Specifies the capabilities of this connector. The Yahoo connector
+ * supports only some basic criteria capability
+ */
+public class YahooCapabilities extends BasicConnectorCapabilities {
+
+ public static final int YAHOO_MAX_SET_SIZE = 100;
+
+ /**
+ * Construct the capabilities class
+ */
+ public YahooCapabilities() {
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List getSupportedFunctions() {
+ return Collections.EMPTY_LIST;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrCriteria()
+ */
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCompareCriteriaEquals()
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteria()
+ */
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ /**
+ * @see com.metamatrix.connector.jdbc.JDBCCapabilities#getMaxInCriteriaSize()
+ * @since 4.2
+ */
+ public int getMaxInCriteriaSize() {
+ return YAHOO_MAX_SET_SIZE;
+ }
+
+}
Added: trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecution.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecution.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,296 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.yahoo;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.math.BigInteger;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Condition;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ResultSetExecution;
+
+
+/**
+ * Represents the execution of a command.
+ */
+public class YahooExecution extends BasicExecution implements ResultSetExecution {
+
+ public static final String JAVA_PROP_HTTP_PROXY_HOST = "http.proxyHost"; //$NON-NLS-1$
+ public static final String JAVA_PROP_HTTP_PROXY_PORT = "http.proxyPort"; //$NON-NLS-1$
+
+ private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy"); //$NON-NLS-1$
+ private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mma"); //$NON-NLS-1$
+
+ // Connector resources
+ private RuntimeMetadata metadata;
+ private Select command;
+
+ // Execution state
+ List results;
+ int[] neededColumns;
+ int returnIndex = 0;
+ private Select query;
+
+ /**
+ *
+ */
+ public YahooExecution(Select query, RuntimeMetadata metadata) {
+ this.metadata = metadata;
+ this.query = query;
+ }
+
+ /*
+ * @see com.metamatrix.data.SynchQueryExecution#execute(com.metamatrix.data.language.IQuery, int)
+ */
+ @Override
+ public void execute() throws ConnectorException {
+ // Log our command
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Yahoo executing command: " + command); //$NON-NLS-1$
+
+ // Build url
+ String yahooUrl = translateIntoUrl(query);
+
+ // Execute url to get results
+ this.results = executeUrl(yahooUrl);
+
+ // Determine needed columns in results
+ this.neededColumns = getNeededColumns(query.getDerivedColumns(), this.metadata);
+ }
+
+ static String translateIntoUrl(Select query) throws ConnectorException {
+ StringBuffer url = new StringBuffer();
+ url.append(YahooPlugin.Util.getString("YahooExecution.URL_BEGIN")); //$NON-NLS-1$
+
+ Set tickers = getTickers(query);
+ if(tickers.size() == 0) {
+ throw new ConnectorException(YahooPlugin.Util.getString("YahooExecution.No_tickers")); //$NON-NLS-1$
+ }
+ String urlAppendChar = YahooPlugin.Util.getString("YahooExecution.URL_APPEND_CHAR"); //$NON-NLS-1$
+ Iterator tickerIter = tickers.iterator();
+ url.append(tickerIter.next());
+ while(tickerIter.hasNext()) {
+ url.append(urlAppendChar);
+ url.append(tickerIter.next());
+ }
+
+ url.append(YahooPlugin.Util.getString("YahooExecution.URL_END")); //$NON-NLS-1$
+ return url.toString();
+ }
+
+ /**
+ * @return
+ */
+ static Set getTickers(Select query) throws ConnectorException {
+ Condition crit = query.getWhere();
+ if(crit == null) {
+ throw new ConnectorException(YahooPlugin.Util.getString("YahooExecution.Must_have_criteria")); //$NON-NLS-1$
+ }
+ return TickerCollectorVisitor.getTickers(crit);
+ }
+
+ /**
+ * @param yahooUrl
+ * @return
+ */
+ protected List executeUrl(String yahooUrl) throws ConnectorException {
+ List rows = new ArrayList();
+ InputStreamReader inSR = null;
+ BufferedReader buffReader = null;
+
+ try {
+ // create the URL object
+ URL url = new URL(yahooUrl);
+
+ // create the connection to the URL
+ URLConnection conn = url.openConnection();
+
+ // establish the connection to the URL
+ conn.connect();
+
+ // get the stream from the commection
+ inSR = new InputStreamReader(conn.getInputStream());
+
+ // place the stream into a buffered reader
+ buffReader = new BufferedReader(inSR);
+
+ // now read each line from the Yahoo! Source and place
+ // it into a StringBuffer object
+ String line = null;
+ while((line = buffReader.readLine()) != null){
+ rows.add(parseLine(line));
+ }
+ // clean up our opened connections
+ buffReader.close();
+ inSR.close();
+
+ } catch(MalformedURLException mue){
+ throw new ConnectorException(mue, mue.getMessage());
+ } catch(IOException e) {
+ throw new ConnectorException(e, e.getMessage());
+ } finally {
+ buffReader = null;
+ inSR = null;
+ }
+
+ return rows;
+ }
+
+ /**
+ * @param line
+ * @return
+ */
+ static List parseLine(String line) {
+ List row = new ArrayList();
+ StringTokenizer rowToken = new StringTokenizer(line,","); //$NON-NLS-1$
+ for(int i=0; rowToken.hasMoreTokens(); i++){
+ String data = rowToken.nextToken();
+ if(data.charAt(0) == '"') {
+ data = data.substring(1, data.length()-1);
+ }
+
+ if(data.equals("N/A")) { //$NON-NLS-1$
+ row.add(null);
+ } else if(i==1 || i==4 || i== 5 || i==6 || i==7) {
+ row.add(Double.valueOf(data));
+ } else if(i==8) {
+ row.add(new BigInteger(data));
+ } else if(i==2) {
+ if(!data.equals("0")){ //$NON-NLS-1$
+ try {
+ Date date = DATE_FORMAT.parse(data);
+ row.add(new java.sql.Date(date.getTime()));
+ } catch(ParseException e) {
+ Object[] params = new Object[] { data, e.getMessage() };
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, YahooPlugin.Util.getString("YahooExecution.Parse_date_error", params)); //$NON-NLS-1$
+ row.add(null);
+ }
+ } else{
+ row.add(null);
+ }
+ } else if(i==3) {
+ if(!data.equals("0")){ //$NON-NLS-1$
+ try {
+ Date time = TIME_FORMAT.parse(data);
+ row.add(new java.sql.Time(time.getTime()));
+ } catch(ParseException e) {
+ Object[] params = new Object[] { data, e.getMessage() };
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, YahooPlugin.Util.getString("YahooExecution.Parse_time_value", params)); //$NON-NLS-1$
+ row.add(null);
+ }
+ } else {
+ row.add(null);
+ }
+
+ } else {
+ row.add(data);
+ }
+ }
+
+ return row;
+ }
+
+ /**
+ * @param select
+ * @return
+ */
+ static int[] getNeededColumns(List<DerivedColumn> select, RuntimeMetadata metadata) throws ConnectorException {
+ int[] cols = new int[select.size()];
+ Iterator iter = select.iterator();
+ for(int i=0; iter.hasNext(); i++) {
+ DerivedColumn symbol = (DerivedColumn) iter.next();
+ Expression expr = symbol.getExpression();
+ if(expr instanceof ColumnReference) {
+ Column element = ((ColumnReference)expr).getMetadataObject();
+ cols[i] = element.getPosition();
+ } else {
+ throw new ConnectorException(YahooPlugin.Util.getString("YahooExecution.Invalid_select_symbol", expr)); //$NON-NLS-1$
+ }
+ }
+
+ return cols;
+ }
+
+ @Override
+ public List next() throws ConnectorException, DataNotAvailableException {
+ if (returnIndex < results.size()) {
+ List row = (List) results.get(returnIndex++);
+ return projectRow(row, neededColumns);
+ }
+
+ return null;
+ }
+
+
+ /**
+ * @param row
+ * @param neededColumns
+ */
+ static List projectRow(List row, int[] neededColumns) {
+ List output = new ArrayList(neededColumns.length);
+
+ for(int i=0; i<neededColumns.length; i++) {
+ output.add(row.get(neededColumns[i]));
+ }
+
+ return output;
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#close()
+ */
+ @Override
+ public void close() throws ConnectorException {
+ // nothing to do
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#cancel()
+ */
+ @Override
+ public void cancel() throws ConnectorException {
+
+ }
+}
Added: trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecutionFactory.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecutionFactory.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,50 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.yahoo;
+
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ResultSetExecution;
+
+public class YahooExecutionFactory extends BasicExecutionFactory {
+
+ @Override
+ public void start() throws ConnectorException {
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return YahooCapabilities.class;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ return new YahooExecution((Select)command, metadata);
+ }
+}
Added: trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooPlugin.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooPlugin.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/java/org/teiid/resource/adapter/yahoo/YahooPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,32 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.yahoo;
+
+import java.util.ResourceBundle;
+import com.metamatrix.core.BundleUtil;
+
+
+public class YahooPlugin {
+ public static final String PLUGIN_ID = "org.teiid.resource.adapter.yahoo" ; //$NON-NLS-1$
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+}
Added: trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.yahoo.YahooExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/sandbox/translator-yahoo/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/yahoo/i18n.properties
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/yahoo/i18n.properties (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/main/resources/org/teiid/resource/adapter/yahoo/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,33 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+YahooExecution.URL_BEGIN=http://finance.yahoo.com/d/quotes.csv?s=
+YahooExecution.URL_APPEND_CHAR=+
+YahooExecution.URL_END=&f=sl1d1t1c1ohgv&e=.csv
+TickerCollectorVisitor.Unexpected_type=Unable to parse literal of type: {0}
+TickerCollectorVisitor.Unexpected_expression=Unable to parse expression: {0}
+YahooExecution.No_tickers=Yahoo connector must be called with tickers in the criteria
+YahooExecution.Must_have_criteria=Query against Yahoo connector must have criteria
+YahooExecution.Parse_date_error=Unable to parse date value: {0}, got: {1}
+YahooExecution.Parse_time_value=Unable to parse time value: {0}, got: {1}
+YahooExecution.Invalid_select_symbol=Yahoo connector can''t handle {0} in SELECT
+YahooConnector.proxyPortNotSet=HTTP proxy port is not set. The default port number 80 will be used.
Added: trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/yahoo/TestYahooTranslation.java
===================================================================
--- trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/yahoo/TestYahooTranslation.java (rev 0)
+++ trunk/connectors/sandbox/translator-yahoo/src/test/java/org/teiid/resource/adapter/yahoo/TestYahooTranslation.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,61 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.yahoo;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Select;
+import org.teiid.resource.adapter.yahoo.YahooExecution;
+
+import junit.framework.TestCase;
+
+import com.metamatrix.cdk.unittest.FakeTranslationFactory;
+
+public class TestYahooTranslation extends TestCase {
+
+ public void helpTestTranslation(String sql, String expectedUrl) throws Exception {
+ Command command = FakeTranslationFactory.getInstance().getYahooTranslationUtility().parseCommand(sql);
+
+ String url = YahooExecution.translateIntoUrl((Select) command);
+ assertEquals("Did not get expected url", expectedUrl, url); //$NON-NLS-1$
+ }
+
+ public void testURLTranslation1() throws Exception {
+ helpTestTranslation(
+ "SELECT LastTrade FROM Yahoo.QuoteServer WHERE TickerSymbol = 'BA'", //$NON-NLS-1$
+ "http://finance.yahoo.com/d/quotes.csv?s=BA&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$
+ }
+
+ public void testURLTranslation2() throws Exception {
+ helpTestTranslation(
+ "SELECT LastTrade FROM Yahoo.QuoteServer WHERE TickerSymbol IN ('BA', 'MON')", //$NON-NLS-1$
+ "http://finance.yahoo.com/d/quotes.csv?s=MON+BA&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$
+ }
+
+ public void testURLTranslation3() throws Exception {
+ helpTestTranslation(
+ "SELECT LastTrade FROM Yahoo.QuoteServer WHERE TickerSymbol = 'BA' OR TickerSymbol = 'MON'", //$NON-NLS-1$
+ "http://finance.yahoo.com/d/quotes.csv?s=MON+BA&f=sl1d1t1c1ohgv&e=.csv"); //$NON-NLS-1$
+ }
+
+
+}
Copied: trunk/connectors/translator-jdbc (from rev 2083, trunk/connectors/connector-jdbc)
Modified: trunk/connectors/translator-jdbc/pom.xml
===================================================================
--- trunk/connectors/connector-jdbc/pom.xml 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -8,12 +8,11 @@
<version>7.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
- <artifactId>connector-jdbc</artifactId>
+ <artifactId>translator-jdbc</artifactId>
<groupId>org.jboss.teiid.connectors</groupId>
- <name>JDBC Connector</name>
- <packaging>rar</packaging>
+ <name>JDBC Translator</name>
- <description>This project contains connectors for a JDBC source. Currently this is an aggregator for all the JDBC connectors relational databases.</description>
+ <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>
@@ -31,33 +30,27 @@
<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>
-
+ <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
+</project>
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCBaseExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCBaseExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCBaseExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,219 +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.jdbc;
-
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.sql.SQLWarning;
-import java.sql.Statement;
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.jdbc.translator.Translator;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Literal;
-
-/**
- */
-public abstract class JDBCBaseExecution extends BasicExecution {
-
- // ===========================================================================================================================
- // Fields
- // ===========================================================================================================================
-
- // Passed to constructor
- protected Connection connection;
- protected Translator sqlTranslator;
- protected ConnectorLogger logger;
- protected ExecutionContext context;
- protected JDBCManagedConnectionFactory env;
-
- // Derived from properties
- protected boolean trimString;
- protected int fetchSize;
- protected int maxResultRows;
-
- // Set during execution
- protected Statement statement;
-
- // ===========================================================================================================================
- // Constructors
- // ===========================================================================================================================
-
- protected JDBCBaseExecution(Connection connection, ExecutionContext context, JDBCManagedConnectionFactory env) throws ConnectorException {
- this.connection = connection;
- this.sqlTranslator = env.getTranslator();
- this.logger = env.getLogger();
- this.context = context;
- this.env = env;
-
- trimString = env.isTrimStrings();
- fetchSize = (env.getFetchSize() != -1)?env.getFetchSize():context.getBatchSize();
- maxResultRows = env.getMaxResultRows();
-
- //if the connector work needs to throw an excpetion, set the size plus 1
- if (maxResultRows > 0 && env.isExceptionOnMaxRows()) {
- maxResultRows++;
- }
- if (maxResultRows > 0) {
- fetchSize = Math.min(fetchSize, maxResultRows);
- }
- }
-
- /**
- * Return true if this is a batched update
- */
- protected void bindPreparedStatementValues(PreparedStatement stmt, TranslatedCommand tc, int rowCount) throws SQLException {
- List<?> params = tc.getPreparedValues();
-
- for (int row = 0; row < rowCount; row++) {
- for (int i = 0; i< params.size(); i++) {
- Literal paramValue = (Literal)params.get(i);
- Object value = paramValue.getValue();
- if (paramValue.isMultiValued()) {
- value = ((List<?>)value).get(row);
- }
- Class<?> paramType = paramValue.getType();
- sqlTranslator.bindValue(stmt, value, paramType, i+1);
- }
- if (rowCount > 1) {
- stmt.addBatch();
- }
- }
- }
-
- // ===========================================================================================================================
- // Methods
- // ===========================================================================================================================
-
- protected TranslatedCommand translateCommand(Command command) throws ConnectorException {
- TranslatedCommand translatedCommand = new TranslatedCommand(context, sqlTranslator);
- translatedCommand.translateCommand(command);
-
- if (translatedCommand.getSql() != null && this.logger.isDetailEnabled()) {
- this.logger.logDetail("Source-specific command: " + translatedCommand.getSql()); //$NON-NLS-1$
- }
-
- return translatedCommand;
- }
-
- /*
- * @see com.metamatrix.data.Execution#close()
- */
- public synchronized void close() throws ConnectorException {
- try {
- if (statement != null) {
- statement.close();
- }
- } catch (SQLException e) {
- throw new ConnectorException(e);
- }
- }
-
- /*
- * @see com.metamatrix.data.Execution#cancel()
- */
- public synchronized void cancel() throws ConnectorException {
- // if both the DBMS and driver support aborting an SQL
- try {
- if (statement != null) {
- statement.cancel();
- }
- } catch (SQLException e) {
- // Defect 16187 - DataDirect does not support the cancel() method for
- // Statement.cancel() for DB2 and Informix. Here we are tolerant
- // of these and other JDBC drivers that do not support the cancel() operation.
- }
- }
-
- protected void setSizeContraints(Statement statement) throws SQLException {
- if (maxResultRows > 0) {
- statement.setMaxRows(maxResultRows);
- }
- statement.setFetchSize(fetchSize);
- }
-
- protected synchronized Statement getStatement() throws SQLException {
- if (statement != null) {
- statement.close();
- statement = null;
- }
- statement = connection.createStatement();
- setSizeContraints(statement);
- return statement;
- }
-
- protected synchronized CallableStatement getCallableStatement(String sql) throws SQLException {
- if (statement != null) {
- statement.close();
- statement = null;
- }
- statement = connection.prepareCall(sql);
- setSizeContraints(statement);
- return (CallableStatement)statement;
- }
-
- protected synchronized PreparedStatement getPreparedStatement(String sql) throws SQLException {
- if (statement != null) {
- statement.close();
- statement = null;
- }
- statement = connection.prepareStatement(sql);
- setSizeContraints(statement);
- return (PreparedStatement)statement;
- }
-
- /**
- * Returns the JDBC connection used by the execution object.
- *
- * @return Returns the connection.
- * @since 4.1.1
- */
- public Connection getConnection() {
- return this.connection;
- }
-
- public Translator getSqlTranslator() {
- return sqlTranslator;
- }
-
- public void addStatementWarnings() throws SQLException {
- SQLWarning warning = this.statement.getWarnings();
- while (warning != null) {
- SQLWarning toAdd = warning;
- warning = toAdd.getNextWarning();
- toAdd.setNextException(null);
- if (logger.isDetailEnabled()) {
- logger.logDetail(context.getRequestIdentifier() + " Warning: ", warning); //$NON-NLS-1$
- }
- context.addWarning(toAdd);
- }
- this.statement.clearWarnings();
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCCapabilities.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCCapabilities.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,331 +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.jdbc;
-
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-
-
-/**
- */
-public class JDBCCapabilities extends BasicConnectorCapabilities {
-
- /**
- *
- */
- public JDBCCapabilities() {
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#getSupportedFunctions()
- */
- public List<String> getSupportedFunctions() {
- return Arrays.asList(new String[] { "+", "-", "*", "/" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
- }
-
- /**
- * @see org.teiid.connector.basic.BasicConnectorCapabilities#getMaxInCriteriaSize()
- * @since 4.2
- */
- public int getMaxInCriteriaSize() {
- return 1000;
- }
-
- @Override
- public boolean supportsGroupBy() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesAvg()
- */
- public boolean supportsAggregatesAvg() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCount()
- */
- public boolean supportsAggregatesCount() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCountStar()
- */
- public boolean supportsAggregatesCountStar() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesDistinct()
- */
- public boolean supportsAggregatesDistinct() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMax()
- */
- public boolean supportsAggregatesMax() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMin()
- */
- public boolean supportsAggregatesMin() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesSum()
- */
- public boolean supportsAggregatesSum() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsAliasedGroup()
- */
- public boolean supportsAliasedGroup() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsBetweenCriteria()
- */
- public boolean supportsBetweenCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsCaseExpressions()
- */
- public boolean supportsCaseExpressions() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsCompareCriteriaEquals()
- */
- public boolean supportsCompareCriteriaEquals() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsCorrelatedSubqueries()
- */
- public boolean supportsCorrelatedSubqueries() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsExistsCriteria()
- */
- public boolean supportsExistsCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsFullOuterJoins()
- */
- public boolean supportsFullOuterJoins() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteria()
- */
- public boolean supportsInCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteriaSubquery()
- */
- public boolean supportsInCriteriaSubquery() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsIsNullCriteria()
- */
- public boolean supportsIsNullCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteria()
- */
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
- */
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsNotCriteria()
- */
- public boolean supportsNotCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsOrCriteria()
- */
- public boolean supportsOrCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsOrderBy()
- */
- public boolean supportsOrderBy() {
- return true;
- }
-
- @Override
- public boolean supportsOrderByUnrelated() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsOuterJoins()
- */
- public boolean supportsOuterJoins() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
- */
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsScalarSubqueries()
- */
- public boolean supportsScalarSubqueries() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsSearchedCaseExpressions()
- */
- public boolean supportsSearchedCaseExpressions() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsSelectDistinct()
- */
- public boolean supportsSelectDistinct() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.ConnectorCapabilities#supportsSelfJoins()
- */
- public boolean supportsSelfJoins() {
- return true;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsInlineViews()
- */
- public boolean supportsInlineViews() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
- */
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return true;
- }
-
- /**
- * @see org.teiid.connector.basic.BasicConnectorCapabilities#supportsSetQueryOrderBy()
- */
- @Override
- public boolean supportsSetQueryOrderBy() {
- return true;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsUnions()
- */
- public boolean supportsUnions() {
- return true;
- }
-
- @Override
- public boolean supportsBulkUpdate() {
- return true;
- }
-
- @Override
- public boolean supportsBatchedUpdates() {
- return true;
- }
-
- @Override
- public boolean supportsCompareCriteriaOrdered() {
- return true;
- }
-
- @Override
- public SupportedJoinCriteria getSupportedJoinCriteria() {
- return SupportedJoinCriteria.ANY;
- }
-
- @Override
- public boolean supportsHaving() {
- return true;
- }
-
- @Override
- public boolean supportsInnerJoins() {
- return true;
- }
-
- @Override
- public boolean supportsSelectExpression() {
- return true;
- }
-
- @Override
- public boolean supportsInsertWithQueryExpression() {
- return true;
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCConnector.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCConnector.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,100 +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.jdbc;
-
-import java.sql.SQLException;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.sql.DataSource;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.basic.BasicConnector;
-
-import com.metamatrix.core.util.StringUtil;
-
-/**
- * JDBC implementation of Connector interface.
- */
-public class JDBCConnector extends BasicConnector {
-
- private JDBCManagedConnectionFactory config;
- private ConnectorCapabilities capabilities;
-
-
- @Override
- public void initialize(ConnectorEnvironment env) throws ConnectorException {
- super.initialize(env);
-
- this.config = (JDBCManagedConnectionFactory)env;
-
- ConnectorLogger logger = config.getLogger();
-
- logger.logInfo(JDBCPlugin.Util.getString("JDBCConnector.JDBCConnector_initialized._1")); //$NON-NLS-1$
-
-
- // Get the JNDI name for the underlying JDBC source
- String dataSourceName = this.config.getSourceJNDIName();
-
- // Verify required items
- if (!StringUtil.isValid(dataSourceName)) {
- throw new ConnectorException(JDBCPlugin.Util.getString("JDBCSourceConnectionFactory.Missing_JDBC_jndi_1")); //$NON-NLS-1$
- }
-
- capabilities = config.getTranslator().getConnectorCapabilities();
-
- logger.logInfo(JDBCPlugin.Util.getString("JDBCConnector.JDBCConnector_started._4")); //$NON-NLS-1$
- }
-
-
- @Override
- public Connection getConnection() throws ConnectorException {
- DataSource dataSource = getDataSource();
- try {
- // TODO: credential mapping facility is now gone. so, no more re-authenticating user.
- return new JDBCSourceConnection(dataSource.getConnection(), this.config);
- } catch (SQLException e) {
- throw new ConnectorException(e);
- }
- }
-
-
- @Override
- public ConnectorCapabilities getCapabilities() {
- return capabilities;
- }
-
- protected DataSource getDataSource() throws ConnectorException {
- String dsName = this.config.getSourceJNDIName();
- try {
- InitialContext ic = new InitialContext();
- return (DataSource) ic.lookup(dsName);
- } catch (NamingException e) {
- throw new ConnectorException(e,JDBCPlugin.Util.getString("JDBCSourceConnectionFactory.Unable_to_find_jndi_ds", dsName)); //$NON-NLS-1$
- }
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCExecutionException.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCExecutionException.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCExecutionException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,39 +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.jdbc;
-
-import java.sql.SQLException;
-import java.util.Arrays;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-
-
-public class JDBCExecutionException extends ConnectorException {
-
- public JDBCExecutionException(SQLException error,
- TranslatedCommand... commands) {
- super(error.getErrorCode(), commands == null ? error.getMessage() : JDBCPlugin.Util.getString("JDBCQueryExecution.Error_executing_query__1", //$NON-NLS-1$
- error.getMessage(), Arrays.toString(commands)));
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCManagedConnectionFactory.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,119 +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.jdbc;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.basic.BasicManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.Translator;
-
-import com.metamatrix.core.MetaMatrixCoreException;
-import com.metamatrix.core.util.ReflectionHelper;
-import com.metamatrix.core.util.StringUtil;
-
-public class JDBCManagedConnectionFactory extends BasicManagedConnectionFactory {
-
- private static final long serialVersionUID = -6719853084334318668L;
- // JDBC connector properties
- private boolean useBindVariables = false;
- private String databaseTimeZone;
- private String extensionTranslationClassName;
- private String sourceJNDIName;
- private boolean trimStrings=false;
- private boolean useCommentsInSourceQuery = false;
- private int fetchSize = -1;
-
- // derived
- private Translator sqlTranslator;
-
- public boolean isUseBindVariables() {
- return useBindVariables;
- }
-
- public String getDatabaseTimeZone() {
- return databaseTimeZone;
- }
-
- public String getExtensionTranslationClassName() {
- return extensionTranslationClassName;
- }
-
- public Translator getTranslator() throws ConnectorException {
- if (this.sqlTranslator == null) {
- try {
- String className = getExtensionTranslationClassName();
- if (!StringUtil.isValid(className)) {
- this.sqlTranslator = new Translator();
- } else {
- this.sqlTranslator = (Translator)ReflectionHelper.create(className, null, Thread.currentThread().getContextClassLoader());
- }
- sqlTranslator.initialize(this);
- } catch (MetaMatrixCoreException e) {
- throw new ConnectorException(e);
- }
- }
- return this.sqlTranslator;
- }
-
- public String getSourceJNDIName() {
- return sourceJNDIName;
- }
-
- public boolean isTrimStrings() {
- return trimStrings;
- }
-
- public boolean isUseCommentsInSourceQuery() {
- return useCommentsInSourceQuery;
- }
-
- public void setUseBindVariables(Boolean arg0) {
- this.useBindVariables = arg0.booleanValue();
- }
-
- public void setDatabaseTimeZone(String arg0) {
- this.databaseTimeZone = arg0;
- }
-
- public void setExtensionTranslationClassName(String arg0) {
- this.extensionTranslationClassName = arg0;
- }
-
- public void setSourceJNDIName(String arg0) {
- this.sourceJNDIName = arg0;
- }
-
- public void setTrimStrings(Boolean arg0) {
- this.trimStrings = arg0.booleanValue();
- }
-
- public void setUseCommentsInSourceQuery(Boolean arg0) {
- this.useCommentsInSourceQuery = arg0.booleanValue();
- }
-
- public void setFetchSize(Integer arg0) {
- this.fetchSize = arg0.intValue();
- }
-
- public int getFetchSize() {
- return this.fetchSize;
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCMetdataProcessor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,441 +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.jdbc;
-
-import java.sql.Connection;
-import java.sql.DatabaseMetaData;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
-import org.teiid.connector.metadata.runtime.BaseColumn;
-import org.teiid.connector.metadata.runtime.Column;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.Procedure;
-import org.teiid.connector.metadata.runtime.Table;
-import org.teiid.connector.metadata.runtime.BaseColumn.NullType;
-import org.teiid.connector.metadata.runtime.ProcedureParameter.Type;
-
-import com.metamatrix.core.util.StringUtil;
-
-/**
- * Reads from {@link DatabaseMetaData} and creates metadata through the {@link MetadataFactory}.
- */
-public class JDBCMetdataProcessor {
-
- /**
- * A holder for table records that keeps track of catalog and schema information.
- */
- private static class TableInfo {
- private String catalog;
- private String schema;
- private String name;
- private Table table;
-
- public TableInfo(String catalog, String schema, String name, Table table) {
- this.catalog = catalog;
- this.schema = schema;
- this.name = name;
- this.table = table;
- }
- }
-
- private boolean importProcedures;
- private boolean importKeys;
- private boolean importIndexes;
- private String procedureNamePattern;
- private boolean useFullSchemaName;
- private String[] tableTypes;
- private String tableNamePattern;
- private String catalog;
- private String schemaPattern;
- private boolean importApproximateIndexes = true;
- private boolean widenUnsingedTypes = true;
- private boolean quoteNameInSource = true;
- //TODO add an option to not fully qualify name in source
-
- private ConnectorLogger logger;
- private Set<String> unsignedTypes = new HashSet<String>();
- private String quoteString;
-
-
-
- public JDBCMetdataProcessor(ConnectorLogger logger) {
- this.logger = logger;
- }
-
- public void getConnectorMetadata(Connection conn, MetadataFactory metadataFactory)
- throws SQLException, ConnectorException {
- DatabaseMetaData metadata = conn.getMetaData();
-
- quoteString = metadata.getIdentifierQuoteString();
- if (quoteString != null && quoteString.trim().length() == 0) {
- quoteString = null;
- }
-
- if (widenUnsingedTypes) {
- ResultSet rs = metadata.getTypeInfo();
- while (rs.next()) {
- String name = rs.getString(1);
- boolean unsigned = rs.getBoolean(10);
- if (unsigned) {
- unsignedTypes.add(name);
- }
- }
- }
-
- Map<String, TableInfo> tableMap = getTables(metadataFactory, metadata);
-
- if (importKeys) {
- getPrimaryKeys(metadataFactory, metadata, tableMap);
-
- getForeignKeys(metadataFactory, metadata, tableMap);
- }
-
- if (importIndexes) {
- getIndexes(metadataFactory, metadata, tableMap);
- }
-
- if (importProcedures) {
- getProcedures(metadataFactory, metadata);
- }
-
- }
-
- private void getProcedures(MetadataFactory metadataFactory,
- DatabaseMetaData metadata) throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing procedures"); //$NON-NLS-1$
- ResultSet procedures = metadata.getProcedures(catalog, schemaPattern, procedureNamePattern);
- while (procedures.next()) {
- String procedureCatalog = procedures.getString(1);
- String procedureSchema = procedures.getString(2);
- String procedureName = procedures.getString(3);
- String fullProcedureName = getFullyQualifiedName(procedureCatalog, procedureSchema, procedureName);
- Procedure procedure = metadataFactory.addProcedure(useFullSchemaName?fullProcedureName:procedureName);
- procedure.setNameInSource(getFullyQualifiedName(procedureCatalog, procedureSchema, procedureName, true));
- ResultSet columns = metadata.getProcedureColumns(catalog, procedureSchema, procedureName, null);
- while (columns.next()) {
- String columnName = columns.getString(4);
- short columnType = columns.getShort(5);
- int sqlType = columns.getInt(6);
- String typeName = columns.getString(7);
- sqlType = checkForUnsigned(sqlType, typeName);
- if (columnType == DatabaseMetaData.procedureColumnUnknown) {
- continue; //there's a good chance this won't work
- }
- BaseColumn record = null;
- if (columnType == DatabaseMetaData.procedureColumnResult) {
- Column column = metadataFactory.addProcedureResultSetColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(sqlType), procedure);
- record = column;
- column.setNativeType(typeName);
- } else {
- record = metadataFactory.addProcedureParameter(columnName, TypeFacility.getDataTypeNameFromSQLType(sqlType), Type.values()[columnType], procedure);
- }
- record.setPrecision(columns.getInt(8));
- record.setLength(columns.getInt(9));
- record.setScale(columns.getInt(10));
- record.setRadix(columns.getInt(11));
- record.setNullType(NullType.values()[columns.getShort(12)]);
- record.setAnnotation(columns.getString(13));
- }
- }
- procedures.close();
- }
-
- private int checkForUnsigned(int sqlType, String typeName) {
- if (widenUnsingedTypes && unsignedTypes.contains(typeName)) {
- switch (sqlType) {
- case Types.TINYINT:
- sqlType = Types.SMALLINT;
- break;
- case Types.SMALLINT:
- sqlType = Types.INTEGER;
- break;
- case Types.INTEGER:
- sqlType = Types.BIGINT;
- break;
- }
- }
- return sqlType;
- }
-
- private Map<String, TableInfo> getTables(MetadataFactory metadataFactory,
- DatabaseMetaData metadata) throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing tables"); //$NON-NLS-1$
- ResultSet tables = metadata.getTables(catalog, schemaPattern, tableNamePattern, tableTypes);
- Map<String, TableInfo> tableMap = new HashMap<String, TableInfo>();
- while (tables.next()) {
- String tableCatalog = tables.getString(1);
- String tableSchema = tables.getString(2);
- String tableName = tables.getString(3);
- String fullName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
- Table table = metadataFactory.addTable(useFullSchemaName?fullName:tableName);
- table.setNameInSource(getFullyQualifiedName(tableCatalog, tableSchema, tableName, true));
- table.setSupportsUpdate(true);
- String remarks = tables.getString(5);
- table.setAnnotation(remarks);
- tableMap.put(fullName, new TableInfo(tableCatalog, tableSchema, tableName, table));
- tableMap.put(tableName, new TableInfo(tableCatalog, tableSchema, tableName, table));
- }
- tables.close();
-
- getColumns(metadataFactory, metadata, tableMap);
- return tableMap;
- }
-
- private void getColumns(MetadataFactory metadataFactory,
- DatabaseMetaData metadata, Map<String, TableInfo> tableMap)
- throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing columns"); //$NON-NLS-1$
- ResultSet columns = metadata.getColumns(catalog, schemaPattern, tableNamePattern, null);
- int rsColumns = columns.getMetaData().getColumnCount();
- while (columns.next()) {
- String tableCatalog = columns.getString(1);
- String tableSchema = columns.getString(2);
- String tableName = columns.getString(3);
- String fullTableName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
- TableInfo tableInfo = tableMap.get(fullTableName);
- if (tableInfo == null) {
- tableInfo = tableMap.get(tableName);
- if (tableInfo == null) {
- continue;
- }
- }
- String columnName = columns.getString(4);
- int type = columns.getInt(5);
- String typeName = columns.getString(6);
- type = checkForUnsigned(type, typeName);
- //note that the resultset is already ordered by position, so we can rely on just adding columns in order
- Column column = metadataFactory.addColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(type), tableInfo.table);
- column.setNameInSource(quoteName(columnName));
- column.setNativeType(columns.getString(6));
- column.setRadix(columns.getInt(10));
- column.setNullType(NullType.values()[columns.getShort(11)]);
- column.setUpdatable(true);
- String remarks = columns.getString(12);
- column.setAnnotation(remarks);
- column.setCharOctetLength(columns.getInt(16));
- if (rsColumns >= 23) {
- column.setAutoIncremented("YES".equalsIgnoreCase(columns.getString(23))); //$NON-NLS-1$
- }
- }
- columns.close();
- }
-
- private String quoteName(String name) {
- if (quoteNameInSource) {
- return quoteString + StringUtil.replaceAll(name, quoteString, quoteString + quoteString) + quoteString;
- }
- return name;
- }
-
- private void getPrimaryKeys(MetadataFactory metadataFactory,
- DatabaseMetaData metadata, Map<String, TableInfo> tableMap)
- throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing primary keys"); //$NON-NLS-1$
- for (TableInfo tableInfo : tableMap.values()) {
- ResultSet pks = metadata.getPrimaryKeys(tableInfo.catalog, tableInfo.schema, tableInfo.name);
- TreeMap<Short, String> keyColumns = null;
- String pkName = null;
- while (pks.next()) {
- String columnName = pks.getString(4);
- short seqNum = pks.getShort(5);
- if (keyColumns == null) {
- keyColumns = new TreeMap<Short, String>();
- }
- keyColumns.put(seqNum, columnName);
- if (pkName == null) {
- pkName = pks.getString(6);
- if (pkName == null) {
- pkName = "PK_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
- }
- }
- }
- if (keyColumns != null) {
- metadataFactory.addPrimaryKey(pkName, new ArrayList<String>(keyColumns.values()), tableInfo.table);
- }
- pks.close();
- }
- }
-
- private void getForeignKeys(MetadataFactory metadataFactory,
- DatabaseMetaData metadata, Map<String, TableInfo> tableMap) throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing foreign keys"); //$NON-NLS-1$
- for (TableInfo tableInfo : tableMap.values()) {
- ResultSet fks = metadata.getImportedKeys(tableInfo.catalog, tableInfo.schema, tableInfo.name);
- TreeMap<Short, String> keyColumns = null;
- String fkName = null;
- TableInfo pkTable = null;
- short savedSeqNum = Short.MAX_VALUE;
- while (fks.next()) {
- String columnName = fks.getString(8);
- short seqNum = fks.getShort(9);
- if (seqNum <= savedSeqNum) {
- if (keyColumns != null) {
- metadataFactory.addForiegnKey(fkName, new ArrayList<String>(keyColumns.values()), pkTable.table, tableInfo.table);
- }
- keyColumns = new TreeMap<Short, String>();
- fkName = null;
- }
- savedSeqNum = seqNum;
- keyColumns.put(seqNum, columnName);
- if (fkName == null) {
- String tableCatalog = fks.getString(1);
- String tableSchema = fks.getString(2);
- String tableName = fks.getString(3);
- String fullTableName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
- pkTable = tableMap.get(fullTableName);
- if (pkTable == null) {
- throw new ConnectorException(JDBCPlugin.Util.getString("JDBCMetadataProcessor.cannot_find_primary", fullTableName)); //$NON-NLS-1$
- }
- fkName = fks.getString(12);
- if (fkName == null) {
- fkName = "FK_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
- }
- }
- }
- if (keyColumns != null) {
- metadataFactory.addForiegnKey(fkName, new ArrayList<String>(keyColumns.values()), pkTable.table, tableInfo.table);
- }
- fks.close();
- }
- }
-
- private void getIndexes(MetadataFactory metadataFactory,
- DatabaseMetaData metadata, Map<String, TableInfo> tableMap) throws SQLException, ConnectorException {
- logger.logDetail("JDBCMetadataProcessor - Importing index info"); //$NON-NLS-1$
- for (TableInfo tableInfo : tableMap.values()) {
- ResultSet indexInfo = metadata.getIndexInfo(tableInfo.catalog, tableInfo.schema, tableInfo.name, false, importApproximateIndexes);
- TreeMap<Short, String> indexColumns = null;
- String indexName = null;
- short savedOrdinalPosition = Short.MAX_VALUE;
- boolean nonUnique = false;
- while (indexInfo.next()) {
- short type = indexInfo.getShort(7);
- if (type == DatabaseMetaData.tableIndexStatistic) {
- tableInfo.table.setCardinality(indexInfo.getInt(11));
- continue;
- }
- short ordinalPosition = indexInfo.getShort(8);
- if (ordinalPosition <= savedOrdinalPosition) {
- if (indexColumns != null) {
- metadataFactory.addIndex(indexName, nonUnique, new ArrayList<String>(indexColumns.values()), tableInfo.table);
- }
- indexColumns = new TreeMap<Short, String>();
- indexName = null;
- }
- savedOrdinalPosition = ordinalPosition;
- String columnName = indexInfo.getString(9);
- nonUnique = indexInfo.getBoolean(4);
- indexColumns.put(ordinalPosition, columnName);
- if (indexName == null) {
- indexName = indexInfo.getString(6);
- if (indexName == null) {
- indexName = "NDX_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
- }
- }
- }
- if (indexColumns != null) {
- metadataFactory.addIndex(indexName, nonUnique, new ArrayList<String>(indexColumns.values()), tableInfo.table);
- }
- indexInfo.close();
- }
- }
-
- private String getFullyQualifiedName(String catalogName, String schemaName, String objectName) {
- return getFullyQualifiedName(catalogName, schemaName, objectName, false);
- }
-
- private String getFullyQualifiedName(String catalogName, String schemaName, String objectName, boolean quoted) {
- String fullName = (quoted?quoteName(objectName):objectName);
- if (schemaName != null && schemaName.length() > 0) {
- fullName = (quoted?quoteName(schemaName):schemaName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
- }
- if (catalogName != null && catalogName.length() > 0) {
- fullName = (quoted?quoteName(catalogName):catalogName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
- }
- return fullName;
- }
-
-
-
- public void setTableNamePattern(String tableNamePattern) {
- this.tableNamePattern = tableNamePattern;
- }
-
- public void setTableTypes(String[] tableTypes) {
- this.tableTypes = tableTypes;
- }
-
- public void setUseFullSchemaName(boolean useFullSchemaName) {
- this.useFullSchemaName = useFullSchemaName;
- }
-
- public void setProcedureNamePattern(String procedureNamePattern) {
- this.procedureNamePattern = procedureNamePattern;
- }
-
- public void setImportIndexes(boolean importIndexes) {
- this.importIndexes = importIndexes;
- }
-
- public void setImportKeys(boolean importKeys) {
- this.importKeys = importKeys;
- }
-
- public void setImportProcedures(boolean importProcedures) {
- this.importProcedures = importProcedures;
- }
-
- public void setImportApproximateIndexes(boolean importApproximateIndexes) {
- this.importApproximateIndexes = importApproximateIndexes;
- }
-
- public void setWidenUnsingedTypes(boolean widenUnsingedTypes) {
- this.widenUnsingedTypes = widenUnsingedTypes;
- }
-
- public void setQuoteNameInSource(boolean quoteIdentifiers) {
- this.quoteNameInSource = quoteIdentifiers;
- }
-
- // Importer specific properties
- public void setCatalog(String catalog) {
- this.catalog = catalog;
- }
-
- public void setSchemaPattern(String schema) {
- this.schemaPattern = schema;
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCPlugin.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCPlugin.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,41 +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.jdbc;
-
-import java.util.ResourceBundle;
-import com.metamatrix.core.BundleUtil;
-
-/**
- * CommonPlugin
- * <p>Used here in <code>data</code> to have access to the new
- * logging framework for <code>LogManager</code>.</p>
- */
-public class JDBCPlugin { // extends Plugin {
-
- public static final String PLUGIN_ID = "org.teiid.connector.jdbc" ; //$NON-NLS-1$
-
- public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,
- PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCProcedureExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCProcedureExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,116 +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.jdbc;
-
-import java.sql.CallableStatement;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.language.Argument;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.Command;
-
-/**
- */
-public class JDBCProcedureExecution extends JDBCQueryExecution implements ProcedureExecution {
-
- /**
- * @param connection
- * @param sqlTranslator
- * @param logger
- * @param props
- * @param id
- */
- public JDBCProcedureExecution(Command command, Connection connection, ExecutionContext context, JDBCManagedConnectionFactory env) throws ConnectorException {
- super(command, connection, context, env);
- }
-
- @Override
- public void execute() throws ConnectorException {
- Call procedure = (Call)command;
- columnDataTypes = procedure.getResultSetColumnTypes();
-
- //translate command
- TranslatedCommand translatedComm = translateCommand(procedure);
-
- //create statement or CallableStatement and execute
- String sql = translatedComm.getSql();
- try{
- //create parameter index map
- CallableStatement cstmt = getCallableStatement(sql);
- this.results = sqlTranslator.executeStoredProcedure(cstmt, translatedComm, procedure.getReturnType());
- addStatementWarnings();
- }catch(SQLException e){
- throw new ConnectorException(e, JDBCPlugin.Util.getString("JDBCQueryExecution.Error_executing_query__1", sql)); //$NON-NLS-1$
- }
-
- }
-
- @Override
- public List<?> next() throws ConnectorException, DataNotAvailableException {
- if (results == null) {
- return null;
- }
- return super.next();
- }
-
- @Override
- public List<?> getOutputParameterValues() throws ConnectorException {
- try {
- Call proc = (Call)this.command;
- List<Object> result = new ArrayList<Object>();
- int paramIndex = 1;
- if (proc.getReturnType() != null) {
- addParameterValue(result, paramIndex++, proc.getReturnType());
- }
- for (Argument parameter : proc.getArguments()) {
- switch (parameter.getDirection()) {
- case IN:
- paramIndex++;
- break;
- case INOUT:
- case OUT:
- addParameterValue(result, paramIndex++, parameter.getType());
- break;
- }
- }
- return result;
- } catch (SQLException e) {
- throw new ConnectorException(e);
- }
- }
-
- private void addParameterValue(List<Object> result, int paramIndex,
- Class<?> type) throws SQLException {
- Object value = sqlTranslator.retrieveValue((CallableStatement)this.statement, paramIndex, type);
- result.add(value);
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCQueryExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCQueryExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCQueryExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,131 +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.jdbc;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.QueryExpression;
-
-
-/**
- *
- */
-public class JDBCQueryExecution extends JDBCBaseExecution implements ResultSetExecution {
-
- // ===========================================================================================================================
- // Fields
- // ===========================================================================================================================
-
- protected ResultSet results;
- protected Command command;
- protected Class<?>[] columnDataTypes;
-
- // ===========================================================================================================================
- // Constructors
- // ===========================================================================================================================
-
- public JDBCQueryExecution(Command command, Connection connection, ExecutionContext context, JDBCManagedConnectionFactory env) throws ConnectorException {
- super(connection, context, env);
- this.command = command;
- }
-
- @Override
- public void execute() throws ConnectorException {
- // get column types
- columnDataTypes = ((QueryExpression)command).getColumnTypes();
-
- // translate command
- TranslatedCommand translatedComm = translateCommand(command);
-
- String sql = translatedComm.getSql();
-
- try {
-
- if (!translatedComm.isPrepared()) {
- results = getStatement().executeQuery(sql);
- } else {
- PreparedStatement pstatement = getPreparedStatement(sql);
- bindPreparedStatementValues(pstatement, translatedComm, 1);
- results = pstatement.executeQuery();
- }
- addStatementWarnings();
- } catch (SQLException e) {
- throw new JDBCExecutionException(e, translatedComm);
- }
- }
-
- @Override
- public List<?> next() throws ConnectorException, DataNotAvailableException {
- try {
- if (results.next()) {
- // New row for result set
- List<Object> vals = new ArrayList<Object>(columnDataTypes.length);
-
- for (int i = 0; i < columnDataTypes.length; i++) {
- // Convert from 0-based to 1-based
- Object value = sqlTranslator.retrieveValue(results, i+1, columnDataTypes[i]);
- vals.add(value);
- }
-
- return vals;
- }
- } catch (SQLException e) {
- throw new ConnectorException(e,
- JDBCPlugin.Util.getString("JDBCTranslator.Unexpected_exception_translating_results___8", e.getMessage())); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * @see org.teiid.connector.jdbc.JDBCBaseExecution#close()
- */
- public synchronized void close() throws ConnectorException {
- // first we would need to close the result set here then we can close
- // the statement, using the base class.
- if (results != null) {
- try {
- results.close();
- results = null;
- } catch (SQLException e) {
- throw new ConnectorException(e);
- }
- }
- super.close();
- }
-
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCSourceConnection.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCSourceConnection.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCSourceConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.jdbc;
-
-import java.sql.SQLException;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.MetadataProvider;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.jdbc.translator.Translator;
-import org.teiid.connector.language.Call;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.QueryExpression;
-import org.teiid.connector.metadata.runtime.MetadataFactory;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.common.util.PropertiesUtils;
-
-
-/**
- *
- */
-public class JDBCSourceConnection extends BasicConnection implements MetadataProvider{
- protected java.sql.Connection physicalConnection;
- protected JDBCManagedConnectionFactory environment;
- private Translator sqlTranslator;
-
- public JDBCSourceConnection(java.sql.Connection connection, JDBCManagedConnectionFactory environment) throws ConnectorException {
- this.physicalConnection = connection;
- this.environment = environment;
- this.sqlTranslator = environment.getTranslator();
- this.sqlTranslator.afterConnectionCreation(connection);
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new JDBCQueryExecution(command, this.physicalConnection, executionContext, this.environment);
- }
-
- @Override
- public ProcedureExecution createProcedureExecution(Call command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new JDBCProcedureExecution(command, this.physicalConnection, executionContext, this.environment);
- }
-
- @Override
- public UpdateExecution createUpdateExecution(Command command,
- ExecutionContext executionContext, RuntimeMetadata metadata)
- throws ConnectorException {
- return new JDBCUpdateExecution(command, this.physicalConnection, executionContext, this.environment);
- }
-
- @Override
- public void close() {
- closeSourceConnection();
- }
-
- protected void closeSourceConnection() {
- try {
- this.physicalConnection.close();
- } catch(SQLException e) {
- environment.getLogger().logDetail("Exception during close: " + e.getMessage()); //$NON-NLS-1$
- }
- }
-
- @Override
- public void getConnectorMetadata(MetadataFactory metadataFactory) throws ConnectorException {
- try {
- JDBCMetdataProcessor metadataProcessor = new JDBCMetdataProcessor(this.environment.getLogger());
- PropertiesUtils.setBeanProperties(metadataProcessor, metadataFactory.getImportProperties(), "importer"); //$NON-NLS-1$
- metadataProcessor.getConnectorMetadata(this.physicalConnection, metadataFactory);
- } catch (SQLException e) {
- throw new ConnectorException(e);
- }
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCUpdateExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCUpdateExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/JDBCUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,256 +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.jdbc;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.language.BatchedUpdates;
-import org.teiid.connector.language.Command;
-import org.teiid.connector.language.Literal;
-
-
-/**
- */
-public class JDBCUpdateExecution extends JDBCBaseExecution implements UpdateExecution {
-
- private Command command;
- private int[] result;
-
- /**
- * @param connection
- * @param sqlTranslator
- * @param logger
- * @param props
- * @param id
- */
- public JDBCUpdateExecution(Command command, Connection connection, ExecutionContext context, JDBCManagedConnectionFactory env) throws ConnectorException {
- super(connection, context, env);
- this.command = command;
- }
-
- // ===========================================================================================================================
- // Methods
- // ===========================================================================================================================
-
- @Override
- public void execute() throws ConnectorException {
- if (command instanceof BatchedUpdates) {
- result = execute(((BatchedUpdates)command));
- } else {
- // translate command
- TranslatedCommand translatedComm = translateCommand(command);
-
- result = executeTranslatedCommand(translatedComm);
- }
- }
-
- /**
- * @see com.metamatrix.data.api.BatchedUpdatesExecution#execute(org.teiid.connector.language.Command[])
- * @since 4.2
- */
- public int[] execute(BatchedUpdates batchedCommand) throws ConnectorException {
- boolean succeeded = false;
-
- boolean commitType = getAutoCommit(null);
- Command[] commands = batchedCommand.getUpdateCommands().toArray(new Command[batchedCommand.getUpdateCommands().size()]);
- int[] results = new int[commands.length];
-
- TranslatedCommand tCommand = null;
-
- try {
- // temporarily turn the auto commit off, and set it back to what it was
- // before at the end of the command execution.
- if (commitType) {
- connection.setAutoCommit(false);
- }
-
- List<TranslatedCommand> executedCmds = new ArrayList<TranslatedCommand>();
-
- TranslatedCommand previousCommand = null;
-
- for (int i = 0; i < commands.length; i++) {
- tCommand = translateCommand(commands[i]);
- if (tCommand.isPrepared()) {
- PreparedStatement pstmt = null;
- if (previousCommand != null && previousCommand.isPrepared() && previousCommand.getSql().equals(tCommand.getSql())) {
- pstmt = (PreparedStatement)statement;
- } else {
- if (!executedCmds.isEmpty()) {
- executeBatch(i, results, executedCmds);
- }
- pstmt = getPreparedStatement(tCommand.getSql());
- }
- bindPreparedStatementValues(pstmt, tCommand, 1);
- pstmt.addBatch();
- } else {
- if (previousCommand != null && previousCommand.isPrepared()) {
- executeBatch(i, results, executedCmds);
- getStatement();
- }
- if (statement == null) {
- getStatement();
- }
- statement.addBatch(tCommand.getSql());
- }
- executedCmds.add(tCommand);
- previousCommand = tCommand;
- }
- if (!executedCmds.isEmpty()) {
- executeBatch(commands.length, results, executedCmds);
- }
- succeeded = true;
- } catch (SQLException e) {
- throw new JDBCExecutionException(e, tCommand);
- } finally {
- if (commitType) {
- restoreAutoCommit(!succeeded, null);
- }
- }
-
- return results;
- }
-
- private void executeBatch(int commandCount,
- int[] results,
- List<TranslatedCommand> commands) throws ConnectorException {
- try {
- int[] batchResults = statement.executeBatch();
- addStatementWarnings();
- for (int j = 0; j < batchResults.length; j++) {
- results[commandCount - 1 - j] = batchResults[batchResults.length - 1 - j];
- }
- commands.clear();
- } catch (SQLException err) {
- throw new JDBCExecutionException(err, commands.toArray(new TranslatedCommand[commands.size()]));
- }
- }
-
- /**
- * @param translatedComm
- * @throws ConnectorException
- * @since 4.3
- */
- private int[] executeTranslatedCommand(TranslatedCommand translatedComm) throws ConnectorException {
- // create statement or PreparedStatement and execute
- String sql = translatedComm.getSql();
- boolean commitType = false;
- boolean succeeded = false;
- try {
- int updateCount = 0;
- if (!translatedComm.isPrepared()) {
- updateCount = getStatement().executeUpdate(sql);
- } else {
- PreparedStatement pstatement = getPreparedStatement(sql);
- int rowCount = 1;
- for (int i = 0; i< translatedComm.getPreparedValues().size(); i++) {
- Literal paramValue = (Literal)translatedComm.getPreparedValues().get(i);
- if (paramValue.isMultiValued()) {
- rowCount = ((List<?>)paramValue.getValue()).size();
- break;
- }
- }
- if (rowCount > 1) {
- commitType = getAutoCommit(translatedComm);
- if (commitType) {
- connection.setAutoCommit(false);
- }
- }
- bindPreparedStatementValues(pstatement, translatedComm, rowCount);
- if (rowCount > 1) {
- int[] results = pstatement.executeBatch();
-
- for (int i=0; i<results.length; i++) {
- updateCount += results[i];
- }
- succeeded = true;
- } else {
- updateCount = pstatement.executeUpdate();
- }
- }
- addStatementWarnings();
- return new int[] {updateCount};
- } catch (SQLException err) {
- throw new JDBCExecutionException(err, translatedComm);
- } finally {
- if (commitType) {
- restoreAutoCommit(!succeeded, translatedComm);
- }
- }
- }
-
- /**
- * @param command
- * @return
- * @throws ConnectorException
- */
- private boolean getAutoCommit(TranslatedCommand tCommand) throws ConnectorException {
- if (this.context.isTransactional()) {
- return false;
- }
- try {
- return connection.getAutoCommit();
- } catch (SQLException err) {
- throw new JDBCExecutionException(err, tCommand);
- }
- }
-
- /**
- * If the auto comm
- *
- * @param exceptionOccurred
- * @param command
- * @throws ConnectorException
- */
- private void restoreAutoCommit(boolean exceptionOccurred,
- TranslatedCommand tCommand) throws ConnectorException {
- try {
- if (exceptionOccurred) {
- connection.rollback();
- }
- } catch (SQLException err) {
- throw new JDBCExecutionException(err, tCommand);
- } finally {
- try {
- connection.commit(); // in JbossAs setAutocommit = true does not trigger the commit.
- connection.setAutoCommit(true);
- } catch (SQLException err) {
- throw new JDBCExecutionException(err, tCommand);
- }
- }
- }
-
- @Override
- public int[] getUpdateCounts() throws DataNotAvailableException,
- ConnectorException {
- return result;
- }
-}
Deleted: trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/SimpleCapabilities.java
===================================================================
--- trunk/connectors/connector-jdbc/src/main/java/org/teiid/connector/jdbc/SimpleCapabilities.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/connector/jdbc/SimpleCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.connector.jdbc;
-
-import java.util.List;
-
-
-/**
- * This is a "simple" capabilities class that allows criteria but no
- * complicated joins, subqueries, etc to be passed to the connector.
- * This capabilities class may come in handy for testing and for
- * sources that support JDBC but don't support extended JDBC capabilities.
- */
-public class SimpleCapabilities extends JDBCCapabilities {
-
- public SimpleCapabilities() {
- }
-
- @Override
- public int getMaxInCriteriaSize() {
- return 250;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCompareCriteriaEquals()
- */
- public boolean supportsCompareCriteriaEquals() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteria()
- */
- public boolean supportsInCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsIsNullCriteria()
- */
- public boolean supportsIsNullCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteria()
- */
- public boolean supportsLikeCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsNotCriteria()
- */
- public boolean supportsNotCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrCriteria()
- */
- public boolean supportsOrCriteria() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelectDistinct()
- */
- public boolean supportsSelectDistinct() {
- return true;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAliasedGroup()
- */
- public boolean supportsAliasedGroup() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelfJoins()
- */
- public boolean supportsSelfJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOuterJoins()
- */
- public boolean supportsOuterJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsFullOuterJoins()
- */
- public boolean supportsFullOuterJoins() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsBetweenCriteria()
- */
- public boolean supportsBetweenCriteria() {
- return false;
- }
-
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
- */
- public boolean supportsLikeCriteriaEscapeCharacter() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteriaSubquery()
- */
- public boolean supportsInCriteriaSubquery() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsExistsCriteria()
- */
- public boolean supportsExistsCriteria() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
- */
- public boolean supportsQuantifiedCompareCriteriaSome() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
- */
- public boolean supportsQuantifiedCompareCriteriaAll() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrderBy()
- */
- public boolean supportsOrderBy() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesSum()
- */
- public boolean supportsAggregatesSum() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesAvg()
- */
- public boolean supportsAggregatesAvg() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMin()
- */
- public boolean supportsAggregatesMin() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMax()
- */
- public boolean supportsAggregatesMax() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCount()
- */
- public boolean supportsAggregatesCount() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCountStar()
- */
- public boolean supportsAggregatesCountStar() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesDistinct()
- */
- public boolean supportsAggregatesDistinct() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsScalarSubqueries()
- */
- public boolean supportsScalarSubqueries() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCorrelatedSubqueries()
- */
- public boolean supportsCorrelatedSubqueries() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCaseExpressions()
- */
- public boolean supportsCaseExpressions() {
- return false;
- }
-
- /*
- * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSearchedCaseExpressions()
- */
- public boolean supportsSearchedCaseExpressions() {
- return false;
- }
-
- /**
- * Return null to indicate no functions are supported.
- * @return null
- * @see org.teiid.connector.api.ConnectorCapabilities#getSupportedFunctions()
- */
- public List getSupportedFunctions() {
- return null;
- }
-
- public boolean supportsInlineViews() {
- return false;
- }
-
- /**
- * @see org.teiid.connector.api.ConnectorCapabilities#supportsUnions()
- * @since 4.2
- */
- public boolean supportsUnions() {
- return false;
- }
-
- @Override
- public boolean supportsInsertWithQueryExpression() {
- return false;
- }
-
-}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCBaseExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCBaseExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCBaseExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,221 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.util.List;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Literal;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ */
+public abstract class JDBCBaseExecution extends BasicExecution {
+
+ // ===========================================================================================================================
+ // Fields
+ // ===========================================================================================================================
+
+ // Passed to constructor
+ protected Connection connection;
+ protected Translator sqlTranslator;
+ protected ExecutionContext context;
+
+ // Derived from properties
+ protected boolean trimString;
+ protected int fetchSize;
+ protected int maxResultRows;
+
+ // Set during execution
+ protected Statement statement;
+
+ // ===========================================================================================================================
+ // Constructors
+ // ===========================================================================================================================
+
+ protected JDBCBaseExecution(Connection connection, ExecutionContext context, JDBCExecutionFactory env, Translator translator) {
+ this.connection = connection;
+ this.sqlTranslator = translator;
+ this.context = context;
+
+ trimString = env.isTrimStrings();
+ fetchSize = (env.getFetchSize() != -1)?env.getFetchSize():context.getBatchSize();
+ maxResultRows = env.getMaxResultRows();
+
+ //if the connector work needs to throw an excpetion, set the size plus 1
+ if (maxResultRows > 0 && env.isExceptionOnMaxRows()) {
+ maxResultRows++;
+ }
+ if (maxResultRows > 0) {
+ fetchSize = Math.min(fetchSize, maxResultRows);
+ }
+ }
+
+ /**
+ * Return true if this is a batched update
+ */
+ protected void bindPreparedStatementValues(PreparedStatement stmt, TranslatedCommand tc, int rowCount) throws SQLException {
+ List<?> params = tc.getPreparedValues();
+
+ for (int row = 0; row < rowCount; row++) {
+ for (int i = 0; i< params.size(); i++) {
+ Literal paramValue = (Literal)params.get(i);
+ Object value = paramValue.getValue();
+ if (paramValue.isMultiValued()) {
+ value = ((List<?>)value).get(row);
+ }
+ Class<?> paramType = paramValue.getType();
+ sqlTranslator.bindValue(stmt, value, paramType, i+1);
+ }
+ if (rowCount > 1) {
+ stmt.addBatch();
+ }
+ }
+ }
+
+ // ===========================================================================================================================
+ // Methods
+ // ===========================================================================================================================
+
+ protected TranslatedCommand translateCommand(Command command) throws ConnectorException {
+ TranslatedCommand translatedCommand = new TranslatedCommand(context, sqlTranslator);
+ translatedCommand.translateCommand(command);
+
+ if (translatedCommand.getSql() != null && LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL)) {
+ LogManager.logDetail("Source-specific command: " + translatedCommand.getSql()); //$NON-NLS-1$
+ }
+
+ return translatedCommand;
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#close()
+ */
+ public synchronized void close() throws ConnectorException {
+ try {
+ if (statement != null) {
+ statement.close();
+ }
+ if (connection != null) {
+ connection.close();
+ }
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#cancel()
+ */
+ public synchronized void cancel() throws ConnectorException {
+ // if both the DBMS and driver support aborting an SQL
+ try {
+ if (statement != null) {
+ statement.cancel();
+ }
+ } catch (SQLException e) {
+ // Defect 16187 - DataDirect does not support the cancel() method for
+ // Statement.cancel() for DB2 and Informix. Here we are tolerant
+ // of these and other JDBC drivers that do not support the cancel() operation.
+ }
+ }
+
+ protected void setSizeContraints(Statement statement) throws SQLException {
+ if (maxResultRows > 0) {
+ statement.setMaxRows(maxResultRows);
+ }
+ statement.setFetchSize(fetchSize);
+ }
+
+ protected synchronized Statement getStatement() throws SQLException {
+ if (statement != null) {
+ statement.close();
+ statement = null;
+ }
+ statement = connection.createStatement();
+ setSizeContraints(statement);
+ return statement;
+ }
+
+ protected synchronized CallableStatement getCallableStatement(String sql) throws SQLException {
+ if (statement != null) {
+ statement.close();
+ statement = null;
+ }
+ statement = connection.prepareCall(sql);
+ setSizeContraints(statement);
+ return (CallableStatement)statement;
+ }
+
+ protected synchronized PreparedStatement getPreparedStatement(String sql) throws SQLException {
+ if (statement != null) {
+ statement.close();
+ statement = null;
+ }
+ statement = connection.prepareStatement(sql);
+ setSizeContraints(statement);
+ return (PreparedStatement)statement;
+ }
+
+ /**
+ * Returns the JDBC connection used by the execution object.
+ *
+ * @return Returns the connection.
+ * @since 4.1.1
+ */
+ public Connection getConnection() {
+ return this.connection;
+ }
+
+ public Translator getSqlTranslator() {
+ return sqlTranslator;
+ }
+
+ public void addStatementWarnings() throws SQLException {
+ SQLWarning warning = this.statement.getWarnings();
+ while (warning != null) {
+ SQLWarning toAdd = warning;
+ warning = toAdd.getNextWarning();
+ toAdd.setNextException(null);
+ if (LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL)) {
+ LogManager.logDetail(context.getRequestIdentifier() + " Warning: ", warning); //$NON-NLS-1$
+ }
+ context.addWarning(toAdd);
+ }
+ this.statement.clearWarnings();
+ }
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCBaseExecution.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,331 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+
+/**
+ */
+public class JDBCCapabilities extends BasicConnectorCapabilities {
+
+ /**
+ *
+ */
+ public JDBCCapabilities() {
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ return Arrays.asList(new String[] { "+", "-", "*", "/" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#getMaxInCriteriaSize()
+ * @since 4.2
+ */
+ public int getMaxInCriteriaSize() {
+ return 1000;
+ }
+
+ @Override
+ public boolean supportsGroupBy() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesAvg()
+ */
+ public boolean supportsAggregatesAvg() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCount()
+ */
+ public boolean supportsAggregatesCount() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCountStar()
+ */
+ public boolean supportsAggregatesCountStar() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesDistinct()
+ */
+ public boolean supportsAggregatesDistinct() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMax()
+ */
+ public boolean supportsAggregatesMax() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMin()
+ */
+ public boolean supportsAggregatesMin() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesSum()
+ */
+ public boolean supportsAggregatesSum() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAliasedGroup()
+ */
+ public boolean supportsAliasedGroup() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsBetweenCriteria()
+ */
+ public boolean supportsBetweenCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCaseExpressions()
+ */
+ public boolean supportsCaseExpressions() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCompareCriteriaEquals()
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCorrelatedSubqueries()
+ */
+ public boolean supportsCorrelatedSubqueries() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsExistsCriteria()
+ */
+ public boolean supportsExistsCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsFullOuterJoins()
+ */
+ public boolean supportsFullOuterJoins() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteria()
+ */
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteriaSubquery()
+ */
+ public boolean supportsInCriteriaSubquery() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsIsNullCriteria()
+ */
+ public boolean supportsIsNullCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteria()
+ */
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
+ */
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsNotCriteria()
+ */
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrCriteria()
+ */
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrderBy()
+ */
+ public boolean supportsOrderBy() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrderByUnrelated() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOuterJoins()
+ */
+ public boolean supportsOuterJoins() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
+ */
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsScalarSubqueries()
+ */
+ public boolean supportsScalarSubqueries() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSearchedCaseExpressions()
+ */
+ public boolean supportsSearchedCaseExpressions() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSelectDistinct()
+ */
+ public boolean supportsSelectDistinct() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSelfJoins()
+ */
+ public boolean supportsSelfJoins() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsInlineViews()
+ */
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
+ */
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsSetQueryOrderBy()
+ */
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsUnions()
+ */
+ public boolean supportsUnions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsBulkUpdate() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsBatchedUpdates() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+ @Override
+ public SupportedJoinCriteria getSupportedJoinCriteria() {
+ return SupportedJoinCriteria.ANY;
+ }
+
+ @Override
+ public boolean supportsHaving() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInnerJoins() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSelectExpression() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return true;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCCapabilities.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionException.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionException.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionException.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.SQLException;
+import java.util.Arrays;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.translator.jdbc.JDBCPlugin;
+import org.teiid.translator.jdbc.TranslatedCommand;
+
+
+public class JDBCExecutionException extends ConnectorException {
+
+ private static final long serialVersionUID = 1758087499488916573L;
+
+ public JDBCExecutionException(SQLException error,
+ TranslatedCommand... commands) {
+ super(error.getErrorCode(), commands == null ? error.getMessage() : JDBCPlugin.Util.getString("JDBCQueryExecution.Error_executing_query__1", //$NON-NLS-1$
+ error.getMessage(), Arrays.toString(commands)));
+ }
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionException.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,230 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+import javax.sql.DataSource;
+
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.MetadataProvider;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TranslatorProperty;
+import org.teiid.resource.cci.UpdateExecution;
+import org.teiid.translator.jdbc.Translator;
+
+import com.metamatrix.common.util.PropertiesUtils;
+import com.metamatrix.core.MetaMatrixCoreException;
+import com.metamatrix.core.util.ReflectionHelper;
+import com.metamatrix.core.util.StringUtil;
+
+/**
+ * JDBC implementation of Connector interface.
+ */
+public class JDBCExecutionFactory extends BasicExecutionFactory implements MetadataProvider {
+
+ private ConnectorCapabilities capabilities;
+ private Translator sqlTranslator;
+ private boolean useBindVariables;
+ private String databaseTimeZone;
+ private String extensionTranslationClassName;
+ private boolean trimStrings;
+ private boolean useCommentsInSourceQuery;
+ private int fetchSize;
+
+ @Override
+ public void start() throws ConnectorException {
+ super.start();
+ capabilities = getTranslator().getConnectorCapabilities();
+ }
+
+ public Translator getTranslator() throws ConnectorException {
+ if (this.sqlTranslator == null) {
+ try {
+ String className = getExtensionTranslationClassName();
+ if (!StringUtil.isValid(className)) {
+ this.sqlTranslator = new Translator();
+ } else {
+ this.sqlTranslator = (Translator)ReflectionHelper.create(className, null, Thread.currentThread().getContextClassLoader());
+ }
+ sqlTranslator.initialize(this);
+ } catch (MetaMatrixCoreException e) {
+ throw new ConnectorException(e);
+ }
+ }
+ return this.sqlTranslator;
+ }
+
+ @Override
+ public ConnectorCapabilities getCapabilities() {
+ return capabilities;
+ }
+
+ @TranslatorProperty(name="UseBindVariables", display="Use Bind Variables", description="Use prepared statements and bind variables",advanced=true, defaultValue="false")
+ public boolean isUseBindVariables() {
+ return this.useBindVariables;
+ }
+
+ public void setUseBindVariables(boolean useBindVariables) {
+ this.useBindVariables = useBindVariables;
+ }
+
+ @TranslatorProperty(name="DatabaseTimeZone", display="Database time zone", description="Time zone of the database, if different than Integration Server", advanced=true)
+ public String getDatabaseTimeZone() {
+ return this.databaseTimeZone;
+ }
+
+ public void setDatabaseTimeZone(String databaseTimeZone) {
+ this.databaseTimeZone = databaseTimeZone;
+ }
+
+ @TranslatorProperty(name="ExtensionTranslationClassName", display="Extension SQL Translation Class", required=true,
+ defaultValue="org.teiid.translator.jdbc.translator.Translator",
+ allowed= {"org.teiid.translator.jdbc.translator.Translator",
+ "org.teiid.translator.jdbc.access.AccessSQLTranslator",
+ "org.teiid.translator.jdbc.db2.DB2SQLTranslator",
+ "org.teiid.translator.jdbc.derby.DerbySQLTranslator",
+ "org.teiid.translator.jdbc.h2.H2Translator",
+ "org.teiid.translator.jdbc.hsql.HsqlTranslator",
+ "org.teiid.translator.jdbc.mysql.MySQLTranslator",
+ "org.teiid.translator.jdbc.mysql.MySQL5Translator",
+ "org.teiid.translator.jdbc.oracle.OracleSQLTranslator",
+ "org.teiid.translator.jdbc.postgresql.PostgreSQLTranslator",
+ "org.teiid.translator.jdbc.sqlserver.SqlServerSQLTranslator",
+ "org.teiid.translator.jdbc.sybase.SybaseSQLTranslator"
+ })
+ public String getExtensionTranslationClassName() {
+ return this.extensionTranslationClassName;
+ }
+
+ public void setExtensionTranslationClassName(String extensionTranslationClassName) {
+ this.extensionTranslationClassName = extensionTranslationClassName;
+ }
+
+ @TranslatorProperty(name="TrimStrings",display="Trim string flag", description="Right Trim fixed character types returned as Strings - note that the native type must be char or nchar and the source must support the rtrim function.",advanced=true, defaultValue="false")
+ public boolean isTrimStrings() {
+ return this.trimStrings;
+ }
+
+ public void setTrimStrings(boolean trimStrings) {
+ this.trimStrings = trimStrings;
+ }
+
+ @TranslatorProperty(name="UseCommentsInSourceQuery", display="Use informational comments in Source Queries", description="This will embed /*comment*/ style comment with session/request id in source SQL query for informational purposes", advanced=true, defaultValue="false")
+ public boolean isUseCommentsInSourceQuery() {
+ return this.useCommentsInSourceQuery;
+ }
+
+ public void setUseCommentsInSourceQuery(boolean useCommentsInSourceQuery) {
+ this.useCommentsInSourceQuery = useCommentsInSourceQuery;
+ }
+
+
+ @TranslatorProperty(name="FetchSize", display="FetCh Size", description="fetch size used from the connector to its underlying source.", advanced=true, defaultValue="1024")
+ public int getFetchSize() {
+ return this.fetchSize;
+ }
+
+ @Override
+ public boolean isSourceRequired() {
+ return true;
+ }
+
+ public void setFetchSize(int fetchSize) {
+ this.fetchSize = fetchSize;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ DataSource ds = (DataSource)connectionFactory;
+ Connection conn = ds.getConnection();
+ //TODO: This is not correct; this should be only called once for connection creation
+ getTranslator().afterConnectionCreation(conn);
+ return new JDBCQueryExecution(command, conn, executionContext, this, getTranslator());
+ } catch(SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ DataSource ds = (DataSource)connectionFactory;
+ Connection conn = ds.getConnection();
+ //TODO: This is not correct; this should be only called once for connection creation
+ getTranslator().afterConnectionCreation(conn);
+ return new JDBCProcedureExecution(command, conn, executionContext, this, getTranslator());
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ DataSource ds = (DataSource)connectionFactory;
+ Connection conn = ds.getConnection();
+
+ //TODO: This is not correct; this should be only called once for connection creation
+ getTranslator().afterConnectionCreation(conn);
+ return new JDBCUpdateExecution(command, conn, executionContext, this, getTranslator());
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public void getConnectorMetadata(MetadataFactory metadataFactory, Object connectionFactory) throws ConnectorException {
+ try {
+ Connection conn = null;
+ try {
+ DataSource ds = (DataSource)connectionFactory;
+ conn = ds.getConnection();
+
+ JDBCMetdataProcessor metadataProcessor = new JDBCMetdataProcessor();
+ PropertiesUtils.setBeanProperties(metadataProcessor, metadataFactory.getImportProperties(), "importer"); //$NON-NLS-1$
+ metadataProcessor.getConnectorMetadata(conn, metadataFactory);
+ } finally {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCExecutionFactory.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCMetdataProcessor.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCMetdataProcessor.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCMetdataProcessor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,435 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
+import org.teiid.connector.metadata.runtime.BaseColumn;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.connector.metadata.runtime.Procedure;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.connector.metadata.runtime.BaseColumn.NullType;
+import org.teiid.connector.metadata.runtime.ProcedureParameter.Type;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.JDBCPlugin;
+
+import com.metamatrix.core.util.StringUtil;
+
+/**
+ * Reads from {@link DatabaseMetaData} and creates metadata through the {@link MetadataFactory}.
+ */
+public class JDBCMetdataProcessor {
+
+ /**
+ * A holder for table records that keeps track of catalog and schema information.
+ */
+ private static class TableInfo {
+ private String catalog;
+ private String schema;
+ private String name;
+ private Table table;
+
+ public TableInfo(String catalog, String schema, String name, Table table) {
+ this.catalog = catalog;
+ this.schema = schema;
+ this.name = name;
+ this.table = table;
+ }
+ }
+
+ private boolean importProcedures;
+ private boolean importKeys;
+ private boolean importIndexes;
+ private String procedureNamePattern;
+ private boolean useFullSchemaName;
+ private String[] tableTypes;
+ private String tableNamePattern;
+ private String catalog;
+ private String schemaPattern;
+ private boolean importApproximateIndexes = true;
+ private boolean widenUnsingedTypes = true;
+ private boolean quoteNameInSource = true;
+ //TODO add an option to not fully qualify name in source
+
+ private Set<String> unsignedTypes = new HashSet<String>();
+ private String quoteString;
+
+ public void getConnectorMetadata(Connection conn, MetadataFactory metadataFactory)
+ throws SQLException, ConnectorException {
+ DatabaseMetaData metadata = conn.getMetaData();
+
+ quoteString = metadata.getIdentifierQuoteString();
+ if (quoteString != null && quoteString.trim().length() == 0) {
+ quoteString = null;
+ }
+
+ if (widenUnsingedTypes) {
+ ResultSet rs = metadata.getTypeInfo();
+ while (rs.next()) {
+ String name = rs.getString(1);
+ boolean unsigned = rs.getBoolean(10);
+ if (unsigned) {
+ unsignedTypes.add(name);
+ }
+ }
+ }
+
+ Map<String, TableInfo> tableMap = getTables(metadataFactory, metadata);
+
+ if (importKeys) {
+ getPrimaryKeys(metadataFactory, metadata, tableMap);
+
+ getForeignKeys(metadataFactory, metadata, tableMap);
+ }
+
+ if (importIndexes) {
+ getIndexes(metadataFactory, metadata, tableMap);
+ }
+
+ if (importProcedures) {
+ getProcedures(metadataFactory, metadata);
+ }
+
+ }
+
+ private void getProcedures(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata) throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing procedures"); //$NON-NLS-1$
+ ResultSet procedures = metadata.getProcedures(catalog, schemaPattern, procedureNamePattern);
+ while (procedures.next()) {
+ String procedureCatalog = procedures.getString(1);
+ String procedureSchema = procedures.getString(2);
+ String procedureName = procedures.getString(3);
+ String fullProcedureName = getFullyQualifiedName(procedureCatalog, procedureSchema, procedureName);
+ Procedure procedure = metadataFactory.addProcedure(useFullSchemaName?fullProcedureName:procedureName);
+ procedure.setNameInSource(getFullyQualifiedName(procedureCatalog, procedureSchema, procedureName, true));
+ ResultSet columns = metadata.getProcedureColumns(catalog, procedureSchema, procedureName, null);
+ while (columns.next()) {
+ String columnName = columns.getString(4);
+ short columnType = columns.getShort(5);
+ int sqlType = columns.getInt(6);
+ String typeName = columns.getString(7);
+ sqlType = checkForUnsigned(sqlType, typeName);
+ if (columnType == DatabaseMetaData.procedureColumnUnknown) {
+ continue; //there's a good chance this won't work
+ }
+ BaseColumn record = null;
+ if (columnType == DatabaseMetaData.procedureColumnResult) {
+ Column column = metadataFactory.addProcedureResultSetColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(sqlType), procedure);
+ record = column;
+ column.setNativeType(typeName);
+ } else {
+ record = metadataFactory.addProcedureParameter(columnName, TypeFacility.getDataTypeNameFromSQLType(sqlType), Type.values()[columnType], procedure);
+ }
+ record.setPrecision(columns.getInt(8));
+ record.setLength(columns.getInt(9));
+ record.setScale(columns.getInt(10));
+ record.setRadix(columns.getInt(11));
+ record.setNullType(NullType.values()[columns.getShort(12)]);
+ record.setAnnotation(columns.getString(13));
+ }
+ }
+ procedures.close();
+ }
+
+ private int checkForUnsigned(int sqlType, String typeName) {
+ if (widenUnsingedTypes && unsignedTypes.contains(typeName)) {
+ switch (sqlType) {
+ case Types.TINYINT:
+ sqlType = Types.SMALLINT;
+ break;
+ case Types.SMALLINT:
+ sqlType = Types.INTEGER;
+ break;
+ case Types.INTEGER:
+ sqlType = Types.BIGINT;
+ break;
+ }
+ }
+ return sqlType;
+ }
+
+ private Map<String, TableInfo> getTables(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata) throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing tables"); //$NON-NLS-1$
+ ResultSet tables = metadata.getTables(catalog, schemaPattern, tableNamePattern, tableTypes);
+ Map<String, TableInfo> tableMap = new HashMap<String, TableInfo>();
+ while (tables.next()) {
+ String tableCatalog = tables.getString(1);
+ String tableSchema = tables.getString(2);
+ String tableName = tables.getString(3);
+ String fullName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
+ Table table = metadataFactory.addTable(useFullSchemaName?fullName:tableName);
+ table.setNameInSource(getFullyQualifiedName(tableCatalog, tableSchema, tableName, true));
+ table.setSupportsUpdate(true);
+ String remarks = tables.getString(5);
+ table.setAnnotation(remarks);
+ tableMap.put(fullName, new TableInfo(tableCatalog, tableSchema, tableName, table));
+ tableMap.put(tableName, new TableInfo(tableCatalog, tableSchema, tableName, table));
+ }
+ tables.close();
+
+ getColumns(metadataFactory, metadata, tableMap);
+ return tableMap;
+ }
+
+ private void getColumns(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata, Map<String, TableInfo> tableMap)
+ throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing columns"); //$NON-NLS-1$
+ ResultSet columns = metadata.getColumns(catalog, schemaPattern, tableNamePattern, null);
+ int rsColumns = columns.getMetaData().getColumnCount();
+ while (columns.next()) {
+ String tableCatalog = columns.getString(1);
+ String tableSchema = columns.getString(2);
+ String tableName = columns.getString(3);
+ String fullTableName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
+ TableInfo tableInfo = tableMap.get(fullTableName);
+ if (tableInfo == null) {
+ tableInfo = tableMap.get(tableName);
+ if (tableInfo == null) {
+ continue;
+ }
+ }
+ String columnName = columns.getString(4);
+ int type = columns.getInt(5);
+ String typeName = columns.getString(6);
+ type = checkForUnsigned(type, typeName);
+ //note that the resultset is already ordered by position, so we can rely on just adding columns in order
+ Column column = metadataFactory.addColumn(columnName, TypeFacility.getDataTypeNameFromSQLType(type), tableInfo.table);
+ column.setNameInSource(quoteName(columnName));
+ column.setNativeType(columns.getString(6));
+ column.setRadix(columns.getInt(10));
+ column.setNullType(NullType.values()[columns.getShort(11)]);
+ column.setUpdatable(true);
+ String remarks = columns.getString(12);
+ column.setAnnotation(remarks);
+ column.setCharOctetLength(columns.getInt(16));
+ if (rsColumns >= 23) {
+ column.setAutoIncremented("YES".equalsIgnoreCase(columns.getString(23))); //$NON-NLS-1$
+ }
+ }
+ columns.close();
+ }
+
+ private String quoteName(String name) {
+ if (quoteNameInSource) {
+ return quoteString + StringUtil.replaceAll(name, quoteString, quoteString + quoteString) + quoteString;
+ }
+ return name;
+ }
+
+ private void getPrimaryKeys(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata, Map<String, TableInfo> tableMap)
+ throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing primary keys"); //$NON-NLS-1$
+ for (TableInfo tableInfo : tableMap.values()) {
+ ResultSet pks = metadata.getPrimaryKeys(tableInfo.catalog, tableInfo.schema, tableInfo.name);
+ TreeMap<Short, String> keyColumns = null;
+ String pkName = null;
+ while (pks.next()) {
+ String columnName = pks.getString(4);
+ short seqNum = pks.getShort(5);
+ if (keyColumns == null) {
+ keyColumns = new TreeMap<Short, String>();
+ }
+ keyColumns.put(seqNum, columnName);
+ if (pkName == null) {
+ pkName = pks.getString(6);
+ if (pkName == null) {
+ pkName = "PK_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
+ }
+ }
+ }
+ if (keyColumns != null) {
+ metadataFactory.addPrimaryKey(pkName, new ArrayList<String>(keyColumns.values()), tableInfo.table);
+ }
+ pks.close();
+ }
+ }
+
+ private void getForeignKeys(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata, Map<String, TableInfo> tableMap) throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing foreign keys"); //$NON-NLS-1$
+ for (TableInfo tableInfo : tableMap.values()) {
+ ResultSet fks = metadata.getImportedKeys(tableInfo.catalog, tableInfo.schema, tableInfo.name);
+ TreeMap<Short, String> keyColumns = null;
+ String fkName = null;
+ TableInfo pkTable = null;
+ short savedSeqNum = Short.MAX_VALUE;
+ while (fks.next()) {
+ String columnName = fks.getString(8);
+ short seqNum = fks.getShort(9);
+ if (seqNum <= savedSeqNum) {
+ if (keyColumns != null) {
+ metadataFactory.addForiegnKey(fkName, new ArrayList<String>(keyColumns.values()), pkTable.table, tableInfo.table);
+ }
+ keyColumns = new TreeMap<Short, String>();
+ fkName = null;
+ }
+ savedSeqNum = seqNum;
+ keyColumns.put(seqNum, columnName);
+ if (fkName == null) {
+ String tableCatalog = fks.getString(1);
+ String tableSchema = fks.getString(2);
+ String tableName = fks.getString(3);
+ String fullTableName = getFullyQualifiedName(tableCatalog, tableSchema, tableName);
+ pkTable = tableMap.get(fullTableName);
+ if (pkTable == null) {
+ throw new ConnectorException(JDBCPlugin.Util.getString("JDBCMetadataProcessor.cannot_find_primary", fullTableName)); //$NON-NLS-1$
+ }
+ fkName = fks.getString(12);
+ if (fkName == null) {
+ fkName = "FK_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
+ }
+ }
+ }
+ if (keyColumns != null) {
+ metadataFactory.addForiegnKey(fkName, new ArrayList<String>(keyColumns.values()), pkTable.table, tableInfo.table);
+ }
+ fks.close();
+ }
+ }
+
+ private void getIndexes(MetadataFactory metadataFactory,
+ DatabaseMetaData metadata, Map<String, TableInfo> tableMap) throws SQLException, ConnectorException {
+ LogManager.logDetail("JDBCMetadataProcessor - Importing index info"); //$NON-NLS-1$
+ for (TableInfo tableInfo : tableMap.values()) {
+ ResultSet indexInfo = metadata.getIndexInfo(tableInfo.catalog, tableInfo.schema, tableInfo.name, false, importApproximateIndexes);
+ TreeMap<Short, String> indexColumns = null;
+ String indexName = null;
+ short savedOrdinalPosition = Short.MAX_VALUE;
+ boolean nonUnique = false;
+ while (indexInfo.next()) {
+ short type = indexInfo.getShort(7);
+ if (type == DatabaseMetaData.tableIndexStatistic) {
+ tableInfo.table.setCardinality(indexInfo.getInt(11));
+ continue;
+ }
+ short ordinalPosition = indexInfo.getShort(8);
+ if (ordinalPosition <= savedOrdinalPosition) {
+ if (indexColumns != null) {
+ metadataFactory.addIndex(indexName, nonUnique, new ArrayList<String>(indexColumns.values()), tableInfo.table);
+ }
+ indexColumns = new TreeMap<Short, String>();
+ indexName = null;
+ }
+ savedOrdinalPosition = ordinalPosition;
+ String columnName = indexInfo.getString(9);
+ nonUnique = indexInfo.getBoolean(4);
+ indexColumns.put(ordinalPosition, columnName);
+ if (indexName == null) {
+ indexName = indexInfo.getString(6);
+ if (indexName == null) {
+ indexName = "NDX_" + tableInfo.table.getName().toUpperCase(); //$NON-NLS-1$
+ }
+ }
+ }
+ if (indexColumns != null) {
+ metadataFactory.addIndex(indexName, nonUnique, new ArrayList<String>(indexColumns.values()), tableInfo.table);
+ }
+ indexInfo.close();
+ }
+ }
+
+ private String getFullyQualifiedName(String catalogName, String schemaName, String objectName) {
+ return getFullyQualifiedName(catalogName, schemaName, objectName, false);
+ }
+
+ private String getFullyQualifiedName(String catalogName, String schemaName, String objectName, boolean quoted) {
+ String fullName = (quoted?quoteName(objectName):objectName);
+ if (schemaName != null && schemaName.length() > 0) {
+ fullName = (quoted?quoteName(schemaName):schemaName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
+ }
+ if (catalogName != null && catalogName.length() > 0) {
+ fullName = (quoted?quoteName(catalogName):catalogName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
+ }
+ return fullName;
+ }
+
+
+
+ public void setTableNamePattern(String tableNamePattern) {
+ this.tableNamePattern = tableNamePattern;
+ }
+
+ public void setTableTypes(String[] tableTypes) {
+ this.tableTypes = tableTypes;
+ }
+
+ public void setUseFullSchemaName(boolean useFullSchemaName) {
+ this.useFullSchemaName = useFullSchemaName;
+ }
+
+ public void setProcedureNamePattern(String procedureNamePattern) {
+ this.procedureNamePattern = procedureNamePattern;
+ }
+
+ public void setImportIndexes(boolean importIndexes) {
+ this.importIndexes = importIndexes;
+ }
+
+ public void setImportKeys(boolean importKeys) {
+ this.importKeys = importKeys;
+ }
+
+ public void setImportProcedures(boolean importProcedures) {
+ this.importProcedures = importProcedures;
+ }
+
+ public void setImportApproximateIndexes(boolean importApproximateIndexes) {
+ this.importApproximateIndexes = importApproximateIndexes;
+ }
+
+ public void setWidenUnsingedTypes(boolean widenUnsingedTypes) {
+ this.widenUnsingedTypes = widenUnsingedTypes;
+ }
+
+ public void setQuoteNameInSource(boolean quoteIdentifiers) {
+ this.quoteNameInSource = quoteIdentifiers;
+ }
+
+ // Importer specific properties
+ public void setCatalog(String catalog) {
+ this.catalog = catalog;
+ }
+
+ public void setSchemaPattern(String schema) {
+ this.schemaPattern = schema;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCMetdataProcessor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCProcedureExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCProcedureExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,118 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.translator.jdbc.JDBCPlugin;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+/**
+ */
+public class JDBCProcedureExecution extends JDBCQueryExecution implements ProcedureExecution {
+
+ /**
+ * @param connection
+ * @param sqlTranslator
+ * @param logger
+ * @param props
+ * @param id
+ */
+ public JDBCProcedureExecution(Command command, Connection connection, ExecutionContext context, JDBCExecutionFactory env, Translator translator) {
+ super(command, connection, context, env, translator);
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ Call procedure = (Call)command;
+ columnDataTypes = procedure.getResultSetColumnTypes();
+
+ //translate command
+ TranslatedCommand translatedComm = translateCommand(procedure);
+
+ //create statement or CallableStatement and execute
+ String sql = translatedComm.getSql();
+ try{
+ //create parameter index map
+ CallableStatement cstmt = getCallableStatement(sql);
+ this.results = sqlTranslator.executeStoredProcedure(cstmt, translatedComm, procedure.getReturnType());
+ addStatementWarnings();
+ }catch(SQLException e){
+ throw new ConnectorException(e, JDBCPlugin.Util.getString("JDBCQueryExecution.Error_executing_query__1", sql)); //$NON-NLS-1$
+ }
+
+ }
+
+ @Override
+ public List<?> next() throws ConnectorException, DataNotAvailableException {
+ if (results == null) {
+ return null;
+ }
+ return super.next();
+ }
+
+ @Override
+ public List<?> getOutputParameterValues() throws ConnectorException {
+ try {
+ Call proc = (Call)this.command;
+ List<Object> result = new ArrayList<Object>();
+ int paramIndex = 1;
+ if (proc.getReturnType() != null) {
+ addParameterValue(result, paramIndex++, proc.getReturnType());
+ }
+ for (Argument parameter : proc.getArguments()) {
+ switch (parameter.getDirection()) {
+ case IN:
+ paramIndex++;
+ break;
+ case INOUT:
+ case OUT:
+ addParameterValue(result, paramIndex++, parameter.getType());
+ break;
+ }
+ }
+ return result;
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ private void addParameterValue(List<Object> result, int paramIndex,
+ Class<?> type) throws SQLException {
+ Object value = sqlTranslator.retrieveValue((CallableStatement)this.statement, paramIndex, type);
+ result.add(value);
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCProcedureExecution.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCQueryExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCQueryExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCQueryExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,133 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.translator.jdbc.JDBCPlugin;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ *
+ */
+public class JDBCQueryExecution extends JDBCBaseExecution implements ResultSetExecution {
+
+ // ===========================================================================================================================
+ // Fields
+ // ===========================================================================================================================
+
+ protected ResultSet results;
+ protected Command command;
+ protected Class<?>[] columnDataTypes;
+
+ // ===========================================================================================================================
+ // Constructors
+ // ===========================================================================================================================
+
+ public JDBCQueryExecution(Command command, Connection connection, ExecutionContext context, JDBCExecutionFactory env, Translator translator) {
+ super(connection, context, env, translator);
+ this.command = command;
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ // get column types
+ columnDataTypes = ((QueryExpression)command).getColumnTypes();
+
+ // translate command
+ TranslatedCommand translatedComm = translateCommand(command);
+
+ String sql = translatedComm.getSql();
+
+ try {
+
+ if (!translatedComm.isPrepared()) {
+ results = getStatement().executeQuery(sql);
+ } else {
+ PreparedStatement pstatement = getPreparedStatement(sql);
+ bindPreparedStatementValues(pstatement, translatedComm, 1);
+ results = pstatement.executeQuery();
+ }
+ addStatementWarnings();
+ } catch (SQLException e) {
+ throw new JDBCExecutionException(e, translatedComm);
+ }
+ }
+
+ @Override
+ public List<?> next() throws ConnectorException, DataNotAvailableException {
+ try {
+ if (results.next()) {
+ // New row for result set
+ List<Object> vals = new ArrayList<Object>(columnDataTypes.length);
+
+ for (int i = 0; i < columnDataTypes.length; i++) {
+ // Convert from 0-based to 1-based
+ Object value = sqlTranslator.retrieveValue(results, i+1, columnDataTypes[i]);
+ vals.add(value);
+ }
+
+ return vals;
+ }
+ } catch (SQLException e) {
+ throw new ConnectorException(e,
+ JDBCPlugin.Util.getString("JDBCTranslator.Unexpected_exception_translating_results___8", e.getMessage())); //$NON-NLS-1$
+ }
+
+ return null;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.jdbc.JDBCBaseExecution#close()
+ */
+ public synchronized void close() throws ConnectorException {
+ // first we would need to close the result set here then we can close
+ // the statement, using the base class.
+ if (results != null) {
+ try {
+ results.close();
+ results = null;
+ } catch (SQLException e) {
+ throw new ConnectorException(e);
+ }
+ }
+ super.close();
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCQueryExecution.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCUpdateExecution.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCUpdateExecution.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,257 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.BatchedUpdates;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Literal;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.UpdateExecution;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ */
+public class JDBCUpdateExecution extends JDBCBaseExecution implements UpdateExecution {
+
+ private Command command;
+ private int[] result;
+
+ /**
+ * @param connection
+ * @param sqlTranslator
+ * @param logger
+ * @param props
+ * @param id
+ */
+ public JDBCUpdateExecution(Command command, Connection connection, ExecutionContext context, JDBCExecutionFactory env, Translator translator) {
+ super(connection, context, env, translator);
+ this.command = command;
+ }
+
+ // ===========================================================================================================================
+ // Methods
+ // ===========================================================================================================================
+
+ @Override
+ public void execute() throws ConnectorException {
+ if (command instanceof BatchedUpdates) {
+ result = execute(((BatchedUpdates)command));
+ } else {
+ // translate command
+ TranslatedCommand translatedComm = translateCommand(command);
+
+ result = executeTranslatedCommand(translatedComm);
+ }
+ }
+
+ /**
+ * @see com.metamatrix.data.api.BatchedUpdatesExecution#execute(org.teiid.connector.language.Command[])
+ * @since 4.2
+ */
+ public int[] execute(BatchedUpdates batchedCommand) throws ConnectorException {
+ boolean succeeded = false;
+
+ boolean commitType = getAutoCommit(null);
+ Command[] commands = batchedCommand.getUpdateCommands().toArray(new Command[batchedCommand.getUpdateCommands().size()]);
+ int[] results = new int[commands.length];
+
+ TranslatedCommand tCommand = null;
+
+ try {
+ // temporarily turn the auto commit off, and set it back to what it was
+ // before at the end of the command execution.
+ if (commitType) {
+ connection.setAutoCommit(false);
+ }
+
+ List<TranslatedCommand> executedCmds = new ArrayList<TranslatedCommand>();
+
+ TranslatedCommand previousCommand = null;
+
+ for (int i = 0; i < commands.length; i++) {
+ tCommand = translateCommand(commands[i]);
+ if (tCommand.isPrepared()) {
+ PreparedStatement pstmt = null;
+ if (previousCommand != null && previousCommand.isPrepared() && previousCommand.getSql().equals(tCommand.getSql())) {
+ pstmt = (PreparedStatement)statement;
+ } else {
+ if (!executedCmds.isEmpty()) {
+ executeBatch(i, results, executedCmds);
+ }
+ pstmt = getPreparedStatement(tCommand.getSql());
+ }
+ bindPreparedStatementValues(pstmt, tCommand, 1);
+ pstmt.addBatch();
+ } else {
+ if (previousCommand != null && previousCommand.isPrepared()) {
+ executeBatch(i, results, executedCmds);
+ getStatement();
+ }
+ if (statement == null) {
+ getStatement();
+ }
+ statement.addBatch(tCommand.getSql());
+ }
+ executedCmds.add(tCommand);
+ previousCommand = tCommand;
+ }
+ if (!executedCmds.isEmpty()) {
+ executeBatch(commands.length, results, executedCmds);
+ }
+ succeeded = true;
+ } catch (SQLException e) {
+ throw new JDBCExecutionException(e, tCommand);
+ } finally {
+ if (commitType) {
+ restoreAutoCommit(!succeeded, null);
+ }
+ }
+
+ return results;
+ }
+
+ private void executeBatch(int commandCount,
+ int[] results,
+ List<TranslatedCommand> commands) throws ConnectorException {
+ try {
+ int[] batchResults = statement.executeBatch();
+ addStatementWarnings();
+ for (int j = 0; j < batchResults.length; j++) {
+ results[commandCount - 1 - j] = batchResults[batchResults.length - 1 - j];
+ }
+ commands.clear();
+ } catch (SQLException err) {
+ throw new JDBCExecutionException(err, commands.toArray(new TranslatedCommand[commands.size()]));
+ }
+ }
+
+ /**
+ * @param translatedComm
+ * @throws ConnectorException
+ * @since 4.3
+ */
+ private int[] executeTranslatedCommand(TranslatedCommand translatedComm) throws ConnectorException {
+ // create statement or PreparedStatement and execute
+ String sql = translatedComm.getSql();
+ boolean commitType = false;
+ boolean succeeded = false;
+ try {
+ int updateCount = 0;
+ if (!translatedComm.isPrepared()) {
+ updateCount = getStatement().executeUpdate(sql);
+ } else {
+ PreparedStatement pstatement = getPreparedStatement(sql);
+ int rowCount = 1;
+ for (int i = 0; i< translatedComm.getPreparedValues().size(); i++) {
+ Literal paramValue = (Literal)translatedComm.getPreparedValues().get(i);
+ if (paramValue.isMultiValued()) {
+ rowCount = ((List<?>)paramValue.getValue()).size();
+ break;
+ }
+ }
+ if (rowCount > 1) {
+ commitType = getAutoCommit(translatedComm);
+ if (commitType) {
+ connection.setAutoCommit(false);
+ }
+ }
+ bindPreparedStatementValues(pstatement, translatedComm, rowCount);
+ if (rowCount > 1) {
+ int[] results = pstatement.executeBatch();
+
+ for (int i=0; i<results.length; i++) {
+ updateCount += results[i];
+ }
+ succeeded = true;
+ } else {
+ updateCount = pstatement.executeUpdate();
+ }
+ }
+ addStatementWarnings();
+ return new int[] {updateCount};
+ } catch (SQLException err) {
+ throw new JDBCExecutionException(err, translatedComm);
+ } finally {
+ if (commitType) {
+ restoreAutoCommit(!succeeded, translatedComm);
+ }
+ }
+ }
+
+ /**
+ * @param command
+ * @return
+ * @throws ConnectorException
+ */
+ private boolean getAutoCommit(TranslatedCommand tCommand) throws ConnectorException {
+ if (this.context.isTransactional()) {
+ return false;
+ }
+ try {
+ return connection.getAutoCommit();
+ } catch (SQLException err) {
+ throw new JDBCExecutionException(err, tCommand);
+ }
+ }
+
+ /**
+ * If the auto comm
+ *
+ * @param exceptionOccurred
+ * @param command
+ * @throws ConnectorException
+ */
+ private void restoreAutoCommit(boolean exceptionOccurred,
+ TranslatedCommand tCommand) throws ConnectorException {
+ try {
+ if (exceptionOccurred) {
+ connection.rollback();
+ }
+ } catch (SQLException err) {
+ throw new JDBCExecutionException(err, tCommand);
+ } finally {
+ try {
+ connection.commit(); // in JbossAs setAutocommit = true does not trigger the commit.
+ connection.setAutoCommit(true);
+ } catch (SQLException err) {
+ throw new JDBCExecutionException(err, tCommand);
+ }
+ }
+ }
+
+ @Override
+ public int[] getUpdateCounts() throws DataNotAvailableException,
+ ConnectorException {
+ return result;
+ }
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/JDBCUpdateExecution.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/SimpleCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/SimpleCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/SimpleCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.adapter.jdbc;
+
+import java.util.List;
+
+
+/**
+ * This is a "simple" capabilities class that allows criteria but no
+ * complicated joins, subqueries, etc to be passed to the connector.
+ * This capabilities class may come in handy for testing and for
+ * sources that support JDBC but don't support extended JDBC capabilities.
+ */
+public class SimpleCapabilities extends JDBCCapabilities {
+
+ public SimpleCapabilities() {
+ }
+
+ @Override
+ public int getMaxInCriteriaSize() {
+ return 250;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCompareCriteriaEquals()
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteria()
+ */
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsIsNullCriteria()
+ */
+ public boolean supportsIsNullCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteria()
+ */
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsNotCriteria()
+ */
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrCriteria()
+ */
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelectDistinct()
+ */
+ public boolean supportsSelectDistinct() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAliasedGroup()
+ */
+ public boolean supportsAliasedGroup() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSelfJoins()
+ */
+ public boolean supportsSelfJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOuterJoins()
+ */
+ public boolean supportsOuterJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsFullOuterJoins()
+ */
+ public boolean supportsFullOuterJoins() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsBetweenCriteria()
+ */
+ public boolean supportsBetweenCriteria() {
+ return false;
+ }
+
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
+ */
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsInCriteriaSubquery()
+ */
+ public boolean supportsInCriteriaSubquery() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsExistsCriteria()
+ */
+ public boolean supportsExistsCriteria() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaSome()
+ */
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
+ */
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsOrderBy()
+ */
+ public boolean supportsOrderBy() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesSum()
+ */
+ public boolean supportsAggregatesSum() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesAvg()
+ */
+ public boolean supportsAggregatesAvg() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMin()
+ */
+ public boolean supportsAggregatesMin() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesMax()
+ */
+ public boolean supportsAggregatesMax() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCount()
+ */
+ public boolean supportsAggregatesCount() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesCountStar()
+ */
+ public boolean supportsAggregatesCountStar() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsAggregatesDistinct()
+ */
+ public boolean supportsAggregatesDistinct() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsScalarSubqueries()
+ */
+ public boolean supportsScalarSubqueries() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCorrelatedSubqueries()
+ */
+ public boolean supportsCorrelatedSubqueries() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsCaseExpressions()
+ */
+ public boolean supportsCaseExpressions() {
+ return false;
+ }
+
+ /*
+ * @see com.metamatrix.data.api.ConnectorCapabilities#supportsSearchedCaseExpressions()
+ */
+ public boolean supportsSearchedCaseExpressions() {
+ return false;
+ }
+
+ /**
+ * Return null to indicate no functions are supported.
+ * @return null
+ * @see org.teiid.resource.cci.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List getSupportedFunctions() {
+ return null;
+ }
+
+ public boolean supportsInlineViews() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsUnions()
+ * @since 4.2
+ */
+ public boolean supportsUnions() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return false;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/resource/adapter/jdbc/SimpleCapabilities.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.List;
+
+import org.teiid.connector.language.*;
+
+public class AliasModifier extends FunctionModifier {
+ // The alias to use
+ protected String alias;
+
+ /**
+ * Constructor that takes the alias to use for functions.
+ * @param alias The alias to replace the incoming function name with
+ */
+ public AliasModifier(String alias) {
+ this.alias = alias;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ modify(function);
+ return null;
+ }
+
+ protected void modify(Function function) {
+ function.setName(alias);
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ConvertModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ConvertModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,203 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.Literal;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+
+/**
+ * Base class for handling the convert function.
+ * <p>Convert is by far the most complicated pushdown function since it actually
+ * represents a matrix of possible functions. Additionally not every source supports
+ * the same semantics as our conversions.</p>
+ * <p>Each instance of this class makes a best effort at handling converts for for a
+ * given source - compensating for differing string representation, the lack a time type
+ * etc.
+ * <p>The choice of conversion logic is as follows:
+ * <ul>
+ * <li>Look for a specific conversion between the source and target - {@link #addConvert(int, int, FunctionModifier)}</li>
+ * <li>Filter common implicit conversions</li>
+ * <li>Look for a general source conversion - {@link #addSourceConversion(FunctionModifier, int...)}</li>
+ * <li>Look for a general target conversion - {@link #addTypeConversion(FunctionModifier, int...)}</li>
+ * <li>Look for a type mapping, which will replace the target type with the given native type - {@link #addTypeMapping(String, int...)}</li>
+ * <li>Drop the conversion</li>
+ * </ul>
+ */
+public class ConvertModifier extends FunctionModifier {
+
+ public static class FormatModifier extends AliasModifier {
+
+ private String format;
+
+ public FormatModifier(String alias) {
+ super(alias);
+ }
+
+ public FormatModifier(String alias, String format) {
+ super(alias);
+ this.format = format;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ modify(function);
+ if (format == null) {
+ function.getParameters().remove(1);
+ } else {
+ ((Literal)function.getParameters().get(1)).setValue(format);
+ }
+ return null;
+ }
+
+ }
+
+ private Map<Integer, String> typeMapping = new HashMap<Integer, String>();
+ private Map<Integer, FunctionModifier> typeModifier = new HashMap<Integer, FunctionModifier>();
+ private Map<Integer, FunctionModifier> sourceModifier = new HashMap<Integer, FunctionModifier>();
+ private Map<List<Integer>, FunctionModifier> specificConverts = new HashMap<List<Integer>, FunctionModifier>();
+ private boolean booleanNumeric;
+ private boolean wideningNumericImplicit;
+
+ public void addTypeConversion(FunctionModifier convert, int ... targetType) {
+ for (int i : targetType) {
+ this.typeModifier.put(i, convert);
+ }
+ }
+
+ public void addSourceConversion(FunctionModifier convert, int ... sourceType) {
+ for (int i : sourceType) {
+ this.sourceModifier.put(i, convert);
+ }
+ }
+
+ public void addTypeMapping(String nativeType, int ... targetType) {
+ for (int i : targetType) {
+ typeMapping.put(i, nativeType);
+ }
+ }
+
+ public void setWideningNumericImplicit(boolean wideningNumericImplicit) {
+ this.wideningNumericImplicit = wideningNumericImplicit;
+ }
+
+ public void addConvert(int sourceType, int targetType, FunctionModifier convert) {
+ specificConverts.put(Arrays.asList(sourceType, targetType), convert);
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ function.setName("cast"); //$NON-NLS-1$
+ int targetCode = getCode(function.getType());
+ List<Expression> args = function.getParameters();
+ Class<?> srcType = args.get(0).getType();
+ int sourceCode = getCode(srcType);
+
+ List<Integer> convesionCode = Arrays.asList(sourceCode, targetCode);
+ FunctionModifier convert = specificConverts.get(convesionCode);
+ if (convert != null) {
+ return convert.translate(function);
+ }
+
+ boolean implicit = sourceCode == CHAR && targetCode == STRING;
+
+ if (targetCode >= BYTE && targetCode <= BIGDECIMAL) {
+ if (booleanNumeric && sourceCode == BOOLEAN) {
+ sourceCode = BYTE;
+ implicit = targetCode == BYTE;
+ }
+ implicit |= wideningNumericImplicit && sourceCode >= BYTE && sourceCode <= BIGDECIMAL && sourceCode < targetCode;
+ }
+
+ if (!implicit) {
+ convert = this.sourceModifier.get(sourceCode);
+ if (convert != null
+ && (!convert.equals(sourceModifier.get(targetCode)) || sourceCode == targetCode)) { //checks for implicit, but allows for dummy converts
+ return convert.translate(function);
+ }
+
+ convert = this.typeModifier.get(targetCode);
+ if (convert != null
+ && (!convert.equals(typeModifier.get(sourceCode)) || sourceCode == targetCode)) { //checks for implicit, but allows for dummy converts
+ return convert.translate(function);
+ }
+
+ String type = typeMapping.get(targetCode);
+
+ if (type != null
+ && (!type.equals(typeMapping.get(sourceCode)) || sourceCode == targetCode)) { //checks for implicit, but allows for dummy converts
+ ((Literal)function.getParameters().get(1)).setValue(type);
+ return null;
+ }
+ }
+
+ return Arrays.asList(function.getParameters().get(0));
+ }
+
+ public static Function createConvertFunction(LanguageFactory langFactory, Expression expr, String typeName) {
+ Class<?> type = TypeFacility.getDataTypeClass(typeName);
+ return langFactory.createFunction(SourceSystemFunctions.CONVERT,
+ new Expression[] {expr, langFactory.createLiteral(typeName, type)}, type);
+ }
+
+ public void addNumericBooleanConversions() {
+ this.booleanNumeric = true;
+ //number -> boolean
+ this.addTypeConversion(new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ Expression stringValue = function.getParameters().get(0);
+ return Arrays.asList("CASE WHEN ", stringValue, " = 0 THEN 0 WHEN ", stringValue, " IS NOT NULL THEN 1 END"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ }, FunctionModifier.BOOLEAN);
+ this.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ Expression booleanValue = function.getParameters().get(0);
+ if (booleanValue instanceof Function) {
+ Function nested = (Function)booleanValue;
+ if (nested.getName().equalsIgnoreCase("convert") && Number.class.isAssignableFrom(nested.getParameters().get(0).getType())) { //$NON-NLS-1$
+ booleanValue = nested.getParameters().get(0);
+ }
+ }
+ return Arrays.asList("CASE WHEN ", booleanValue, " = 0 THEN 'false' WHEN ", booleanValue, " IS NOT NULL THEN 'true' END"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ this.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ Expression stringValue = function.getParameters().get(0);
+ return Arrays.asList("CASE WHEN ", stringValue, " IN ('false', '0') THEN 0 WHEN ", stringValue, " IS NOT NULL THEN 1 END"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ConvertModifier.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,50 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.Function;
+
+
+/**
+ * Wrap a function in standard JDBC escape syntax. In some cases, the
+ * driver can then convert to the correct database syntax for us.
+ * @since 5.0
+ */
+public class EscapeSyntaxModifier extends FunctionModifier {
+
+ /**
+ * @see org.teiid.connector.jdbc.translator.BasicFunctionModifier#translate(org.teiid.connector.language.Function)
+ * @since 5.0
+ */
+ public List<?> translate(Function function) {
+ List<Object> objs = new ArrayList<Object>();
+ objs.add("{fn "); //$NON-NLS-1$
+ objs.add(function);
+ objs.add("}"); //$NON-NLS-1$
+ return objs;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ExtractFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ExtractFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ExtractFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,88 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.connector.language.SQLReservedWords.Tokens;
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+
+/**
+ * Convert the YEAR/MONTH/DAY etc. function into an equivalent Extract function.
+ * Format: EXTRACT(YEAR from Element) or EXTRACT(YEAR from DATE '2004-03-03')
+ */
+public class ExtractFunctionModifier extends FunctionModifier {
+ public static final String YEAR = "YEAR"; //$NON-NLS-1$
+ public static final String QUARTER = "QUARTER"; //$NON-NLS-1$
+ public static final String MONTH = "MONTH"; //$NON-NLS-1$
+ public static final String DAYOFYEAR = "DOY"; //$NON-NLS-1$
+ public static final String DAY = "DAY"; //$NON-NLS-1$
+ public static final String WEEK = "WEEK"; //$NON-NLS-1$
+ public static final String DAYOFWEEK = "DOW"; //$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 SECOND = "SECOND"; //$NON-NLS-1$
+ public static final String MILLISECONDS = "MILLISECONDS"; //$NON-NLS-1$
+
+ private static Map<String, String> FUNCTION_PART_MAP = new HashMap<String, String>();
+
+ static {
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.WEEK, WEEK);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.DAYOFWEEK, DAYOFWEEK);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.DAYOFYEAR, DAYOFYEAR);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.YEAR, YEAR);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.QUARTER, QUARTER);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.MONTH, MONTH);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.DAYOFMONTH, DAY);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.HOUR, HOUR);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.MINUTE, MINUTE);
+ FUNCTION_PART_MAP.put(SourceSystemFunctions.SECOND, SECOND);
+ }
+
+ public ExtractFunctionModifier() {
+ }
+
+ public List<?> translate(Function function) {
+ List<Expression> args = function.getParameters();
+ List<Object> objs = new ArrayList<Object>();
+ objs.add("EXTRACT("); //$NON-NLS-1$
+ objs.add(FUNCTION_PART_MAP.get(function.getName().toLowerCase()));
+ objs.add(Tokens.SPACE);
+ objs.add(SQLReservedWords.FROM);
+ objs.add(Tokens.SPACE);
+ objs.add(args.get(0));
+ objs.add(Tokens.RPAREN);
+ if (function.getName().toLowerCase().equals(SourceSystemFunctions.DAYOFWEEK)) {
+ objs.add(0, Tokens.LPAREN);
+ objs.add(" + 1)"); //$NON-NLS-1$
+ }
+ return objs;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,102 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.resource.cci.TypeFacility;
+
+
+/**
+ * Implementations of this interface are used to modify Teiid functions
+ * coming in to the connector into alternate datasource-specific language, if
+ * necessary.
+ */
+public abstract class FunctionModifier {
+
+ /*
+ * Public sharing part for the mapping between class and type in format of Map<class->Integer>.
+ */
+ public static final int STRING = 0;
+ public static final int CHAR = 1;
+ public static final int BOOLEAN = 2;
+ public static final int BYTE = 3;
+ public static final int SHORT = 4;
+ public static final int INTEGER = 5;
+ public static final int LONG = 6;
+ public static final int BIGINTEGER = 7;
+ public static final int FLOAT = 8;
+ public static final int DOUBLE = 9;
+ public static final int BIGDECIMAL = 10;
+ public static final int DATE = 11;
+ public static final int TIME = 12;
+ public static final int TIMESTAMP = 13;
+ public static final int OBJECT = 14;
+ public static final int BLOB = 15;
+ public static final int CLOB = 16;
+ public static final int XML = 17;
+
+ private static final Map<Class<?>, Integer> typeMap = new HashMap<Class<?>, Integer>();
+
+ static {
+ typeMap.put(TypeFacility.RUNTIME_TYPES.STRING, new Integer(STRING));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.CHAR, new Integer(CHAR));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.BOOLEAN, new Integer(BOOLEAN));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.BYTE, new Integer(BYTE));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.SHORT, new Integer(SHORT));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.INTEGER, new Integer(INTEGER));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.LONG, new Integer(LONG));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.BIG_INTEGER, new Integer(BIGINTEGER));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.FLOAT, new Integer(FLOAT));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.DOUBLE, new Integer(DOUBLE));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL, new Integer(BIGDECIMAL));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.DATE, new Integer(DATE));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.TIME, new Integer(TIME));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.TIMESTAMP, new Integer(TIMESTAMP));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.OBJECT, new Integer(OBJECT));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.BLOB, new Integer(BLOB));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.CLOB, new Integer(CLOB));
+ typeMap.put(TypeFacility.RUNTIME_TYPES.XML, new Integer(XML));
+ }
+
+ public static int getCode(Class<?> source) {
+ return typeMap.get(source).intValue();
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if this FunctionModifier wishes to rely on the default translation of the
+ * conversion visitor.
+ * @param function IFunction to be translated
+ * @return List of translated parts, or null
+ * @since 4.2
+ */
+ public abstract List<?> translate(Function function);
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,37 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.ResourceBundle;
+import com.metamatrix.core.BundleUtil;
+
+
+public class JDBCPlugin {
+
+ public static final String PLUGIN_ID = "org.teiid.translator.jdbc" ; //$NON-NLS-1$
+
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,
+ PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/LocateFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/LocateFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/LocateFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.translator.jdbc;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.Comparison.Operator;
+import org.teiid.resource.cci.TypeFacility;
+
+
+/**
+ * A modifier class that can be used to translate the scalar function
+ * <code>locate(search_string, source_string)</code> and
+ * <code>locate(search_string, source_string, start_index)</code> to a function
+ * or expression that can be used at the data source.
+ * <p>
+ * If the default implementation is used, a function name of LOCATE will be used
+ * for the function name.
+ * <p>
+ * If the default implementation is used, the expression will not be modified if:
+ * <li><code>locate(search_string, source_string)</code> is used</li>
+ * <li><code>locate(search_string, source_string, start_index)</code> is used
+ * and <code>start_index</code> is a literal integer greater then 0</li>
+ * <li>the default function parameter order is used or unspecified</li>
+ * <p>
+ * If the default implementation is used, the expression will be modified if:
+ * <li><code>locate(search_string, source_string, start_index)</code> is used
+ * and <code>start_index</code> is a literal integer less then 1</li>
+ * <li><code>locate(search_string, source_string, start_index)</code> is used
+ * and <code>start_index</code> is not a literal integer</li>
+ * <li>the function parameter order is something other than the default</li>
+ * <p>
+ * If the default implementation is used and the expression is modified, it is
+ * modified to ensure that any literal integer value less than 1 is made equal
+ * to 1 and any non literal value is wrapped by a searched case expression
+ * to ensure that a value of less then 1 will be equal to 1 and the parameter
+ * order matches that of what the data source expects.
+ * <p>
+ * For example:
+ * <li><code>locate('a', 'abcdef')</code> --> <code>LOCATE('a', 'abcdef')</code></li>
+ * <li><code>locate('a', 'abcdef', 2)</code> --> <code>LOCATE('a', 'abcdef', 2)</code></li>
+ * <li><code>locate('a', 'abcdef', 0)</code> --> <code>LOCATE('a', 'abcdef', 1)</code></li>
+ * <li><code>locate('a', 'abcdef', intCol)</code> --> <code>LOCATE('a', 'abcdef', CASE WHEN intCol < 1 THEN 1 ELSE intCol END)</code></li>
+ *
+ * @since 6.2
+ */
+public class LocateFunctionModifier extends AliasModifier {
+
+ public static String LOCATE = "LOCATE"; //$NON-NLS-1$
+
+ private LanguageFactory langFactory;
+ private boolean sourceStringFirst;
+
+ /**
+ * Constructs a {@link BasicFunctionModifier} object that can be used to
+ * translate the scalar function LOCATE() to a source specific scalar
+ * function or expression.
+ *
+ * @param langFactory the language factory associated with translation
+ */
+ public LocateFunctionModifier(LanguageFactory langFactory) {
+ this(langFactory, LOCATE, false);
+ }
+
+ /**
+ * Constructs a {@link BasicFunctionModifier} object that can be used to
+ * translate the scalar function LOCATE() to a source specific scalar
+ * function or expression.
+ *
+ * @param langFactory the language factory associated with translation
+ * @param functionName the function name or alias to be used instead of LOCATE
+ * @param sourceStringFirst
+ */
+ public LocateFunctionModifier(LanguageFactory langFactory, final String functionName, boolean sourceStringFirst) {
+ super(functionName);
+ this.langFactory = langFactory;
+ this.sourceStringFirst = sourceStringFirst;
+ }
+
+ /**
+ * Returns a version of <code>function</code> suitable for executing at the
+ * data source.
+ * <p>
+ * First, a default function name or the value specified during construction
+ * of <code>MODFunctionModifier</code> is set on <code>function</code>.
+ * <p>
+ * If <code>function</code> represents <code>LOCATE(searchStr, sourceStr, startIndex)</code>
+ * and <code>startIndex</code> is a literal value, it is translated for
+ * consistency between the built-in system function
+ * <code>LOCATE(searchStr, sourceStr, startIndex)</code> and the sources
+ * implementation. This is done by calling {@link #getStartIndexExpression(Literal)}
+ * and passing it the literal <code>startIndex</code> value.
+ * <p>
+ * If <code>function</code> represents <code>LOCATE(searchStr, sourceStr, startIndex)</code>
+ * and <code>startIndex</code> is not a literal value, it is translated for
+ * consistency between the built-in system function
+ * <code>LOCATE(searchStr, sourceStr, startIndex)</code> and the sources
+ * implementation. This is done by calling {@link #getStartIndexExpression(Expression)}
+ * and passing it the non-literal <code>startIndex</code> value.
+ * <p>
+ * Finally, <code>function</code>'s parameters may be rearranged depending
+ * on the value specified by {@link ParameterOrder} during construction of
+ * <code>MODFunctionModifier</code>.
+ * <p>
+ * The translated <code>function</code> is then returned.
+ * <p>
+ * For example:
+ * <ul>
+ * <code>locate('a', 'abcdefg') ---> LOCATE('a', 'abcdefg')</code><br />
+ * <code>locate('a', 'abcdefg', 1) ---> LOCATE('a', 'abcdefg', 1)</code><br />
+ * <code>locate('a', 'abcdefg', 1) ---> INSTR('abcdefg', 'a', 1)</code><br />
+ * <code>locate('a', 'abcdefg', -5) ---> INSTR('abcdefg', 'a', 1)</code><br />
+ * <code>locate('a', 'abcdefg', 1) ---> FINDSTR('a', 'abcdefg', 1)</code><br />
+ * <code>locate('a', 'abcdefg', myCol) ---> LOCATE('a', 'abcdefg', CASE WHEN myCol < 1 THEN 1 ELSE myCol END)</code>
+ * </ul>
+ *
+ * @param function the LOCATE function that may need to be modified
+ */
+ public void modify(Function function) {
+ super.modify(function);
+ List<Expression> args = function.getParameters();
+ Expression searchStr = args.get(0);
+ Expression sourceStr = args.get(1);
+
+ // if startIndex was given then we may need to do additional work
+ if (args.size() > 2) {
+ args.set(2, ensurePositiveStartIndex(args.get(2)));
+ }
+ if (sourceStringFirst) {
+ args.set(0, sourceStr);
+ args.set(1, searchStr);
+ }
+ }
+
+ private Expression ensurePositiveStartIndex(Expression startIndex) {
+ if (startIndex instanceof Literal) {
+ Literal literal = (Literal)startIndex;
+ if (literal.getValue() instanceof Integer && ((Integer)literal.getValue() < 1)) {
+ literal.setValue(1);
+ }
+ } else {
+ Comparison whenExpr = langFactory.createCompareCriteria(
+ Operator.LT,
+ startIndex,
+ langFactory.createLiteral(1, Integer.class)
+ );
+ Literal thenExpr = langFactory.createLiteral(1, Integer.class);
+ startIndex = langFactory.createSearchedCaseExpression(Arrays.asList(langFactory.createSearchedWhenCondition(whenExpr, thenExpr)), startIndex, TypeFacility.RUNTIME_TYPES.INTEGER);
+ }
+ return startIndex;
+ }
+
+ /**
+ * Get the instance of {@link LanguageFactory} set during construction.
+ *
+ * @return the <code>ILanguageFactory</code> instance
+ */
+ protected LanguageFactory getLanguageFactory() {
+ return this.langFactory;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/LocateFunctionModifier.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,84 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+
+/**
+ * Adds mod (remainder) support for non-integral types
+ */
+public class ModFunctionModifier extends AliasModifier {
+
+ private Set<Class> supportedTypes = new HashSet<Class>(Arrays.asList(TypeFacility.RUNTIME_TYPES.INTEGER, TypeFacility.RUNTIME_TYPES.LONG));
+
+ private LanguageFactory langFactory;
+
+ public ModFunctionModifier(String modFunction, LanguageFactory langFactory) {
+ this(modFunction, langFactory, null);
+ }
+
+ public ModFunctionModifier(String modFunction, LanguageFactory langFactory, Collection<Class> supportedTypes) {
+ super(modFunction);
+ this.langFactory = langFactory;
+ if (supportedTypes != null) {
+ this.supportedTypes.addAll(supportedTypes);
+ }
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ List<Expression> expressions = function.getParameters();
+ Class<?> type = function.getType();
+ if (supportedTypes.contains(type)) {
+ modify(function);
+ return null;
+ }
+ //x % y => x - sign(x) * floor(abs(x / y)) * y
+ Function divide = langFactory.createFunction(SourceSystemFunctions.DIVIDE_OP, new ArrayList<Expression>(expressions), type);
+
+ Function abs = langFactory.createFunction(SourceSystemFunctions.ABS, Arrays.asList(divide), type);
+
+ Function floor = langFactory.createFunction(SourceSystemFunctions.FLOOR, Arrays.asList(abs), type);
+
+ Function sign = langFactory.createFunction(SourceSystemFunctions.SIGN, Arrays.asList(expressions.get(0)), type);
+
+ List<? extends Expression> multArgs = Arrays.asList(sign, floor, langFactory.createFunction(SourceSystemFunctions.ABS, Arrays.asList(expressions.get(1)), type));
+ Function mult = langFactory.createFunction(SourceSystemFunctions.MULTIPLY_OP, multArgs, type);
+
+ List<Expression> minusArgs = Arrays.asList(expressions.get(0), mult);
+
+ return Arrays.asList(langFactory.createFunction(SourceSystemFunctions.SUBTRACT_OP, minusArgs, type));
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,372 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.ExpressionValueSource;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.In;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.connector.language.Like;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.connector.language.SearchedCase;
+import org.teiid.connector.language.SetClause;
+import org.teiid.connector.language.SortSpecification;
+import org.teiid.connector.language.Argument.Direction;
+import org.teiid.connector.language.SQLReservedWords.Tokens;
+import org.teiid.connector.language.SetQuery.Operation;
+import org.teiid.connector.language.SortSpecification.Ordering;
+import org.teiid.connector.visitor.util.SQLStringVisitor;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.Translator.NullOrder;
+
+
+/**
+ * This visitor takes an ICommand and does DBMS-specific conversion on it
+ * to produce a SQL String. This class is expected to be subclassed.
+ */
+public class SQLConversionVisitor extends SQLStringVisitor{
+
+ private static DecimalFormat DECIMAL_FORMAT =
+ new DecimalFormat("#############################0.0#############################"); //$NON-NLS-1$
+ private static double SCIENTIC_LOW = Math.pow(10, -3);
+ private static double SCIENTIC_HIGH = Math.pow(10, 7);
+
+ private ExecutionContext context;
+ private Translator translator;
+
+ private boolean prepared;
+
+ private List preparedValues = new ArrayList();
+
+ private Set<LanguageObject> recursionObjects = Collections.newSetFromMap(new IdentityHashMap<LanguageObject, Boolean>());
+ private Map<LanguageObject, Object> translations = new IdentityHashMap<LanguageObject, Object>();
+
+ private boolean replaceWithBinding = false;
+
+ public SQLConversionVisitor(Translator translator) {
+ this.translator = translator;
+ this.prepared = translator.usePreparedStatements();
+ }
+
+ @Override
+ public void append(LanguageObject obj) {
+ boolean replacementMode = replaceWithBinding;
+ if (obj instanceof Command || obj instanceof Function) {
+ /*
+ * In general it is not appropriate to use bind values within a function
+ * unless the particulars of the function parameters are know.
+ * As needed, other visitors or modifiers can set the literals used within
+ * a particular function as bind variables.
+ */
+ this.replaceWithBinding = false;
+ }
+ List<?> parts = null;
+ if (!recursionObjects.contains(obj)) {
+ Object trans = this.translations.get(obj);
+ if (trans instanceof List<?>) {
+ parts = (List<?>)trans;
+ } else if (trans instanceof LanguageObject) {
+ obj = (LanguageObject)trans;
+ } else {
+ parts = translator.translate(obj, context);
+ if (parts != null) {
+ this.translations.put(obj, parts);
+ } else {
+ this.translations.put(obj, obj);
+ }
+ }
+ }
+ if (parts != null) {
+ recursionObjects.add(obj);
+ for (Object part : parts) {
+ if(part instanceof LanguageObject) {
+ append((LanguageObject)part);
+ } else {
+ buffer.append(part);
+ }
+ }
+ recursionObjects.remove(obj);
+ } else {
+ super.append(obj);
+ }
+ this.replaceWithBinding = replacementMode;
+ }
+
+ @Override
+ public void visit(SortSpecification obj) {
+ super.visit(obj);
+ NullOrder nullOrder = this.translator.getDefaultNullOrder();
+ if (!this.translator.supportsExplicitNullOrdering() || nullOrder == NullOrder.LOW) {
+ return;
+ }
+ if (obj.getOrdering() == Ordering.ASC) {
+ if (nullOrder != NullOrder.FIRST) {
+ buffer.append(" NULLS FIRST"); //$NON-NLS-1$
+ }
+ } else if (nullOrder == NullOrder.FIRST) {
+ buffer.append(" NULLS LAST"); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @param type
+ * @param object
+ * @param valuesbuffer
+ */
+ private void translateSQLType(Class type, Object obj, StringBuilder valuesbuffer) {
+ if (obj == null) {
+ valuesbuffer.append(SQLReservedWords.NULL);
+ } else {
+ if(Number.class.isAssignableFrom(type)) {
+ boolean useFormatting = false;
+
+ if (Double.class.isAssignableFrom(type)){
+ double value = ((Double)obj).doubleValue();
+ useFormatting = (value <= SCIENTIC_LOW || value >= SCIENTIC_HIGH);
+ }
+ else if (Float.class.isAssignableFrom(type)){
+ float value = ((Float)obj).floatValue();
+ useFormatting = (value <= SCIENTIC_LOW || value >= SCIENTIC_HIGH);
+ }
+ // The formatting is to avoid the so-called "scientic-notation"
+ // where toString will use for numbers greater than 10p7 and
+ // less than 10p-3, where database may not understand.
+ if (useFormatting) {
+ synchronized (DECIMAL_FORMAT) {
+ valuesbuffer.append(DECIMAL_FORMAT.format(obj));
+ }
+ }
+ else {
+ valuesbuffer.append(obj);
+ }
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.BOOLEAN)) {
+ valuesbuffer.append(translator.translateLiteralBoolean((Boolean)obj));
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.TIMESTAMP)) {
+ valuesbuffer.append(translator.translateLiteralTimestamp((Timestamp)obj));
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.TIME)) {
+ valuesbuffer.append(translator.translateLiteralTime((Time)obj));
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.DATE)) {
+ valuesbuffer.append(translator.translateLiteralDate((java.sql.Date)obj));
+ } else {
+ // If obj is string, toSting() will not create a new String
+ // object, it returns it self, so new object creation.
+ valuesbuffer.append(Tokens.QUOTE)
+ .append(escapeString(obj.toString(), Tokens.QUOTE))
+ .append(Tokens.QUOTE);
+ }
+ }
+ }
+
+ /**
+ * @see org.teiid.connector.visitor.util.SQLStringVisitor#visit(org.teiid.connector.language.Call)
+ */
+ public void visit(Call obj) {
+ this.prepared = true;
+ /*
+ * preparedValues is now a list of procedure params instead of just values
+ */
+ this.preparedValues = obj.getArguments();
+ buffer.append(generateSqlForStoredProcedure(obj));
+ }
+
+ /**
+ * @see org.teiid.connector.visitor.util.SQLStringVisitor#visit(org.teiid.connector.language.Literal)
+ */
+ public void visit(Literal obj) {
+ if (this.prepared && (replaceWithBinding || TranslatedCommand.isBindEligible(obj) || obj.isBindValue())) {
+ buffer.append(UNDEFINED_PARAM);
+ preparedValues.add(obj);
+ } else {
+ translateSQLType(obj.getType(), obj.getValue(), buffer);
+ }
+ }
+
+ @Override
+ public void visit(In obj) {
+ replaceWithBinding = true;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(Like obj) {
+ replaceWithBinding = true;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(Comparison obj) {
+ replaceWithBinding = true;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(ExpressionValueSource obj) {
+ replaceWithBinding = true;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(SetClause obj) {
+ replaceWithBinding = true;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(DerivedColumn obj) {
+ replaceWithBinding = false;
+ super.visit(obj);
+ }
+
+ @Override
+ public void visit(SearchedCase obj) {
+ replaceWithBinding = false;
+ super.visit(obj);
+ }
+
+ /**
+ * Set the per-command execution context on this visitor.
+ * @param context ExecutionContext
+ * @since 4.3
+ */
+ public void setExecutionContext(ExecutionContext context) {
+ this.context = context;
+ }
+
+ /**
+ * Retrieve the per-command execution context for this visitor
+ * (intended for subclasses to use).
+ * @return
+ * @since 4.3
+ */
+ protected ExecutionContext getExecutionContext() {
+ return this.context;
+ }
+
+ protected String getSourceComment(Command command) {
+ return this.translator.getSourceComment(this.context, command);
+ }
+
+ /**
+ * This is a generic implementation. Subclass should override this method
+ * if necessary.
+ * @param exec The command for the stored procedure.
+ * @return String to be executed by CallableStatement.
+ */
+ protected String generateSqlForStoredProcedure(Call exec) {
+ StringBuffer prepareCallBuffer = new StringBuffer();
+ prepareCallBuffer.append("{ "); //$NON-NLS-1$
+
+ List<Argument> params = exec.getArguments();
+
+ //check whether a "?" is needed if there are returns
+ boolean needQuestionMark = exec.getReturnType() != null;
+
+ prepareCallBuffer.append(getSourceComment(exec));
+
+ if(needQuestionMark){
+ prepareCallBuffer.append("?="); //$NON-NLS-1$
+ }
+
+ prepareCallBuffer.append(" call ");//$NON-NLS-1$
+ prepareCallBuffer.append(exec.getMetadataObject() != null ? getName(exec.getMetadataObject()) : exec.getProcedureName());
+ prepareCallBuffer.append("("); //$NON-NLS-1$
+
+ int numberOfParameters = 0;
+ for (Argument param : params) {
+ if(param.getDirection() == Direction.IN || param.getDirection() == Direction.OUT || param.getDirection() == Direction.INOUT){
+ if(numberOfParameters > 0){
+ prepareCallBuffer.append(","); //$NON-NLS-1$
+ }
+ prepareCallBuffer.append("?"); //$NON-NLS-1$
+ numberOfParameters++;
+ }
+ }
+ prepareCallBuffer.append(")"); //$NON-NLS-1$
+ prepareCallBuffer.append("}"); //$NON-NLS-1$
+ return prepareCallBuffer.toString();
+ }
+
+ /**
+ * @return the preparedValues
+ */
+ List getPreparedValues() {
+ return this.preparedValues;
+ }
+
+ public boolean isPrepared() {
+ return prepared;
+ }
+
+ public void setPrepared(boolean prepared) {
+ this.prepared = prepared;
+ }
+
+ @Override
+ protected boolean useAsInGroupAlias() {
+ return this.translator.useAsInGroupAlias();
+ }
+
+ @Override
+ protected boolean useParensForSetQueries() {
+ return translator.useParensForSetQueries();
+ }
+
+ @Override
+ protected String replaceElementName(String group, String element) {
+ return translator.replaceElementName(group, element);
+ }
+
+ @Override
+ protected void appendSetOperation(Operation operation) {
+ buffer.append(translator.getSetOperationString(operation));
+ }
+
+ @Override
+ protected boolean useParensForJoins() {
+ return translator.useParensForJoins();
+ }
+
+ protected boolean useSelectLimit() {
+ return translator.useSelectLimit();
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.translator.jdbc;
+
+import java.util.List;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.visitor.util.CollectorVisitor;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.TypeFacility;
+
+
+/**
+ * This is a utility class used to translate an ICommand using a SQLConversionVisitor.
+ * The SQLConversionVisitor should not be invoked directly; this object will use it to
+ * translate the ICommand.
+ */
+public class TranslatedCommand {
+
+ private String sql;
+ private boolean prepared;
+ private List preparedValues;
+
+ private Translator sqlTranslator;
+ private ExecutionContext context;
+
+ /**
+ * Constructor, takes a SQLConversionVisitor subclass
+ * @param visitor a SQLConversionVisitor subclass
+ */
+ public TranslatedCommand(ExecutionContext context, Translator sqlTranslator){
+ this.sqlTranslator = sqlTranslator;
+ this.context = context;
+ }
+
+ /**
+ * The method to cause this object to do it's thing. This method should
+ * be called right after the constructor; afterward, all of the getter methods
+ * can be called to retrieve results.
+ * @param command ICommand to be translated
+ * @throws ConnectorException
+ */
+ public void translateCommand(Command command) throws ConnectorException {
+ SQLConversionVisitor sqlConversionVisitor = sqlTranslator.getSQLConversionVisitor();
+ sqlConversionVisitor.setExecutionContext(context);
+ if (sqlTranslator.usePreparedStatements() || hasBindValue(command)) {
+ sqlConversionVisitor.setPrepared(true);
+ }
+
+ sqlConversionVisitor.append(command);
+ this.sql = sqlConversionVisitor.toString();
+ this.preparedValues = sqlConversionVisitor.getPreparedValues();
+ this.prepared = sqlConversionVisitor.isPrepared();
+ }
+
+ /**
+ * Simple check to see if any values in the command should be replaced with bind values
+ *
+ * @param command
+ * @return
+ */
+ private boolean hasBindValue(Command command) {
+ for (Literal l : CollectorVisitor.collectObjects(Literal.class, command)) {
+ if (l.isBindValue() || isBindEligible(l)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @param l
+ * @return
+ */
+ static boolean isBindEligible(Literal l) {
+ return TypeFacility.RUNTIME_TYPES.XML.equals(l.getType())
+ || TypeFacility.RUNTIME_TYPES.CLOB.equals(l.getType())
+ || TypeFacility.RUNTIME_TYPES.BLOB.equals(l.getType())
+ || TypeFacility.RUNTIME_TYPES.OBJECT.equals(l.getType());
+ }
+
+ /**
+ * Return List of values to set on a prepared statement, if
+ * necessary (see {@link #getStatementType})
+ * @return List of values to be set on a prepared statement
+ */
+ public List getPreparedValues() {
+ return preparedValues;
+ }
+
+ /**
+ * Get String SQL of translated command; but use
+ * {@link #nextLargeSetQuerySQL} if this command is
+ * a {@link #isLargeSetQuery large set query}
+ * @return SQL of translated command, or null if the
+ * command is a {@link #isLargeSetQuery large set query}
+ */
+ public String getSql() {
+ return sql;
+ }
+
+ /**
+ * Return the statement type, one of {@link #STMT_TYPE_STATEMENT},
+ * {@link #STMT_TYPE_PREPARED_STATEMENT}, or
+ * {@link #STMT_TYPE_CALLABLE_STATEMENT}
+ * @return statement type of translated command
+ */
+ public boolean isPrepared() {
+ return prepared;
+ }
+
+ @Override
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ if (prepared) {
+ sb.append("Prepared Values: ").append(preparedValues).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ sb.append("SQL: ").append(sql); //$NON-NLS-1$
+ return sb.toString();
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/Translator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/Translator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,820 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.MessageFormat;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TimeZone;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SetQuery;
+import org.teiid.connector.language.Argument.Direction;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+
+import com.metamatrix.core.util.ReflectionHelper;
+
+/**
+ * Base class for creating source SQL queries and retrieving results.
+ * Specific databases should override as necessary.
+ */
+public class Translator {
+
+ public enum NullOrder {
+ HIGH,
+ LOW,
+ FIRST,
+ LAST
+ }
+
+ // Because the retrieveValue() method will be hit for every value of
+ // every JDBC result set returned, we do lots of weird special stuff here
+ // to improve the performance (most importantly to remove big if/else checks
+ // of every possible type.
+
+ private static final Map<Class<?>, Integer> TYPE_CODE_MAP = new HashMap<Class<?>, Integer>();
+
+ private static final int INTEGER_CODE = 0;
+ private static final int LONG_CODE = 1;
+ private static final int DOUBLE_CODE = 2;
+ private static final int BIGDECIMAL_CODE = 3;
+ private static final int SHORT_CODE = 4;
+ private static final int FLOAT_CODE = 5;
+ private static final int TIME_CODE = 6;
+ private static final int DATE_CODE = 7;
+ private static final int TIMESTAMP_CODE = 8;
+ private static final int BLOB_CODE = 9;
+ private static final int CLOB_CODE = 10;
+ private static final int BOOLEAN_CODE = 11;
+
+ static {
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.INTEGER, new Integer(INTEGER_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.LONG, new Integer(LONG_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DOUBLE, new Integer(DOUBLE_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BIG_DECIMAL, new Integer(BIGDECIMAL_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.SHORT, new Integer(SHORT_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.FLOAT, new Integer(FLOAT_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIME, new Integer(TIME_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.DATE, new Integer(DATE_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.TIMESTAMP, new Integer(TIMESTAMP_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BLOB, new Integer(BLOB_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.CLOB, new Integer(CLOB_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BOOLEAN, new Integer(BOOLEAN_CODE));
+ TYPE_CODE_MAP.put(TypeFacility.RUNTIME_TYPES.BYTE, new Integer(SHORT_CODE));
+ }
+
+ private static final ThreadLocal<MessageFormat> COMMENT = new ThreadLocal<MessageFormat>() {
+ protected MessageFormat initialValue() {
+ return new MessageFormat("/*teiid sessionid:{0}, requestid:{1}.{2}*/ "); //$NON-NLS-1$
+ }
+ };
+ public final static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();
+
+ private static final ThreadLocal<Calendar> CALENDAR = new ThreadLocal<Calendar>() {
+ @Override
+ protected Calendar initialValue() {
+ return Calendar.getInstance();
+ }
+ };
+
+ private Map<String, FunctionModifier> functionModifiers = new HashMap<String, FunctionModifier>();
+ private JDBCExecutionFactory environment;
+
+ private boolean useComments;
+ private boolean usePreparedStatements;
+
+ private TypeFacility typeFacility;
+
+ private volatile boolean initialConnection;
+ private boolean trimChar;
+
+ /**
+ * Initialize the SQLTranslator.
+ * @param env
+ * @param metadata
+ * @throws ConnectorException
+ */
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ this.environment = env;
+ this.typeFacility = env.getTypeFacility();
+
+ String timeZone = this.environment.getDatabaseTimeZone();
+ if(timeZone != null && timeZone.trim().length() > 0) {
+ TimeZone tz = TimeZone.getTimeZone(timeZone);
+ if(!DEFAULT_TIME_ZONE.hasSameRules(tz)) {
+ CALENDAR.set(Calendar.getInstance(tz));
+ }
+ }
+
+ this.useComments = this.environment.isUseCommentsInSourceQuery();
+ this.usePreparedStatements = this.environment.isUseBindVariables();
+ trimChar = this.environment.isTrimStrings();
+ }
+
+ /**
+ * Gets the database calendar. This will be set to the time zone
+ * specified by the property {@link JDBCPropertyNames#DATABASE_TIME_ZONE}, or
+ * the local time zone if none is specified.
+ * @return
+ */
+ public Calendar getDatabaseCalendar() {
+ return CALENDAR.get();
+ }
+
+ /**
+ * Gets the {@link LanguageFactory}
+ */
+ public final LanguageFactory getLanguageFactory() {
+ return environment.getLanguageFactory();
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation. Override with care.
+ * @param command
+ * @param context
+ * @return
+ */
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ List<?> parts = null;
+ if (obj instanceof Function) {
+ Function function = (Function)obj;
+ if (functionModifiers != null) {
+ FunctionModifier modifier = functionModifiers.get(function.getName().toLowerCase());
+ if (modifier != null) {
+ parts = modifier.translate(function);
+ }
+ }
+ } else if (obj instanceof Command) {
+ parts = translateCommand((Command)obj, context);
+ } else if (obj instanceof Limit) {
+ parts = translateLimit((Limit)obj, context);
+ } else if (obj instanceof ColumnReference) {
+ ColumnReference elem = (ColumnReference)obj;
+ if (trimChar && elem.getType() == TypeFacility.RUNTIME_TYPES.STRING && elem.getMetadataObject() != null
+ && ("char".equalsIgnoreCase(elem.getMetadataObject().getNativeType()) || "nchar".equalsIgnoreCase(elem.getMetadataObject().getNativeType()))) { //$NON-NLS-1$ //$NON-NLS-2$
+ return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.RTRIM, new Expression[] {elem}, TypeFacility.RUNTIME_TYPES.STRING));
+ }
+ }
+ return parts;
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation.
+ * @param command
+ * @param context
+ * @return
+ */
+ public List<?> translateCommand(Command command, ExecutionContext context) {
+ return null;
+ }
+
+ /**
+ * Return a List of translated parts ({@link LanguageObject}s and Objects), or null
+ * if to rely on the default translation.
+ * @param limit
+ * @param context
+ * @return
+ */
+ public List<?> translateLimit(Limit limit, ExecutionContext context) {
+ return null;
+ }
+
+ /**
+ * Return a map of function name in lower case to FunctionModifier.
+ * @return Map of function name to FunctionModifier.
+ */
+ public Map<String, FunctionModifier> getFunctionModifiers() {
+ return functionModifiers;
+ }
+
+ /**
+ * Add the {@link FunctionModifier} to the set of known modifiers.
+ * @param name
+ * @param modifier
+ */
+ public void registerFunctionModifier(String name, FunctionModifier modifier) {
+ this.functionModifiers.put(name, modifier);
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal boolean value. By default, a boolean literal is represented as:
+ * <code>'0'</code> or <code>'1'</code>.
+ * @param booleanValue Boolean value, never null
+ * @return Translated string
+ */
+ public String translateLiteralBoolean(Boolean booleanValue) {
+ if(booleanValue.booleanValue()) {
+ return "1"; //$NON-NLS-1$
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal date value. By default, a date literal is represented as:
+ * <code>{d '2002-12-31'}</code>
+ * @param dateValue Date value, never null
+ * @return Translated string
+ */
+ public String translateLiteralDate(java.sql.Date dateValue) {
+ return "{d '" + formatDateValue(dateValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal time value. By default, a time literal is represented as:
+ * <code>{t '23:59:59'}</code>
+ *
+ * See {@link Translator#hasTimeType()} to represent literal times as timestamps.
+ *
+ * @param timeValue Time value, never null
+ * @return Translated string
+ */
+ public String translateLiteralTime(Time timeValue) {
+ if (!hasTimeType()) {
+ return "{ts '1970-01-01 " + formatDateValue(timeValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return "{t '" + formatDateValue(timeValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Subclasses should override this method to provide a different sql translation
+ * of the literal timestamp value. By default, a timestamp literal is
+ * represented as: <code>{ts '2002-12-31 23:59:59'}</code>.
+ *
+ * See {@link Translator#getTimestampNanoPrecision()} to control the literal
+ * precision.
+ *
+ * @param timestampValue Timestamp value, never null
+ * @return Translated string
+ */
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ return "{ts '" + formatDateValue(timestampValue) + "'}"; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Format the dateObject (of type date, time, or timestamp) into a string
+ * using the DatabaseTimeZone format.
+ * @param dateObject
+ * @return Formatted string
+ */
+ public String formatDateValue(java.util.Date dateObject) {
+ if (dateObject instanceof Timestamp && getTimestampNanoPrecision() < 9) {
+ Timestamp ts = (Timestamp)dateObject;
+ Timestamp newTs = new Timestamp(ts.getTime());
+ if (getTimestampNanoPrecision() > 0) {
+ int mask = (int)Math.pow(10, 9-getTimestampNanoPrecision());
+ newTs.setNanos(ts.getNanos()/mask*mask);
+ } else {
+ newTs.setNanos(0);
+ }
+ dateObject = newTs;
+ }
+ return this.environment.getTypeFacility().convertDate(dateObject,
+ DEFAULT_TIME_ZONE, getDatabaseCalendar(), dateObject.getClass()).toString();
+ }
+
+ /**
+ * Returns true to indicate that SQL should include a comment
+ * indicating the session and request ids.
+ */
+ public boolean addSourceComment() {
+ return useComments;
+ }
+
+ /**
+ * Indicates whether group alias should be of the form
+ * "...FROM groupA AS X" or "...FROM groupA X". Certain
+ * data sources (such as Oracle) may not support the first
+ * form.
+ * @return boolean
+ */
+ public boolean useAsInGroupAlias(){
+ return true;
+ }
+
+ /**
+ * Use PreparedStatements (or CallableStatements) as
+ * appropriate for all commands. Bind values will be
+ * determined by the {@link BindValueVisitor}. {@link Literal#setBindValue(boolean)}
+ * can be used to force a literal to be a bind value.
+ */
+ public boolean usePreparedStatements() {
+ return this.usePreparedStatements;
+ }
+
+ /**
+ * Set to true to indicate that every branch of a set query
+ * should have parenthesis, i.e. (query) union (query)
+ * @return
+ */
+ public boolean useParensForSetQueries() {
+ return false;
+ }
+
+ /**
+ * Return false to indicate that time support should be emulated
+ * with timestamps.
+ * @return
+ */
+ public boolean hasTimeType() {
+ return true;
+ }
+
+ /**
+ * Returns the name for a given {@link SetQuery.Operation}
+ * @param operation
+ * @return
+ */
+ public String getSetOperationString(SetQuery.Operation operation) {
+ return operation.toString();
+ }
+
+ /**
+ * Returns the source comment for
+ * @param context
+ * @param command
+ * @return
+ */
+ public String getSourceComment(ExecutionContext context, Command command) {
+ if (addSourceComment() && context != null) {
+ return COMMENT.get().format(new Object[] {context.getConnectionIdentifier(), context.getRequestIdentifier(), context.getPartIdentifier()});
+ }
+ return ""; //$NON-NLS-1$
+ }
+
+ /**
+ * Override to return a name other than the default [group.]element
+ * @param group
+ * @param element
+ * @return
+ */
+ public String replaceElementName(String group, String element) {
+ return null;
+ }
+
+ /**
+ * Return the precision of timestamp literals. Defaults to 9
+ * @return
+ */
+ public int getTimestampNanoPrecision() {
+ return 9;
+ }
+
+ public TypeFacility getTypeFacility() {
+ return typeFacility;
+ }
+
+ /**
+ * This is a generic implementation. Because different databases handle
+ * stored procedures differently, subclasses should override this method
+ * if necessary.
+ */
+ public ResultSet executeStoredProcedure(CallableStatement statement, TranslatedCommand command, Class<?> returnType) throws SQLException {
+ List params = command.getPreparedValues();
+ int index = 1;
+
+ if(returnType != null){
+ registerSpecificTypeOfOutParameter(statement, returnType, index++);
+ }
+
+ Iterator iter = params.iterator();
+ while(iter.hasNext()){
+ Argument param = (Argument)iter.next();
+
+ if(param.getDirection() == Direction.INOUT){
+ registerSpecificTypeOfOutParameter(statement,param.getType(), index);
+ }else if(param.getDirection() == Direction.OUT){
+ registerSpecificTypeOfOutParameter(statement,param.getType(), index++);
+ }
+
+ if(param.getDirection() == Direction.IN || param.getDirection() == Direction.INOUT){
+ bindValue(statement, param.getArgumentValue().getValue(), param.getType(), index++);
+ }
+ }
+ boolean resultSetNext = statement.execute();
+
+ while (!resultSetNext) {
+ int update_count = statement.getUpdateCount();
+ if (update_count == -1) {
+ break;
+ }
+ resultSetNext = statement.getMoreResults();
+ }
+ return statement.getResultSet();
+ }
+
+ /**
+ * For registering specific output parameter types we need to translate these into the appropriate
+ * java.sql.Types output parameters
+ * We will need to match these up with the appropriate standard sql types
+ * @param cstmt
+ * @param parameter
+ * @throws SQLException
+ */
+ protected void registerSpecificTypeOfOutParameter(CallableStatement statement, Class<?> runtimeType, int index) throws SQLException {
+ int typeToSet = TypeFacility.getSQLTypeFromRuntimeType(runtimeType);
+
+ statement.registerOutParameter(index,typeToSet);
+ }
+
+ /**
+ * Sets prepared statement parameter i with param.
+ *
+ * Performs special handling to translate dates using the database time zone and to
+ * translate biginteger, float, and char to JDBC safe objects.
+ *
+ * @param stmt
+ * @param param
+ * @param paramType
+ * @param i
+ * @param cal
+ * @throws SQLException
+ */
+ public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
+ int type = TypeFacility.getSQLTypeFromRuntimeType(paramType);
+
+ if (param == null) {
+ stmt.setNull(i, type);
+ return;
+ }
+ //if this is a Date object, then use the database calendar
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.DATE)) {
+ stmt.setDate(i,(java.sql.Date)param, getDatabaseCalendar());
+ return;
+ }
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIME)) {
+ stmt.setTime(i,(java.sql.Time)param, getDatabaseCalendar());
+ return;
+ }
+ if (paramType.equals(TypeFacility.RUNTIME_TYPES.TIMESTAMP)) {
+ stmt.setTimestamp(i,(java.sql.Timestamp)param, getDatabaseCalendar());
+ return;
+ }
+ //convert these the following to jdbc safe values
+ if (TypeFacility.RUNTIME_TYPES.BIG_INTEGER.equals(paramType)) {
+ param = new BigDecimal((BigInteger)param);
+ } else if (TypeFacility.RUNTIME_TYPES.FLOAT.equals(paramType)) {
+ param = new Double(((Float)param).doubleValue());
+ } else if (TypeFacility.RUNTIME_TYPES.CHAR.equals(paramType)) {
+ param = ((Character)param).toString();
+ }
+ stmt.setObject(i, param, type);
+ }
+
+ /**
+ * Retrieve the value on the current resultset row for the given column index.
+ * @param results
+ * @param columnIndex
+ * @param expectedType
+ * @return
+ * @throws SQLException
+ */
+ public Object retrieveValue(ResultSet results, int columnIndex, Class<?> expectedType) throws SQLException {
+ Integer code = TYPE_CODE_MAP.get(expectedType);
+ if(code != null) {
+ // Calling the specific methods here is more likely to get uniform (and fast) results from different
+ // data sources as the driver likely knows the best and fastest way to convert from the underlying
+ // raw form of the data to the expected type. We use a switch with codes in order without gaps
+ // as there is a special bytecode instruction that treats this case as a map such that not every value
+ // needs to be tested, which means it is very fast.
+ switch(code.intValue()) {
+ case INTEGER_CODE: {
+ int value = results.getInt(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Integer.valueOf(value);
+ }
+ case LONG_CODE: {
+ long value = results.getLong(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Long.valueOf(value);
+ }
+ case DOUBLE_CODE: {
+ double value = results.getDouble(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Double.valueOf(value);
+ }
+ case BIGDECIMAL_CODE: {
+ return results.getBigDecimal(columnIndex);
+ }
+ case SHORT_CODE: {
+ short value = results.getShort(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Short.valueOf(value);
+ }
+ case FLOAT_CODE: {
+ float value = results.getFloat(columnIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Float.valueOf(value);
+ }
+ case TIME_CODE: {
+ return results.getTime(columnIndex, getDatabaseCalendar());
+ }
+ case DATE_CODE: {
+ return results.getDate(columnIndex, getDatabaseCalendar());
+ }
+ case TIMESTAMP_CODE: {
+ return results.getTimestamp(columnIndex, getDatabaseCalendar());
+ }
+ case BLOB_CODE: {
+ try {
+ return results.getBlob(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ try {
+ return results.getBytes(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ break;
+ }
+ case CLOB_CODE: {
+ try {
+ return results.getClob(columnIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ break;
+ }
+ case BOOLEAN_CODE: {
+ return results.getBoolean(columnIndex);
+ }
+ }
+ }
+
+ return results.getObject(columnIndex);
+ }
+
+ /**
+ * Retrieve the value for the given parameter index
+ * @param results
+ * @param parameterIndex
+ * @param expectedType
+ * @return
+ * @throws SQLException
+ */
+ public Object retrieveValue(CallableStatement results, int parameterIndex, Class expectedType) throws SQLException{
+ Integer code = TYPE_CODE_MAP.get(expectedType);
+ if(code != null) {
+ switch(code.intValue()) {
+ case INTEGER_CODE: {
+ int value = results.getInt(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Integer.valueOf(value);
+ }
+ case LONG_CODE: {
+ long value = results.getLong(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Long.valueOf(value);
+ }
+ case DOUBLE_CODE: {
+ double value = results.getDouble(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return new Double(value);
+ }
+ case BIGDECIMAL_CODE: {
+ return results.getBigDecimal(parameterIndex);
+ }
+ case SHORT_CODE: {
+ short value = results.getShort(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return Short.valueOf(value);
+ }
+ case FLOAT_CODE: {
+ float value = results.getFloat(parameterIndex);
+ if(results.wasNull()) {
+ return null;
+ }
+ return new Float(value);
+ }
+ case TIME_CODE: {
+ return results.getTime(parameterIndex, getDatabaseCalendar());
+ }
+ case DATE_CODE: {
+ return results.getDate(parameterIndex, getDatabaseCalendar());
+ }
+ case TIMESTAMP_CODE: {
+ return results.getTimestamp(parameterIndex, getDatabaseCalendar());
+ }
+ case BLOB_CODE: {
+ try {
+ return results.getBlob(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ try {
+ return results.getBytes(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ case CLOB_CODE: {
+ try {
+ return results.getClob(parameterIndex);
+ } catch (SQLException e) {
+ // ignore
+ }
+ }
+ case BOOLEAN_CODE: {
+ return results.getBoolean(parameterIndex);
+ }
+ }
+ }
+
+ // otherwise fall through and call getObject() and rely on the normal
+ // translation routines
+ return results.getObject(parameterIndex);
+ }
+
+ /**
+ * Called exactly once for this source.
+ * @param connection
+ */
+ protected void afterInitialConnectionCreation(Connection connection) {
+ // now dig some details about this driver/database for log.
+ try {
+ StringBuffer sb = new StringBuffer();
+ DatabaseMetaData dbmd = connection.getMetaData();
+ sb.append("Commit=").append(connection.getAutoCommit()); //$NON-NLS-1$
+ sb.append(";DatabaseProductName=").append(dbmd.getDatabaseProductName()); //$NON-NLS-1$
+ sb.append(";DatabaseProductVersion=").append(dbmd.getDatabaseProductVersion()); //$NON-NLS-1$
+ sb.append(";DriverMajorVersion=").append(dbmd.getDriverMajorVersion()); //$NON-NLS-1$
+ sb.append(";DriverMajorVersion=").append(dbmd.getDriverMinorVersion()); //$NON-NLS-1$
+ sb.append(";DriverName=").append(dbmd.getDriverName()); //$NON-NLS-1$
+ sb.append(";DriverVersion=").append(dbmd.getDriverVersion()); //$NON-NLS-1$
+ sb.append(";IsolationLevel=").append(dbmd.getDefaultTransactionIsolation()); //$NON-NLS-1$
+
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, sb.toString());
+ } catch (SQLException e) {
+ String errorStr = JDBCPlugin.Util.getString("ConnectionListener.failed_to_report_jdbc_connection_details"); //$NON-NLS-1$
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, errorStr);
+ }
+ }
+
+ /**
+ * Provides a hook to call source specific logic when
+ * a connection is created.
+ *
+ * defect request 13979 & 13978
+ */
+ public void afterConnectionCreation(Connection connection) {
+ if (initialConnection) {
+ synchronized (this) {
+ if (!initialConnection) {
+ return;
+ }
+ initialConnection = false;
+ afterInitialConnectionCreation(connection);
+ }
+ }
+ }
+
+
+
+ /**
+ * Create the {@link SQLConversionVisitor} that will perform translation. Typical custom
+ * JDBC connectors will not need to create custom conversion visitors, rather implementors
+ * should override existing {@link Translator} methods.
+ * @return
+ */
+ public SQLConversionVisitor getSQLConversionVisitor() {
+ return new SQLConversionVisitor(this);
+ }
+
+ /**
+ * Get the default capabilities class. Will be used by {@link #getConnectorCapabilities()} to
+ * return a capabilities instance.
+ * @return
+ */
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return JDBCCapabilities.class;
+ }
+
+ /**
+ * Get the capabilties for the source.
+ * @return
+ * @throws ConnectorException
+ */
+ public ConnectorCapabilities getConnectorCapabilities() throws ConnectorException {
+ // create Capabilities
+ String className = this.environment.getCapabilitiesClass();
+ try {
+ ConnectorCapabilities result = null;
+ if (className != null && className.length() > 0) {
+ result = (ConnectorCapabilities) ReflectionHelper.create(className, null, Thread.currentThread().getContextClassLoader());
+ } else {
+ result = getDefaultCapabilities().newInstance();
+ }
+
+ return result;
+ } catch (Exception e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ /**
+ * Set to true to indicate that every branch of a join
+ * should have parenthesis.
+ * @return
+ */
+ public boolean useParensForJoins() {
+ return false;
+ }
+
+ /**
+ * get the default null ordering
+ * @return
+ */
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.LOW;
+ }
+
+ /**
+ *
+ * @return true if nulls high|low can be specified
+ */
+ public boolean supportsExplicitNullOrdering() {
+ return false;
+ }
+
+ /**
+ *
+ * @return true if the limit clause is part of the select
+ */
+ public boolean useSelectLimit() {
+ return false;
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/Translator.java
___________________________________________________________________
Name: svn:mergeinfo
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.access;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+public class AccessCapabilities extends JDBCCapabilities{
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrderBy()
+ */
+ public boolean supportsOrderBy() {
+ return false;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInsertWithQueryExpression() {
+ return false;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/access/AccessSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.access;
+
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.translator.jdbc.sybase.SybaseSQLTranslator;
+
+
+public class AccessSQLTranslator extends SybaseSQLTranslator {
+
+ @Override
+ public String translateLiteralBoolean(Boolean booleanValue) {
+ if(booleanValue.booleanValue()) {
+ return "-1"; //$NON-NLS-1$
+ }
+ return "0"; //$NON-NLS-1$
+ }
+
+ @Override
+ public boolean addSourceComment() {
+ return false;
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return AccessCapabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2Capabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2Capabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2Capabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,141 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.db2;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+/**
+ */
+public class DB2Capabilities extends JDBCCapabilities {
+
+ public DB2Capabilities() {
+ }
+
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ //supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ //supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ //supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("RAND"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ //supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ //supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("DAY"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+ supportedFunctions.add("COALESCE"); //$NON-NLS-1$
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsExcept()
+ */
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsIntersect()
+ */
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2SQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2SQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2SQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,159 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.db2;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.Join;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.Comparison.Operator;
+import org.teiid.connector.language.Join.JoinType;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+
+public class DB2SQLTranslator extends Translator {
+
+ private final class NullHandlingFormatModifier extends
+ ConvertModifier.FormatModifier {
+ private NullHandlingFormatModifier(String alias) {
+ super(alias);
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ Expression arg = function.getParameters().get(0);
+ if (arg instanceof Literal && ((Literal)arg).getValue() == null) {
+ ((Literal)function.getParameters().get(1)).setValue(this.alias);
+ return null;
+ }
+ return super.translate(function);
+ }
+ }
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("coalesce")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr")); //$NON-NLS-1$
+
+ registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier("MOD", getLanguageFactory())); //$NON-NLS-1$
+
+ //add in type conversion
+ ConvertModifier convertModifier = new ConvertModifier();
+ convertModifier.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(31,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(31,12)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("blob", FunctionModifier.BLOB, FunctionModifier.OBJECT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("clob", FunctionModifier.CLOB, FunctionModifier.XML); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("timestamp('1970-01-01', ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("timestamp(",function.getParameters().get(0), ", '00:00:00')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ //the next convert is not strictly necessary for db2, but it also works for derby
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("cast(double(", function.getParameters().get(0), ") as real)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("char"), FunctionModifier.STRING); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("smallint"), FunctionModifier.BYTE, FunctionModifier.SHORT); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("integer"), FunctionModifier.INTEGER); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("bigint"), FunctionModifier.LONG); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("double"), FunctionModifier.DOUBLE); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("date"), FunctionModifier.DATE); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("time"), FunctionModifier.TIME); //$NON-NLS-1$
+ convertModifier.addTypeConversion(new NullHandlingFormatModifier("timestamp"), FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addNumericBooleanConversions();
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<?> translateLimit(Limit limit, ExecutionContext context) {
+ return Arrays.asList("FETCH FIRST ", limit.getRowLimit(), " ROWS ONLY"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ //DB2 doesn't support cross join
+ if (obj instanceof Join) {
+ Join join = (Join)obj;
+ if (join.getJoinType() == JoinType.CROSS_JOIN) {
+ Literal one = getLanguageFactory().createLiteral(1, TypeFacility.RUNTIME_TYPES.INTEGER);
+ join.setCondition(getLanguageFactory().createCompareCriteria(Operator.EQ, one, one));
+ join.setJoinType(JoinType.INNER_JOIN);
+ }
+ }
+ //DB2 needs projected nulls wrapped in casts
+ if (obj instanceof DerivedColumn) {
+ DerivedColumn selectSymbol = (DerivedColumn)obj;
+ if (selectSymbol.getExpression() instanceof Literal) {
+ Literal literal = (Literal)selectSymbol.getExpression();
+ if (literal.getValue() == null) {
+ selectSymbol.setExpression(ConvertModifier.createConvertFunction(getLanguageFactory(), literal, TypeFacility.getDataTypeName(literal.getType())));
+ }
+ }
+ }
+ return super.translate(obj, context);
+ }
+
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return DB2Capabilities.class;
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.HIGH;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,192 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.derby;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+
+/**
+ * @since 5.0
+ */
+public class DerbyCapabilities extends JDBCCapabilities {
+
+ public static final String TEN_1 = "10.1"; //$NON-NLS-1$
+ public static final String TEN_2 = "10.2"; //$NON-NLS-1$
+ public static final String TEN_4 = "10.4"; //$NON-NLS-1$
+ public static final String TEN_5 = "10.5"; //$NON-NLS-1$
+
+ private String version = TEN_1;
+
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ if (version.compareTo(TEN_2) >= 0) {
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ }
+ if (version.compareTo(TEN_4) >= 0) {
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ }
+ // These are executed within the server and never pushed down
+ //supportedFunctions.add("BITAND"); //$NON-NLS-1$
+ //supportedFunctions.add("BITNOT"); //$NON-NLS-1$
+ //supportedFunctions.add("BITOR"); //$NON-NLS-1$
+ //supportedFunctions.add("BITXOR"); //$NON-NLS-1$
+ if (version.compareTo(TEN_2) >= 0) {
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ }
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ if (version.compareTo(TEN_2) >= 0) {
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ //supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ //supportedFunctions.add("ROUND"); //$NON-NLS-1$
+ if (version.compareTo(TEN_4) >= 0) {
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ }
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ }
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ //supportedFunctions.add("TAN"); //$NON-NLS-1$
+
+ //supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ //supportedFunctions.add("CHR"); //$NON-NLS-1$
+ //supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ //supportedFunctions.add("INSERT"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ //supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ //supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ //supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ //supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ //supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+
+ // These are executed within the server and never pushed down
+ //supportedFunctions.add("CURDATE"); //$NON-NLS-1$
+ //supportedFunctions.add("CURTIME"); //$NON-NLS-1$
+ //supportedFunctions.add("NOW"); //$NON-NLS-1$
+ //supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ //supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ //supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ //supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ //supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ //supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("COALESCE"); //$NON-NLS-1$
+ return supportedFunctions;
+ }
+
+ public void setDatabaseVersion(String version) {
+ this.version = version;
+ }
+
+ /**
+ * Derby supports only SearchedCaseExpression, not CaseExpression.
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsCaseExpressions()
+ * @since 5.0
+ */
+ public boolean supportsCaseExpressions() {
+ return false;
+ }
+
+ /**
+ * Derby supports only left and right outer joins.
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFullOuterJoins()
+ * @since 5.0
+ */
+ public boolean supportsFullOuterJoins() {
+ return false;
+ }
+
+ /**
+ * Inline views (subqueries in the FROM clause) are supported.
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsInlineViews()
+ * @since 4.3
+ */
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsExcept()
+ */
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsIntersect()
+ */
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsRowLimit() {
+ return this.version.compareTo(TEN_5) >= 0;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbySQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbySQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,73 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.derby;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.EscapeSyntaxModifier;
+import org.teiid.translator.jdbc.db2.DB2SQLTranslator;
+import org.teiid.translator.jdbc.oracle.LeftOrRightFunctionModifier;
+
+
+
+/**
+ * @since 4.3
+ */
+public class DerbySQLTranslator extends DB2SQLTranslator {
+
+ private String version = DerbyCapabilities.TEN_1;
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ //additional derby functions
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+
+ //overrides of db2 functions
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new EscapeSyntaxModifier());
+ }
+
+ @Override
+ public boolean addSourceComment() {
+ return false;
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return DerbyCapabilities.class;
+ }
+
+ @Override
+ public boolean supportsExplicitNullOrdering() {
+ return version.compareTo(DerbyCapabilities.TEN_4) >= 0;
+ }
+
+ public void setDatabaseVersion(String version) {
+ this.version = version;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Capabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Capabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Capabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,133 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+public class H2Capabilities extends JDBCCapabilities {
+
+ 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;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Translator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Translator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.jdbc.h2;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.hsql.AddDiffModifier;
+import org.teiid.translator.jdbc.oracle.ConcatFunctionModifier;
+
+public class H2Translator extends Translator {
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ 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 Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return H2Capabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/AddDiffModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/AddDiffModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/AddDiffModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,101 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.hsql;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+public class AddDiffModifier extends FunctionModifier {
+
+ private static Map<String, String> INTERVAL_MAP = new HashMap<String, String>();
+
+ static {
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_DAY, ExtractFunctionModifier.DAY);
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_HOUR, ExtractFunctionModifier.HOUR);
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_MINUTE, ExtractFunctionModifier.MINUTE);
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_MONTH, ExtractFunctionModifier.MONTH);
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_SECOND, ExtractFunctionModifier.SECOND);
+ INTERVAL_MAP.put(SQLReservedWords.SQL_TSI_YEAR, ExtractFunctionModifier.YEAR);
+ }
+
+ private boolean add;
+ private LanguageFactory factory;
+
+ public AddDiffModifier(boolean add, LanguageFactory factory) {
+ this.add = add;
+ this.factory = factory;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ if (add) {
+ function.setName("dateadd"); //$NON-NLS-1$
+ } else {
+ function.setName("datediff"); //$NON-NLS-1$
+ }
+ Literal intervalType = (Literal)function.getParameters().get(0);
+ String interval = ((String)intervalType.getValue()).toUpperCase();
+ String newInterval = INTERVAL_MAP.get(interval);
+ if (newInterval != null) {
+ intervalType.setValue(newInterval);
+ return null;
+ }
+ if (add) {
+ if (interval.equals(SQLReservedWords.SQL_TSI_FRAC_SECOND)) {
+ intervalType.setValue("MILLISECOND"); //$NON-NLS-1$
+ Expression[] args = new Expression[] {function.getParameters().get(1), factory.createLiteral(1000000, TypeFacility.RUNTIME_TYPES.INTEGER)};
+ function.getParameters().set(1, factory.createFunction("/", args, TypeFacility.RUNTIME_TYPES.INTEGER)); //$NON-NLS-1$
+ } else if (interval.equals(SQLReservedWords.SQL_TSI_QUARTER)) {
+ intervalType.setValue(ExtractFunctionModifier.DAY);
+ Expression[] args = new Expression[] {function.getParameters().get(1), factory.createLiteral(91, TypeFacility.RUNTIME_TYPES.INTEGER)};
+ function.getParameters().set(1, factory.createFunction("*", args, TypeFacility.RUNTIME_TYPES.INTEGER)); //$NON-NLS-1$
+ } else {
+ intervalType.setValue(ExtractFunctionModifier.DAY);
+ Expression[] args = new Expression[] {function.getParameters().get(1), factory.createLiteral(7, TypeFacility.RUNTIME_TYPES.INTEGER)};
+ function.getParameters().set(1, factory.createFunction("*", args, TypeFacility.RUNTIME_TYPES.INTEGER)); //$NON-NLS-1$
+ }
+ return null;
+ }
+ if (interval.equals(SQLReservedWords.SQL_TSI_FRAC_SECOND)) {
+ intervalType.setValue("MILLISECOND"); //$NON-NLS-1$
+ return Arrays.asList(function, " * 1000000"); //$NON-NLS-1$
+ } else if (interval.equals(SQLReservedWords.SQL_TSI_QUARTER)) {
+ intervalType.setValue(ExtractFunctionModifier.DAY);
+ return Arrays.asList(function, " / 91"); //$NON-NLS-1$
+ }
+ intervalType.setValue(ExtractFunctionModifier.DAY);
+ return Arrays.asList(function, " / 7"); //$NON-NLS-1$
+ }
+
+}
\ No newline at end of file
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,133 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.hsql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+public class HsqlCapabilities extends JDBCCapabilities {
+
+ 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.FORMATDATE);
+ //supportedFunctions.add(SourceSystemFunctions.FORMATTIME);
+ //supportedFunctions.add(SourceSystemFunctions.FORMATTIMESTAMP);
+ supportedFunctions.add(SourceSystemFunctions.HOUR);
+ supportedFunctions.add(SourceSystemFunctions.MINUTE);
+ supportedFunctions.add(SourceSystemFunctions.MONTH);
+ supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
+
+ //supportedFunctions.add(SourceSystemFunctions.PARSEDATE);
+ //supportedFunctions.add(SourceSystemFunctions.PARSETIME);
+ //supportedFunctions.add(SourceSystemFunctions.PARSETIMESTAMP);
+ supportedFunctions.add(SourceSystemFunctions.QUARTER);
+ supportedFunctions.add(SourceSystemFunctions.SECOND);
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
+ supportedFunctions.add(SourceSystemFunctions.WEEK);
+ supportedFunctions.add(SourceSystemFunctions.YEAR);
+
+ supportedFunctions.add(SourceSystemFunctions.CONVERT);
+ supportedFunctions.add(SourceSystemFunctions.IFNULL);
+ supportedFunctions.add(SourceSystemFunctions.COALESCE);
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,83 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.hsql;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+
+public class HsqlTranslator extends Translator {
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ 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 Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return HsqlCapabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,45 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.informix;
+
+import java.util.*;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+/**
+ */
+public class InformixCapabilities extends JDBCCapabilities {
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List getSupportedFunctions() {
+ List supportedFunctons = new ArrayList();
+ supportedFunctons.addAll(super.getSupportedFunctions());
+ supportedFunctons.add("CAST"); //$NON-NLS-1$
+ supportedFunctons.add("CONVERT"); //$NON-NLS-1$
+ return supportedFunctons;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/informix/InformixSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,50 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.informix;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ */
+public class InformixSQLTranslator extends Translator {
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, new ConvertModifier());
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return InformixCapabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mm/MMCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mm/MMCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mm/MMCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,126 @@
+/*
+ * Copyright © 2000-2005 MetaMatrix, Inc. All rights reserved.
+ */
+/*
+ */
+package org.teiid.translator.jdbc.mm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+/**
+ * Capabilities compatible with MM 5.5.x
+ */
+public class MMCapabilities extends JDBCCapabilities {
+
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATBIGDECIMAL"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATBIGINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATDOUBLE"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATFLOAT"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATLONG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEBIGDECIMAL"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEBIGINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEDOUBLE"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEFLOAT"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("PARSELONG"); //$NON-NLS-1$
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("RAND"); //$NON-NLS-1$
+ supportedFunctions.add("ROUND"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT2"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("INSERT"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("CURDATE"); //$NON-NLS-1$
+ supportedFunctions.add("CURTIME"); //$NON-NLS-1$
+ supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+ supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+ supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("MODIFYTIMEZONE"); //$NON-NLS-1$
+ supportedFunctions.add("DECODESTRING"); //$NON-NLS-1$
+ supportedFunctions.add("DECODEINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("USER"); //$NON-NLS-1$
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ public boolean supportsRowOffset() {
+ return true;
+ }
+}
\ No newline at end of file
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/BitFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/BitFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/BitFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.mysql;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+
+public class BitFunctionModifier extends AliasModifier {
+ private LanguageFactory langFactory;
+
+ public BitFunctionModifier(String alias, LanguageFactory langFactory) {
+ super(alias);
+ this.langFactory = langFactory;
+ }
+
+ /**
+ * Wrap the renamed function in a convert back to integer
+ */
+ @Override
+ public List<?> translate(Function function) {
+ modify(function);
+ return Arrays.asList(ConvertModifier.createConvertFunction(langFactory, function, TypeFacility.RUNTIME_NAMES.INTEGER));
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Capabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Capabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Capabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,49 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.mysql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+
+
+/**
+ * @since 4.3
+ */
+public class MySQL5Capabilities extends MySQLCapabilities {
+
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
+ supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
+ return supportedFunctions;
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Translator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Translator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.mysql;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Function;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+public class MySQL5Translator extends MySQLTranslator {
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.CHAR, new FunctionModifier() {
+
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("char(", function.getParameters().get(0), " USING ASCII)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return MySQL5Capabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,282 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.mysql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+
+
+/**
+ * @since 4.3
+ */
+public class MySQLCapabilities extends JDBCCapabilities {
+
+ 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);
+
+ // These are executed within the server and never pushed down
+// supportedFunctions.add("CURDATE"); //$NON-NLS-1$
+// supportedFunctions.add("CURTIME"); //$NON-NLS-1$
+// supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add(SourceSystemFunctions.DAYNAME);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
+ supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
+
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add(SourceSystemFunctions.HOUR);
+ supportedFunctions.add(SourceSystemFunctions.MINUTE);
+ supportedFunctions.add(SourceSystemFunctions.MONTH);
+ supportedFunctions.add(SourceSystemFunctions.MONTHNAME);
+
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add(SourceSystemFunctions.QUARTER);
+ supportedFunctions.add(SourceSystemFunctions.SECOND);
+// supportedFunctions.add(SourceSystemFunctions.TIMESTAMPADD);
+// supportedFunctions.add(SourceSystemFunctions.TIMESTAMPDIFF);
+ supportedFunctions.add(SourceSystemFunctions.WEEK);
+ supportedFunctions.add(SourceSystemFunctions.YEAR);
+
+ supportedFunctions.add(SourceSystemFunctions.CONVERT);
+ supportedFunctions.add(SourceSystemFunctions.IFNULL);
+ supportedFunctions.add(SourceSystemFunctions.COALESCE);
+
+// supportedFunctions.add("GREATEST"); //$NON-NLS-1$
+// supportedFunctions.add("ISNULL"); //$NON-NLS-1$
+// supportedFunctions.add("LEAST"); //$NON-NLS-1$
+// supportedFunctions.add("STRCMP"); // String-specific //$NON-NLS-1$
+//
+// // String
+// supportedFunctions.add("BIN"); //$NON-NLS-1$
+// supportedFunctions.add("BIT_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("CHAR_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("CHARACTER_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("COMPRESS"); //$NON-NLS-1$
+// supportedFunctions.add("CONCAT_WS"); //$NON-NLS-1$
+// supportedFunctions.add("CONV"); //$NON-NLS-1$
+// supportedFunctions.add("ELT"); //$NON-NLS-1$
+// supportedFunctions.add("EXPORT_SET"); //$NON-NLS-1$
+// supportedFunctions.add("FIELD"); //$NON-NLS-1$
+// supportedFunctions.add("FIND_IN_SET"); //$NON-NLS-1$
+// supportedFunctions.add("FORMAT"); //$NON-NLS-1$
+// supportedFunctions.add("HEX"); //$NON-NLS-1$
+// supportedFunctions.add("INSTR"); //$NON-NLS-1$
+// supportedFunctions.add("LOAD_FILE"); //$NON-NLS-1$
+// supportedFunctions.add("MAKE_SET"); //$NON-NLS-1$
+// supportedFunctions.add("MID"); //$NON-NLS-1$
+// supportedFunctions.add("OCT"); //$NON-NLS-1$
+// supportedFunctions.add("OCTET_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("ORD"); //$NON-NLS-1$
+// supportedFunctions.add("QUOTE"); //$NON-NLS-1$
+// supportedFunctions.add("REVERSE"); //$NON-NLS-1$
+// supportedFunctions.add("SOUNDEX"); //$NON-NLS-1$
+// supportedFunctions.add("SPACE"); //$NON-NLS-1$
+// supportedFunctions.add("SUBSTR"); //$NON-NLS-1$
+// supportedFunctions.add("SUBSTRING_INDEX"); //$NON-NLS-1$
+// supportedFunctions.add("TRIM"); //$NON-NLS-1$
+// supportedFunctions.add("UNCOMPRESS"); //$NON-NLS-1$
+// supportedFunctions.add("UNHEX"); //$NON-NLS-1$
+//
+// // Math
+// supportedFunctions.add("CEIL"); //$NON-NLS-1$
+// supportedFunctions.add("CRC32"); //$NON-NLS-1$
+// // DIV is an operator equivalent to '/'
+// supportedFunctions.add("DIV"); //$NON-NLS-1$
+// supportedFunctions.add("FORMAT"); //$NON-NLS-1$
+// supportedFunctions.add("LN"); //$NON-NLS-1$
+// supportedFunctions.add("LOG2"); //$NON-NLS-1$
+// supportedFunctions.add("POW"); //$NON-NLS-1$
+// supportedFunctions.add("RAND"); //$NON-NLS-1$
+// supportedFunctions.add("TRUNCATE"); //$NON-NLS-1$
+//
+// // Date / Time
+// supportedFunctions.add("ADDDATE"); //$NON-NLS-1$
+// supportedFunctions.add("ADDTIME"); //$NON-NLS-1$
+// supportedFunctions.add("CONVERT_TZ"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_DATE"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_TIME"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_TIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("DATE"); //$NON-NLS-1$
+// supportedFunctions.add("DATEDIFF"); //$NON-NLS-1$
+//// supportedFunctions.add("DATE_ADD");
+//// supportedFunctions.add("DATE_SUB");
+// supportedFunctions.add("DATE_FORMAT"); //$NON-NLS-1$
+// supportedFunctions.add("DAY"); //$NON-NLS-1$
+//// supportedFunctions.add("EXTRACT");
+// supportedFunctions.add("FROM_DAYS"); //$NON-NLS-1$
+// supportedFunctions.add("FROM_UNIXTIME"); //$NON-NLS-1$
+// supportedFunctions.add("GET_FORMAT"); //$NON-NLS-1$
+// supportedFunctions.add("LAST_DAY"); //$NON-NLS-1$
+// supportedFunctions.add("LOCALTIME"); //$NON-NLS-1$
+// supportedFunctions.add("LOCALTIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("MAKEDATE"); //$NON-NLS-1$
+// supportedFunctions.add("MAKETIME"); //$NON-NLS-1$
+// supportedFunctions.add("MICROSECOND"); //$NON-NLS-1$
+// supportedFunctions.add("PERIOD_ADD"); //$NON-NLS-1$
+// supportedFunctions.add("PERIOD_DIFF"); //$NON-NLS-1$
+// supportedFunctions.add("SEC_TO_TIME"); //$NON-NLS-1$
+// supportedFunctions.add("STR_TO_DATE"); //$NON-NLS-1$
+// supportedFunctions.add("SUBDATE"); //$NON-NLS-1$
+// supportedFunctions.add("SUBTIME"); //$NON-NLS-1$
+// supportedFunctions.add("SYSDATE"); //$NON-NLS-1$
+// supportedFunctions.add("TIME"); //$NON-NLS-1$
+// supportedFunctions.add("TIMEDIFF"); //$NON-NLS-1$
+// supportedFunctions.add("TIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("TIME_FORMAT"); //$NON-NLS-1$
+// supportedFunctions.add("TIME_TO_SEC"); //$NON-NLS-1$
+// supportedFunctions.add("TO_DAYS"); //$NON-NLS-1$
+// supportedFunctions.add("UNIX_TIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("UTC_DATE"); //$NON-NLS-1$
+// supportedFunctions.add("UTC_TIME"); //$NON-NLS-1$
+// supportedFunctions.add("UTC_TIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("WEEKDAY"); //$NON-NLS-1$
+// supportedFunctions.add("WEEKOFYEAR"); //$NON-NLS-1$
+// supportedFunctions.add("YEARWEEK"); //$NON-NLS-1$
+//
+// // Bit
+// supportedFunctions.add("|"); //$NON-NLS-1$
+// supportedFunctions.add("&"); //$NON-NLS-1$
+// supportedFunctions.add("^"); //$NON-NLS-1$
+// supportedFunctions.add("<<"); //$NON-NLS-1$
+// supportedFunctions.add(">>"); //$NON-NLS-1$
+// supportedFunctions.add("~"); //$NON-NLS-1$
+// supportedFunctions.add("BIT_COUNT"); //$NON-NLS-1$
+//
+// // Encryption
+// supportedFunctions.add("AES_ENCRYPT"); //$NON-NLS-1$
+// supportedFunctions.add("AES_DECRYPT"); //$NON-NLS-1$
+// supportedFunctions.add("DECODE"); //$NON-NLS-1$
+// supportedFunctions.add("ENCODE"); //$NON-NLS-1$
+// supportedFunctions.add("DES_ENCRYPT"); //$NON-NLS-1$
+// supportedFunctions.add("DES_DECRYPT"); //$NON-NLS-1$
+// supportedFunctions.add("MD5"); //$NON-NLS-1$
+// supportedFunctions.add("OLD_PASSWORD"); //$NON-NLS-1$
+// supportedFunctions.add("PASSWORD"); //$NON-NLS-1$
+// supportedFunctions.add("SHA"); //$NON-NLS-1$
+// supportedFunctions.add("SHA1"); //$NON-NLS-1$
+//
+// // Information
+// supportedFunctions.add("BENCHMARK"); //$NON-NLS-1$
+// supportedFunctions.add("CHARSET"); //$NON-NLS-1$
+// supportedFunctions.add("COERCIBILITY"); //$NON-NLS-1$
+// supportedFunctions.add("COLLATION"); //$NON-NLS-1$
+// supportedFunctions.add("CONNECTION_ID"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_USER"); //$NON-NLS-1$
+// supportedFunctions.add("DATABASE"); //$NON-NLS-1$
+// supportedFunctions.add("FOUND_ROWS"); //$NON-NLS-1$
+// supportedFunctions.add("LAST_INSERT_ID"); //$NON-NLS-1$
+// supportedFunctions.add("ROW_COUNT"); //$NON-NLS-1$
+// supportedFunctions.add("SCHEMA"); //$NON-NLS-1$
+// supportedFunctions.add("SESSION_USER"); //$NON-NLS-1$
+// supportedFunctions.add("SYSTEM_USER"); //$NON-NLS-1$
+// supportedFunctions.add("USER"); //$NON-NLS-1$
+// supportedFunctions.add("VERSION"); //$NON-NLS-1$
+//
+// // Misc.
+// supportedFunctions.add("DEFAULT"); //$NON-NLS-1$
+// supportedFunctions.add("FORMAT"); //$NON-NLS-1$
+//// supportedFunctions.add("GET_LOCK"); //$NON-NLS-1$
+// supportedFunctions.add("INET_ATON"); //$NON-NLS-1$
+// supportedFunctions.add("INET_NTOA"); //$NON-NLS-1$
+//// supportedFunctions.add("IS_FREE_LOCK"); //$NON-NLS-1$
+//// supportedFunctions.add("IS_USED_LOCK"); //$NON-NLS-1$
+//// supportedFunctions.add("MASTER_POS_WAIT"); //$NON-NLS-1$
+//// supportedFunctions.add("NAME_CONST"); //$NON-NLS-1$
+//// supportedFunctions.add("RELEASE_LOCK"); //$NON-NLS-1$
+//// supportedFunctions.add("SLEEP"); //$NON-NLS-1$
+// supportedFunctions.add("UUID"); //$NON-NLS-1$
+// supportedFunctions.add("VALUES"); //$NON-NLS-1$
+ return supportedFunctions;
+ }
+
+ public boolean supportsFullOuterJoins() {
+ return false;
+ }
+
+ public boolean supportsAggregatesDistinct() {
+ return false;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+ public boolean supportsRowOffset() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,156 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.mysql;
+
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Function;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ * @since 4.3
+ */
+public class MySQLTranslator extends Translator {
+
+ /**
+ * Adds support for the 2 argument form of padding
+ */
+ private final class PadFunctionModifier extends FunctionModifier {
+ @Override
+ public List<?> translate(Function function) {
+ if (function.getParameters().size() == 2) {
+ function.getParameters().add(getLanguageFactory().createLiteral(" ", TypeFacility.RUNTIME_TYPES.STRING)); //$NON-NLS-1$
+ }
+ return null;
+ }
+ }
+
+ @Override
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.BITAND, new BitFunctionModifier("&", getLanguageFactory())); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITNOT, new BitFunctionModifier("~", getLanguageFactory())); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITOR, new BitFunctionModifier("|", getLanguageFactory())); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITXOR, new BitFunctionModifier("^", getLanguageFactory())); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.LPAD, new PadFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.RPAD, new PadFunctionModifier());
+ //add in type conversion
+ ConvertModifier convertModifier = new ConvertModifier();
+ convertModifier.addTypeMapping("signed", FunctionModifier.BOOLEAN, FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.INTEGER, FunctionModifier.LONG); //$NON-NLS-1$
+ //char(n) assume 4.1 or later
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("char", FunctionModifier.STRING); //$NON-NLS-1$
+ convertModifier.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
+ convertModifier.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
+ convertModifier.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("DATE")); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("TIME")); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("TIMESTAMP")); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new ConvertModifier.FormatModifier("date_format", "%Y-%m-%d")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("date_format", "%H:%i:%S")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new ConvertModifier.FormatModifier("date_format", "%Y-%m-%d %H:%i:%S.%f")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addTypeConversion(new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList(function.getParameters().get(0), " + 0.0"); //$NON-NLS-1$
+ }
+ }, FunctionModifier.BIGDECIMAL, FunctionModifier.BIGINTEGER, FunctionModifier.FLOAT, FunctionModifier.DOUBLE);
+ convertModifier.addNumericBooleanConversions();
+ convertModifier.setWideningNumericImplicit(true);
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+ }
+
+ @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 "{ts '" + formatDateValue(timestampValue) + "'}"; //$NON-NLS-1$//$NON-NLS-2$
+ }
+
+ @Override
+ public boolean useParensForSetQueries() {
+ return true;
+ }
+
+ @Override
+ public int getTimestampNanoPrecision() {
+ return 0;
+ }
+
+ @Override
+ public void afterConnectionCreation(Connection connection) {
+ super.afterConnectionCreation(connection);
+
+ Statement stmt = null;
+ try {
+ stmt = connection.createStatement();
+ stmt.execute("set SESSION sql_mode = 'ANSI'"); //$NON-NLS-1$
+ } catch (SQLException e) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, e, "Error setting ANSI mode"); //$NON-NLS-1$
+ } finally {
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ LogManager.logDetail("Error closing statement", e); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return MySQLCapabilities.class;
+ }
+
+ public boolean useParensForJoins() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/ConcatFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/ConcatFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/ConcatFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,111 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Condition;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SearchedWhenClause;
+import org.teiid.connector.language.AndOr.Operator;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+
+/**
+ * This Function modifier used to support ANSI concat on Oracle 9i.
+ * <code>
+ * CONCAT(a, b) ==> CASE WHEN (a is NULL OR b is NULL) THEN NULL ELSE CONCAT(a, b)
+ * </code>
+ */
+public class ConcatFunctionModifier extends FunctionModifier {
+ private LanguageFactory langFactory;
+
+ /**
+ * @param langFactory
+ */
+ public ConcatFunctionModifier(LanguageFactory langFactory) {
+ this.langFactory = langFactory;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ Expression a = function.getParameters().get(0);
+ Expression b = function.getParameters().get(1);
+ List<Condition> crits = new ArrayList<Condition>();
+
+ Literal nullValue = langFactory.createLiteral(null, TypeFacility.RUNTIME_TYPES.STRING);
+ if (isNull(a)) {
+ return Arrays.asList(nullValue);
+ } else if (!isNotNull(a)) {
+ crits.add(langFactory.createIsNullCriteria(a, false));
+ }
+ if (isNull(b)) {
+ return Arrays.asList(nullValue);
+ } else if (!isNotNull(b)) {
+ crits.add(langFactory.createIsNullCriteria(b, false));
+ }
+
+ Condition crit = null;
+
+ if (crits.isEmpty()) {
+ return null;
+ } else if (crits.size() == 1) {
+ crit = crits.get(0);
+ } else {
+ crit = langFactory.createAndOr(Operator.OR, crits.get(0), crits.get(1));
+ }
+ List<SearchedWhenClause> cases = Arrays.asList(langFactory.createSearchedWhenCondition(crit, nullValue));
+ return Arrays.asList(langFactory.createSearchedCaseExpression(cases, function, TypeFacility.RUNTIME_TYPES.STRING));
+ }
+
+ private boolean isNotNull(Expression expr) {
+ if (expr instanceof Literal) {
+ Literal literal = (Literal)expr;
+ return literal.getValue() != null;
+ }
+ if (expr instanceof Function) {
+ Function function = (Function)expr;
+ if (function.getName().equalsIgnoreCase("NVL") || function.getName().equalsIgnoreCase(SourceSystemFunctions.IFNULL)) { //$NON-NLS-1$
+ return isNotNull(function.getParameters().get(1));
+ }
+ }
+ return false;
+ }
+
+ private boolean isNull(Expression expr) {
+ if (expr instanceof Literal) {
+ Literal literal = (Literal)expr;
+ return literal.getValue() == null;
+ }
+ return false;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/DayWeekQuarterFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/DayWeekQuarterFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/DayWeekQuarterFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,52 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Function;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+/**
+ * This a method for multiple use. It can be used for:
+ * 1) dayofyear
+ * 2) dayofmonth
+ * 3) dayofweek
+ * 4) week
+ * 5) quarter
+ */
+public class DayWeekQuarterFunctionModifier extends FunctionModifier {
+ private String format;
+
+ public DayWeekQuarterFunctionModifier(String format) {
+ this.format = format;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("to_number(TO_CHAR(",function.getParameters().get(0), ", '", format,"'))"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+}
+
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/LeftOrRightFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/LeftOrRightFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/LeftOrRightFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,72 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+/**
+ * Convert left(string, count) --> substr(string, 1, count)
+ * or right(string, count) --> substr(string, -1 * count) - we lack a way to express a unary negation
+ */
+public class LeftOrRightFunctionModifier extends FunctionModifier {
+ private LanguageFactory langFactory;
+
+ public LeftOrRightFunctionModifier(LanguageFactory langFactory) {
+ this.langFactory = langFactory;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ List<Expression> args = function.getParameters();
+ Function func = null;
+
+ if (function.getName().equalsIgnoreCase("left")) { //$NON-NLS-1$
+ func = langFactory.createFunction("SUBSTR", //$NON-NLS-1$
+ Arrays.asList(
+ args.get(0),
+ langFactory.createLiteral(Integer.valueOf(1), TypeFacility.RUNTIME_TYPES.INTEGER),
+ args.get(1)),
+ String.class);
+ } else if (function.getName().equalsIgnoreCase("right")) { //$NON-NLS-1$
+ Function negIndex = langFactory.createFunction("*", //$NON-NLS-1$
+ Arrays.asList(langFactory.createLiteral(Integer.valueOf(-1), TypeFacility.RUNTIME_TYPES.INTEGER), args.get(1)),
+ Integer.class);
+
+ func = langFactory.createFunction("SUBSTR", //$NON-NLS-1$
+ Arrays.asList(
+ args.get(0),
+ negIndex),
+ String.class);
+ }
+
+ return Arrays.asList(func);
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/Log10FunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/Log10FunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/Log10FunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,52 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+public class Log10FunctionModifier extends FunctionModifier {
+
+ private LanguageFactory languageFactory;
+
+ public Log10FunctionModifier(LanguageFactory languageFactory) {
+ this.languageFactory = languageFactory;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ function.setName("log"); //$NON-NLS-1$
+
+ List<Expression> args = function.getParameters();
+ args.add(args.get(0));
+ args.set(0, languageFactory.createLiteral(new Integer(10), TypeFacility.RUNTIME_TYPES.INTEGER));
+ return null;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/MonthOrDayNameFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/MonthOrDayNameFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/MonthOrDayNameFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+/**
+ * Convert the MONTHNAME etc. function into an equivalent Oracle function.
+ * Format: to_char(timestampvalue/dayvalue, 'Month'/'Day')
+ */
+public class MonthOrDayNameFunctionModifier extends FunctionModifier {
+ private LanguageFactory langFactory;
+ private String format;
+
+ public MonthOrDayNameFunctionModifier(LanguageFactory langFactory, String format) {
+ this.langFactory = langFactory;
+ this.format = format;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ List<Expression> args = function.getParameters();
+
+ Function func = langFactory.createFunction("TO_CHAR", //$NON-NLS-1$
+ Arrays.asList(
+ args.get(0),
+ langFactory.createLiteral(format, TypeFacility.RUNTIME_TYPES.STRING)),
+ TypeFacility.RUNTIME_TYPES.STRING);
+
+ // For some reason, these values have trailing spaces
+ Function trimFunc = langFactory.createFunction(SourceSystemFunctions.RTRIM,
+ Arrays.asList( func ), TypeFacility.RUNTIME_TYPES.STRING);
+
+ return Arrays.asList(trimFunc);
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,154 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+/*
+ */
+package org.teiid.translator.jdbc.oracle;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+import org.teiid.resource.cci.SourceSystemFunctions;
+
+
+/**
+ */
+public class OracleCapabilities extends JDBCCapabilities {
+
+ public OracleCapabilities() {
+ }
+
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add(SourceSystemFunctions.COT);
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("DAY"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+ //supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+ supportedFunctions.add("COALESCE"); //$NON-NLS-1$
+
+ supportedFunctions.add(OracleSQLTranslator.RELATE);
+ supportedFunctions.add(OracleSQLTranslator.NEAREST_NEIGHBOR);
+ supportedFunctions.add(OracleSQLTranslator.FILTER);
+ supportedFunctions.add(OracleSQLTranslator.NEAREST_NEIGHBOR_DISTANCE);
+ supportedFunctions.add(OracleSQLTranslator.WITHIN_DISTANCE);
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsExcept()
+ */
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsIntersect()
+ */
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,439 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.ExpressionValueSource;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.language.SQLReservedWords.Tokens;
+import org.teiid.connector.language.SetQuery.Operation;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.visitor.util.CollectorVisitor;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCPlugin;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+
+
+
+public class OracleSQLTranslator extends Translator {
+
+ /*
+ * Spatial Functions
+ */
+ public static final String RELATE = "sdo_relate"; //$NON-NLS-1$
+ public static final String NEAREST_NEIGHBOR = "sdo_nn"; //$NON-NLS-1$
+ public static final String FILTER = "sdo_filter"; //$NON-NLS-1$
+ public static final String WITHIN_DISTANCE = "sdo_within_distance"; //$NON-NLS-1$
+ public static final String NEAREST_NEIGHBOR_DISTANCE = "sdo_nn_distance"; //$NON-NLS-1$
+
+ public final static String HINT_PREFIX = "/*+"; //$NON-NLS-1$
+ public final static String DUAL = "DUAL"; //$NON-NLS-1$
+ public final static String ROWNUM = "ROWNUM"; //$NON-NLS-1$
+ public final static String SEQUENCE = ":SEQUENCE="; //$NON-NLS-1$
+
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lower")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("upper")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("nvl")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("ln")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CEILING, new AliasModifier("ceil")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG10, new Log10FunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Month"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Day"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.WEEK, new DayWeekQuarterFunctionModifier("WW"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.QUARTER, new DayWeekQuarterFunctionModifier("Q"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new DayWeekQuarterFunctionModifier("D"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new DayWeekQuarterFunctionModifier("DDD"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory(), "INSTR", true)); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new ConcatFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ function.setName(SourceSystemFunctions.TAN);
+ return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE));
+ }
+ });
+
+ //spatial functions
+ registerFunctionModifier(RELATE, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(FILTER, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(WITHIN_DISTANCE, new OracleSpatialFunctionModifier());
+
+ //add in type conversion
+ ConvertModifier convertModifier = new ConvertModifier();
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("date", FunctionModifier.DATE, FunctionModifier.TIME); //$NON-NLS-1$
+ convertModifier.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("case when ", function.getParameters().get(0), " is null then null else to_date('1970-01-01 ' || to_char(",function.getParameters().get(0),", 'HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') end"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("trunc(cast(",function.getParameters().get(0)," AS date))"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", "YYYY-MM-DD")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", "HH24:MI:SS")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ //if column and type is date, just use date format
+ Expression ex = function.getParameters().get(0);
+ String format = "YYYY-MM-DD HH24:MI:SS.FF"; //$NON-NLS-1$
+ if (ex instanceof ColumnReference) {
+ if ("date".equals(((ColumnReference)ex).getMetadataObject().getNativeType())) { //$NON-NLS-1$
+ format = "YYYY-MM-DD HH24:MI:SS"; //$NON-NLS-1$
+ }
+ } else if (!(ex instanceof Function) && !(ex instanceof Literal)) {
+ //this isn't needed in every case, but it's simpler than inspecting the expression more
+ ex = ConvertModifier.createConvertFunction(getLanguageFactory(), function.getParameters().get(0), TypeFacility.RUNTIME_NAMES.TIMESTAMP);
+ }
+ return Arrays.asList("to_char(", ex, ", '", format, "')"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("to_date", "YYYY-MM-DD")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_date", "HH24:MI:SS")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", "YYYY-MM-DD HH24:MI:SS.FF")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_char"), FunctionModifier.STRING); //$NON-NLS-1$
+ //NOTE: numeric handling in Oracle is split only between integral vs. floating/decimal types
+ convertModifier.addTypeConversion(new ConvertModifier.FormatModifier("to_number"), //$NON-NLS-1$
+ FunctionModifier.FLOAT, FunctionModifier.DOUBLE, FunctionModifier.BIGDECIMAL);
+ convertModifier.addTypeConversion(new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ if (Number.class.isAssignableFrom(function.getParameters().get(0).getType())) {
+ return Arrays.asList("trunc(", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return Arrays.asList("trunc(to_number(", function.getParameters().get(0), "))"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ },
+ FunctionModifier.BYTE, FunctionModifier.SHORT, FunctionModifier.INTEGER, FunctionModifier.LONG, FunctionModifier.BIGINTEGER);
+ convertModifier.addNumericBooleanConversions();
+ convertModifier.setWideningNumericImplicit(true);
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+ }
+
+ public void handleInsertSequences(Insert insert) throws ConnectorException {
+ /*
+ * If a missing auto_increment column is modeled with name in source indicating that an Oracle Sequence
+ * then pull the Sequence name out of the name in source of the column.
+ */
+ if (!(insert.getValueSource() instanceof ExpressionValueSource)) {
+ return;
+ }
+ ExpressionValueSource values = (ExpressionValueSource)insert.getValueSource();
+ List<Column> allElements = insert.getTable().getMetadataObject().getColumns();
+ if (allElements.size() == values.getValues().size()) {
+ return;
+ }
+
+ int index = 0;
+ List<ColumnReference> elements = insert.getColumns();
+
+ for (Column element : allElements) {
+ if (!element.isAutoIncremented()) {
+ continue;
+ }
+ String name = element.getNameInSource();
+ int seqIndex = name.indexOf(SEQUENCE);
+ if (seqIndex == -1) {
+ continue;
+ }
+ boolean found = false;
+ while (index < elements.size()) {
+ if (element.equals(elements.get(index).getMetadataObject())) {
+ found = true;
+ break;
+ }
+ index++;
+ }
+ if (found) {
+ continue;
+ }
+
+ String sequence = name.substring(seqIndex + SEQUENCE.length());
+
+ int delimiterIndex = sequence.indexOf(Tokens.DOT);
+ if (delimiterIndex == -1) {
+ throw new ConnectorException("Invalid name in source sequence format. Expected <element name>" + SEQUENCE + "<sequence name>.<sequence value>, but was " + name); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String sequenceGroupName = sequence.substring(0, delimiterIndex);
+ String sequenceElementName = sequence.substring(delimiterIndex + 1);
+
+ NamedTable sequenceGroup = this.getLanguageFactory().createNamedTable(sequenceGroupName, null, null);
+ ColumnReference sequenceElement = this.getLanguageFactory().createColumnReference(sequenceElementName, sequenceGroup, null, element.getJavaType());
+ insert.getColumns().add(index, this.getLanguageFactory().createColumnReference(element.getName(), insert.getTable(), element, element.getJavaType()));
+ values.getValues().add(index, sequenceElement);
+ }
+ }
+
+ @Override
+ public List<?> translateCommand(Command command, ExecutionContext context) {
+ if (command instanceof Insert) {
+ try {
+ handleInsertSequences((Insert)command);
+ } catch (ConnectorException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ if (!(command instanceof QueryExpression)) {
+ return null;
+ }
+ QueryExpression queryCommand = (QueryExpression)command;
+ if (queryCommand.getLimit() == null) {
+ return null;
+ }
+ Limit limit = queryCommand.getLimit();
+ queryCommand.setLimit(null);
+ List<Object> parts = new ArrayList<Object>();
+ parts.add("SELECT "); //$NON-NLS-1$
+ /*
+ * if all of the columns are aliased, assume that names matter - it actually only seems to matter for
+ * the first query of a set op when there is a order by. Rather than adding logic to traverse up,
+ * we just use the projected names
+ */
+ boolean allAliased = true;
+ for (DerivedColumn selectSymbol : queryCommand.getProjectedQuery().getDerivedColumns()) {
+ if (selectSymbol.getAlias() == null) {
+ allAliased = false;
+ break;
+ }
+ }
+ if (allAliased) {
+ String[] columnNames = queryCommand.getColumnNames();
+ for (int i = 0; i < columnNames.length; i++) {
+ if (i > 0) {
+ parts.add(", "); //$NON-NLS-1$
+ }
+ parts.add(columnNames[i]);
+ }
+ } else {
+ parts.add("*"); //$NON-NLS-1$
+ }
+ if (limit.getRowOffset() > 0) {
+ parts.add(" FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM ("); //$NON-NLS-1$
+ } else {
+ parts.add(" FROM ("); //$NON-NLS-1$
+ }
+ parts.add(queryCommand);
+ if (limit.getRowOffset() > 0) {
+ parts.add(") VIEW_FOR_LIMIT WHERE ROWNUM <= "); //$NON-NLS-1$
+ parts.add(limit.getRowLimit() + limit.getRowOffset());
+ parts.add(") WHERE ROWNUM_ > "); //$NON-NLS-1$
+ parts.add(limit.getRowOffset());
+ } else {
+ parts.add(") WHERE ROWNUM <= "); //$NON-NLS-1$
+ parts.add(limit.getRowLimit());
+ }
+ return parts;
+ }
+
+ @Override
+ public boolean useAsInGroupAlias(){
+ return false;
+ }
+
+ @Override
+ public String getSetOperationString(Operation operation) {
+ if (operation == Operation.EXCEPT) {
+ return "MINUS"; //$NON-NLS-1$
+ }
+ return super.getSetOperationString(operation);
+ }
+
+ @Override
+ public String getSourceComment(ExecutionContext context, Command command) {
+ String comment = super.getSourceComment(context, command);
+
+ if (context != null) {
+ // Check for db hints
+ Object payload = context.getExecutionPayload();
+ if (payload instanceof String) {
+ String payloadString = (String)payload;
+ if (payloadString.startsWith(HINT_PREFIX)) {
+ comment += payloadString + " "; //$NON-NLS-1$
+ }
+ }
+ }
+
+ if (command instanceof Select) {
+ //
+ // This simple algorithm determines the hint which will be added to the
+ // query.
+ // Right now, we look through all functions passed in the query
+ // (returned as a collection)
+ // Then we check if any of those functions are sdo_relate
+ // If so, the ORDERED hint is added, if not, it isn't
+ Collection<Function> col = CollectorVisitor.collectObjects(Function.class, command);
+ for (Function func : col) {
+ if (func.getName().equalsIgnoreCase(RELATE)) {
+ return comment + "/*+ ORDERED */ "; //$NON-NLS-1$
+ }
+ }
+ }
+ return comment;
+ }
+
+ /**
+ * Don't fully qualify elements if table = DUAL or element = ROWNUM or special stuff is packed into name in source value.
+ *
+ * @see org.teiid.connector.visitor.util.SQLStringVisitor#skipGroupInElement(java.lang.String, java.lang.String)
+ * @since 5.0
+ */
+ @Override
+ public String replaceElementName(String group, String element) {
+
+ // Check if the element was modeled as using a Sequence
+ int useIndex = element.indexOf(SEQUENCE);
+ if (useIndex >= 0) {
+ String name = element.substring(0, useIndex);
+ if (group != null) {
+ return group + Tokens.DOT + name;
+ }
+ return name;
+ }
+
+ // Check if the group name should be discarded
+ if((group != null && DUAL.equalsIgnoreCase(group)) || element.equalsIgnoreCase(ROWNUM)) {
+ // Strip group if group or element are pseudo-columns
+ return element;
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean hasTimeType() {
+ return false;
+ }
+
+ @Override
+ public void bindValue(PreparedStatement stmt, Object param, Class<?> paramType, int i) throws SQLException {
+ if(param == null && Object.class.equals(paramType)){
+ //Oracle drive does not support JAVA_OBJECT type
+ stmt.setNull(i, Types.LONGVARBINARY);
+ return;
+ }
+ super.bindValue(stmt, param, paramType, i);
+ }
+
+ @Override
+ public void afterInitialConnectionCreation(Connection connection) {
+ String errorStr = JDBCPlugin.Util.getString("ConnectionListener.failed_to_report_oracle_connection_details"); //$NON-NLS-1$
+ ResultSet rs = null;
+ Statement stmt = null;
+ try {
+ stmt = connection.createStatement();
+ rs = stmt.executeQuery("select * from v$instance"); //$NON-NLS-1$
+
+ int columnCount = rs.getMetaData().getColumnCount();
+ while (rs.next()) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 1; i <= columnCount; i++) {
+ sb.append(rs.getMetaData().getColumnName(i)).append("=").append(rs.getString(i)).append(";"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ // log the queried information
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, sb.toString());
+ }
+
+ } catch (SQLException e) {
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, errorStr);
+ }finally {
+ try {
+ if (rs != null) {
+ rs.close();
+ }
+ if (stmt != null) {
+ stmt.close();
+ }
+ } catch (SQLException e1) {
+ LogManager.logInfo(LogConstants.CTX_CONNECTOR, errorStr);
+ }
+ }
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.HIGH;
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return OracleCapabilities.class;
+ }
+
+ public boolean supportsExplicitNullOrdering() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.Literal;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+public class OracleSpatialFunctionModifier extends FunctionModifier {
+
+ /**
+ * If either of the first two parameters are a Literal String, then we need to put the literal itself in the SQL
+ * to be passed to Oracle, without the tick marks
+ */
+ public List<?> translate(Function function) {
+ List<Expression> params = function.getParameters();
+ List<Object> objs = new ArrayList<Object>();
+ objs.add(function.getName());
+ objs.add("("); //$NON-NLS-1$
+ addParamWithConversion(objs, params.get(0));
+ objs.add(", "); //$NON-NLS-1$
+
+ addParamWithConversion(objs, params.get(1));
+ for (int i = 2; i < params.size(); i++) {
+ objs.add(", "); //$NON-NLS-1$
+ objs.add(params.get(i));
+ }
+ objs.add(")"); //$NON-NLS-1$
+ return objs;
+ }
+
+ protected void addParamWithConversion(List<Object> objs,
+ Expression expression) {
+ if ((expression instanceof Literal)
+ && (((Literal) expression).getValue() instanceof String)) {
+ objs.add(((Literal) expression).getValue());
+ } else {
+ objs.add(expression);
+ }
+ }
+
+}
\ No newline at end of file
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/SequeLinkOracleCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/SequeLinkOracleCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/SequeLinkOracleCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,37 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.oracle;
+
+
+
+/**
+ * @since 5.0
+ */
+public class SequeLinkOracleCapabilities extends OracleCapabilities {
+
+ @Override
+ public boolean supportsBulkUpdate() {
+ return false;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/LocateFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/LocateFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/LocateFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,77 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.postgresql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.connector.language.Literal;
+import org.teiid.resource.cci.TypeFacility;
+
+public class LocateFunctionModifier extends org.teiid.translator.jdbc.LocateFunctionModifier {
+
+ public LocateFunctionModifier(LanguageFactory factory) {
+ super(factory);
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ modify(function);
+ List<Object> parts = new ArrayList<Object>();
+ List<Expression> params = function.getParameters();
+ parts.add("position("); //$NON-NLS-1$
+ parts.add(params.get(0));
+ parts.add(" in "); //$NON-NLS-1$
+ boolean useSubStr = false;
+ if (params.size() == 3) {
+ useSubStr = true;
+ if (params.get(2) instanceof Literal && ((Literal)params.get(2)).getValue() instanceof Integer) {
+ Integer value = (Integer)((Literal)params.get(2)).getValue();
+ if (value <= 1) {
+ useSubStr = false;
+ }
+ }
+ }
+ if (useSubStr) {
+ parts.add(0, "("); //$NON-NLS-1$
+ parts.add(this.getLanguageFactory().createFunction("substr", params.subList(1, 3), TypeFacility.RUNTIME_TYPES.STRING)); //$NON-NLS-1$
+ parts.add(")"); //$NON-NLS-1$
+ parts.add(" + "); //$NON-NLS-1$
+ if (params.get(2) instanceof Literal && ((Literal)params.get(2)).getValue() instanceof Integer) {
+ Integer value = (Integer)((Literal)params.get(2)).getValue();
+ parts.add(value - 1);
+ } else {
+ parts.add(params.get(2));
+ parts.add(" - 1"); //$NON-NLS-1$
+ }
+ } else {
+ parts.add(params.get(1));
+ }
+ parts.add(")"); //$NON-NLS-1$
+ return parts;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,284 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.postgresql;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+
+/**
+ * @since 4.3
+ */
+public class PostgreSQLCapabilities extends JDBCCapabilities {
+
+ public static final String EIGHT_0 = "8.0"; //$NON-NLS-1$
+ public static final String EIGHT_1 = "8.1"; //$NON-NLS-1$
+ public static final String EIGHT_2 = "8.2"; //$NON-NLS-1$
+ public static final String EIGHT_3 = "8.3"; //$NON-NLS-1$
+ public static final String EIGHT_4 = "8.4"; //$NON-NLS-1$
+
+ private String version = EIGHT_0;
+
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("BITAND"); //$NON-NLS-1$
+ supportedFunctions.add("BITNOT"); //$NON-NLS-1$
+ supportedFunctions.add("BITOR"); //$NON-NLS-1$
+ supportedFunctions.add("BITXOR"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("FORMATBIGDECIMAL"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATBIGINTEGER"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATDOUBLE"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATFLOAT"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATINTEGER"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATLONG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("ROUND"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+
+ // These are executed within the server and never pushed down
+// supportedFunctions.add("CURDATE"); //$NON-NLS-1$
+// supportedFunctions.add("CURTIME"); //$NON-NLS-1$
+// supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+// supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ // These should not be pushed down since the grammar for string conversion is different
+// supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+// supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ if (this.version.compareTo(EIGHT_2) >= 0) {
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ }
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+
+ // Additional functions
+// // Math
+// supportedFunctions.add("%"); //$NON-NLS-1$
+// supportedFunctions.add("^"); //$NON-NLS-1$
+// supportedFunctions.add("|/"); //$NON-NLS-1$
+// supportedFunctions.add("||/"); //$NON-NLS-1$
+// supportedFunctions.add("!"); //$NON-NLS-1$
+// supportedFunctions.add("!!"); //$NON-NLS-1$
+// supportedFunctions.add("@"); //$NON-NLS-1$
+// // Bit manipulation
+// supportedFunctions.add("&"); //$NON-NLS-1$
+// supportedFunctions.add("|"); //$NON-NLS-1$
+// supportedFunctions.add("#"); //$NON-NLS-1$
+// supportedFunctions.add("~"); //$NON-NLS-1$
+// supportedFunctions.add("<<"); //$NON-NLS-1$
+// supportedFunctions.add(">>"); //$NON-NLS-1$
+//
+// supportedFunctions.add("CBRT"); //$NON-NLS-1$
+// supportedFunctions.add("CEIL"); //$NON-NLS-1$
+// supportedFunctions.add("LN"); //$NON-NLS-1$
+// supportedFunctions.add("MOD"); //$NON-NLS-1$
+// supportedFunctions.add("RANDOM"); //$NON-NLS-1$
+// supportedFunctions.add("SETSEED"); //$NON-NLS-1$
+// supportedFunctions.add("TRUNC"); //$NON-NLS-1$
+// supportedFunctions.add("WIDTH_BUCKET"); //$NON-NLS-1$
+//
+// // String
+// supportedFunctions.add("BIT_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("BTRIM"); //$NON-NLS-1$
+// supportedFunctions.add("CHAR_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("CHARACTER_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("DECODE"); //$NON-NLS-1$
+// supportedFunctions.add("ENCODE"); //$NON-NLS-1$
+// supportedFunctions.add("MD5"); //$NON-NLS-1$
+// supportedFunctions.add("OCTET_LENGTH"); //$NON-NLS-1$
+// supportedFunctions.add("PG_CLIENT_ENCODING"); //$NON-NLS-1$
+// supportedFunctions.add("QUOTE_IDENT"); //$NON-NLS-1$
+// supportedFunctions.add("QUOTE_LITERAL"); //$NON-NLS-1$
+// supportedFunctions.add("SPLIT_PART"); //$NON-NLS-1$
+// supportedFunctions.add("STRPOS"); //$NON-NLS-1$
+// supportedFunctions.add("SUBSTR"); //$NON-NLS-1$
+// supportedFunctions.add("TO_ASCII"); //$NON-NLS-1$
+// supportedFunctions.add("TO_HEX"); //$NON-NLS-1$
+// supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+//
+// // Bit operations
+// supportedFunctions.add("GET_BIT"); //$NON-NLS-1$
+// supportedFunctions.add("GET_BYTE"); //$NON-NLS-1$
+// supportedFunctions.add("SET_BIT"); //$NON-NLS-1$
+// supportedFunctions.add("SET_BYTE"); //$NON-NLS-1$
+//
+// // Formatting
+// supportedFunctions.add("TO_CHAR"); //$NON-NLS-1$
+// supportedFunctions.add("TO_DATE"); //$NON-NLS-1$
+// supportedFunctions.add("TO_TIMESTAMP"); //$NON-NLS-1$
+// supportedFunctions.add("TO_NUMBER"); //$NON-NLS-1$
+//
+// // Date / Time
+// supportedFunctions.add("AGE"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_DATE"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("CURRENT_TIME"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("CURRENT_TIMESTAMP"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("DATE_PART"); //$NON-NLS-1$
+// supportedFunctions.add("DATE_TRUNC"); //$NON-NLS-1$
+// supportedFunctions.add("ISFINITE"); //$NON-NLS-1$
+// supportedFunctions.add("JUSTIFY_HOURS"); //$NON-NLS-1$
+// supportedFunctions.add("JUSTIFY_DAYS"); //$NON-NLS-1$
+// supportedFunctions.add("LOCALTIME"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("LOCALTIMESTAMP"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("TIMEOFDAY"); //$NON-NLS-1$
+//
+// // Conditional
+ supportedFunctions.add("COALESCE"); //$NON-NLS-1$
+// supportedFunctions.add("NULLIF"); //$NON-NLS-1$
+// supportedFunctions.add("GREATEST"); //$NON-NLS-1$
+// supportedFunctions.add("LEAST"); //$NON-NLS-1$
+//
+// // Network Addresses
+//// supportedFunctions.add("BROADCAST"); //$NON-NLS-1$
+//// supportedFunctions.add("HOST"); //$NON-NLS-1$
+//// supportedFunctions.add("MASKLEN"); //$NON-NLS-1$
+//// supportedFunctions.add("SET_MASKLEN"); //$NON-NLS-1$
+//// supportedFunctions.add("NETMASK"); //$NON-NLS-1$
+//// supportedFunctions.add("HOSTMASK"); //$NON-NLS-1$
+//// supportedFunctions.add("NETWORK"); //$NON-NLS-1$
+//// supportedFunctions.add("TEXT"); //$NON-NLS-1$
+//// supportedFunctions.add("ABBREV"); //$NON-NLS-1$
+//// supportedFunctions.add("FAMILY"); //$NON-NLS-1$
+//// supportedFunctions.add("TRUNC"); //$NON-NLS-1$
+//
+// // Set generator
+// supportedFunctions.add("GENERATE_SERIES"); //$NON-NLS-1$
+//
+// // Information
+// supportedFunctions.add("CURRENT_DATABASE"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_SCHEMA"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_SCHEMAS"); //$NON-NLS-1$
+// supportedFunctions.add("CURRENT_USER"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("INET_CLIENT_ADDR"); //$NON-NLS-1$
+// supportedFunctions.add("INET_CLIENT_PORT"); //$NON-NLS-1$
+// supportedFunctions.add("INET_SERVER_ADDR"); //$NON-NLS-1$
+// supportedFunctions.add("INET_SERVER_PORT"); //$NON-NLS-1$
+// supportedFunctions.add("SESSION_USER"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("USER"); //$NON-NLS-1$ // no ()
+// supportedFunctions.add("VERSION"); //$NON-NLS-1$
+//
+ return supportedFunctions;
+ }
+
+ /**
+ * This is true only after Postgre version 7.1
+ * However, since version 7 was released in 2000 we'll assume a post 7 instance.
+ *
+ * @see org.teiid.resource.adapter.jdbc.JDBCCapabilities#supportsInlineViews()
+ */
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsExcept()
+ */
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#supportsIntersect()
+ */
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ public void setDatabaseVersion(String version) {
+ this.version = version;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.translator.jdbc.postgresql;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.AggregateFunction;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.EscapeSyntaxModifier;
+import org.teiid.translator.jdbc.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.oracle.LeftOrRightFunctionModifier;
+import org.teiid.translator.jdbc.oracle.MonthOrDayNameFunctionModifier;
+
+
+
+/**
+ * Translator class for PostgreSQL. Updated to expect a 8.0+ jdbc client
+ * @since 4.3
+ */
+public class PostgreSQLTranslator extends Translator {
+
+ private String version = PostgreSQLCapabilities.EIGHT_0;
+
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ //TODO: all of the functions (except for convert) can be handled through just the escape syntax
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("ln")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LOG10, new AliasModifier("log")); //$NON-NLS-1$
+
+ registerFunctionModifier(SourceSystemFunctions.BITAND, new AliasModifier("&")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITNOT, new AliasModifier("~")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITOR, new AliasModifier("|")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.BITXOR, new AliasModifier("#")); //$NON-NLS-1$
+
+ registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new AliasModifier("||")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lower")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LEFT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.RIGHT, new LeftOrRightFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("upper")); //$NON-NLS-1$
+
+ registerFunctionModifier(SourceSystemFunctions.DAYNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Day"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new MonthOrDayNameFunctionModifier(getLanguageFactory(), "Month"));//$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.QUARTER, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.WEEK, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
+ registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("coalesce")); //$NON-NLS-1$
+
+ registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier("%", getLanguageFactory(), Arrays.asList(TypeFacility.RUNTIME_TYPES.BIG_INTEGER, TypeFacility.RUNTIME_TYPES.BIG_DECIMAL))); //$NON-NLS-1$
+
+ //specific to 8.2 client or later
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new EscapeSyntaxModifier());
+
+ //add in type conversion
+ ConvertModifier convertModifier = new ConvertModifier();
+ convertModifier.addTypeMapping("boolean", FunctionModifier.BOOLEAN); //$NON-NLS-1$
+ convertModifier.addTypeMapping("smallint", FunctionModifier.BYTE, FunctionModifier.SHORT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("integer", FunctionModifier.INTEGER); //$NON-NLS-1$
+ convertModifier.addTypeMapping("bigint", FunctionModifier.LONG); //$NON-NLS-1$
+ convertModifier.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("float8", FunctionModifier.DOUBLE); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(38)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+ convertModifier.addTypeMapping("decimal", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
+ convertModifier.addTypeMapping("date", FunctionModifier.DATE); //$NON-NLS-1$
+ convertModifier.addTypeMapping("time", FunctionModifier.TIME); //$NON-NLS-1$
+ convertModifier.addTypeMapping("timestamp", FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList(function.getParameters().get(0), " + TIMESTAMP '1970-01-01'"); //$NON-NLS-1$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return Arrays.asList("cast(date_trunc('second', ", function.getParameters().get(0), ") AS time)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", "YYYY-MM-DD")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", "HH24:MI:SS")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", "YYYY-MM-DD HH24:MI:SS.UF")); //$NON-NLS-1$ //$NON-NLS-2$
+ convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ Expression stringValue = function.getParameters().get(0);
+ return Arrays.asList("CASE WHEN ", stringValue, " THEN 'true' WHEN not(", stringValue, ") THEN 'false' END"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ });
+ convertModifier.addSourceConversion(new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ ((Literal)function.getParameters().get(1)).setValue("integer"); //$NON-NLS-1$
+ return null;
+ }
+ }, FunctionModifier.BOOLEAN);
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+ }
+
+ @Override
+ public String translateLiteralBoolean(Boolean booleanValue) {
+ if(booleanValue.booleanValue()) {
+ return "TRUE"; //$NON-NLS-1$
+ }
+ return "FALSE"; //$NON-NLS-1$
+ }
+
+ @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 int getTimestampNanoPrecision() {
+ return 6;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<?> translateLimit(Limit limit, ExecutionContext context) {
+ if (limit.getRowOffset() > 0) {
+ return Arrays.asList("LIMIT ", limit.getRowLimit(), " OFFSET ", limit.getRowOffset()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ return null;
+ }
+
+ /**
+ * Postgres doesn't provide min/max(boolean), so this conversion writes a min(BooleanValue) as
+ * bool_and(BooleanValue)
+ * @see org.teiid.connector.visitor.framework.LanguageObjectVisitor#visit(org.teiid.connector.language.AggregateFunction)
+ * @since 4.3
+ */
+ @Override
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ if (obj instanceof AggregateFunction) {
+ AggregateFunction agg = (AggregateFunction)obj;
+ if (agg.getExpression() != null && TypeFacility.RUNTIME_TYPES.BOOLEAN.equals(agg.getExpression().getType())) {
+ if (agg.getName().equalsIgnoreCase(SQLReservedWords.MIN)) {
+ agg.setName("bool_and"); //$NON-NLS-1$
+ } else if (agg.getName().equalsIgnoreCase(SQLReservedWords.MAX)) {
+ agg.setName("bool_or"); //$NON-NLS-1$
+ }
+ }
+ }
+ return super.translate(obj, context);
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.HIGH;
+ }
+
+ @Override
+ public boolean supportsExplicitNullOrdering() {
+ return version.compareTo(PostgreSQLCapabilities.EIGHT_4) >= 0;
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return PostgreSQLCapabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.translator.jdbc.sqlserver;
+
+import java.util.*;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+/**
+ */
+public class SQLServerCapabilities extends JDBCCapabilities {
+
+ public SQLServerCapabilities() {
+ }
+
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ //supportedFunctons.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ //supportedFunctons.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ //supportedFunctons.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ //supportedFunctions.add("RAND"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ //supportedFunctons.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SPACE"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ //supportedFunctons.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ //supportedFunctons.add("CURDATE"); //$NON-NLS-1$
+ //supportedFunctons.add("CURTIME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ //supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ public boolean supportsExcept() {
+ return true;
+ };
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,71 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+/*
+ */
+package org.teiid.translator.jdbc.sqlserver;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageObject;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.sybase.SybaseSQLTranslator;
+
+/**
+ * Updated to assume the use of the DataDirect, 2005 driver, or later.
+ */
+public class SQLServerSQLTranslator extends SybaseSQLTranslator {
+
+ //TEIID-31 remove mod modifier for SQL Server 2008
+
+ @Override
+ protected List<Object> convertDateToString(Function function) {
+ return Arrays.asList("replace(convert(varchar, ", function.getParameters().get(0), ", 102), '.', '-')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ protected List<?> convertTimestampToString(Function function) {
+ return Arrays.asList("convert(varchar, ", function.getParameters().get(0), ", 21)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return SQLServerCapabilities.class;
+ }
+
+ @Override
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ if (obj instanceof ColumnReference) {
+ ColumnReference elem = (ColumnReference)obj;
+ if (TypeFacility.RUNTIME_TYPES.STRING.equals(elem.getType()) && elem.getMetadataObject() != null && "uniqueidentifier".equalsIgnoreCase(elem.getMetadataObject().getNativeType())) { //$NON-NLS-1$
+ return Arrays.asList("cast(", elem, " as char(36))"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ return super.translate(obj, context);
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SubstringFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SubstringFunctionModifier.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SubstringFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,57 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.sybase;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.FunctionModifier;
+
+
+/**
+ * Common logic for Substring modifiers requiring 3 parameters
+ */
+public class SubstringFunctionModifier extends FunctionModifier {
+
+ private LanguageFactory languageFactory;
+
+ public SubstringFunctionModifier(LanguageFactory languageFactory) {
+ this.languageFactory = languageFactory;
+ }
+
+ @Override
+ public List<?> translate(Function function) {
+ List<Expression> args = function.getParameters();
+
+ if(args.size() == 2) {
+ args.add(languageFactory.createFunction(SourceSystemFunctions.LENGTH, Arrays.asList(args.get(0)), TypeFacility.RUNTIME_TYPES.INTEGER));
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.translator.jdbc.sybase;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+/**
+ */
+public class SybaseCapabilities extends JDBCCapabilities {
+
+ public SybaseCapabilities() {
+ }
+
+ @Override
+ public int getMaxInCriteriaSize() {
+ return 250;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ //supportedFunctions.add("RAND"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SPACE"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ //supportedFunctons.add("CURDATE"); //$NON-NLS-1$
+ //supportedFunctons.add("CURTIME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ //supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add("QUARTER"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+ //supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.adapter.BasicConnectorCapabilities#getMaxFromGroups()
+ */
+ public int getMaxFromGroups() {
+ return 50;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseSQLTranslator.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseSQLTranslator.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sybase/SybaseSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,214 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.sybase;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.OrderBy;
+import org.teiid.connector.language.SetQuery;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.EscapeSyntaxModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.Translator;
+
+
+/**
+ */
+public class SybaseSQLTranslator extends Translator {
+
+ /*
+ * @see com.metamatrix.connector.jdbc.extension.SQLTranslator#initialize(com.metamatrix.data.api.ConnectorEnvironment, com.metamatrix.data.metadata.runtime.RuntimeMetadata)
+ */
+ public void initialize(JDBCExecutionFactory env) throws ConnectorException {
+ super.initialize(env);
+ registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier("%", getLanguageFactory())); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.CONCAT, new AliasModifier("+")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("lower")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("isnull")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("upper")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.REPEAT, new AliasModifier("replicate")); //$NON-NLS-1$
+ registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new SubstringFunctionModifier(getLanguageFactory()));
+ registerFunctionModifier(SourceSystemFunctions.DAYNAME, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MONTHNAME, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.HOUR, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.MINUTE, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.QUARTER, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.SECOND, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.WEEK, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPADD, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.TIMESTAMPDIFF, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.LENGTH, new EscapeSyntaxModifier());
+ registerFunctionModifier(SourceSystemFunctions.ATAN2, new EscapeSyntaxModifier());
+
+ //add in type conversion
+ ConvertModifier convertModifier = new ConvertModifier();
+ //boolean isn't treated as bit, since it doesn't support null
+ //byte is treated as smallint, since tinyint is unsigned
+ convertModifier.addTypeMapping("smallint", FunctionModifier.BYTE, FunctionModifier.SHORT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("int", FunctionModifier.INTEGER); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(19,0)", FunctionModifier.LONG); //$NON-NLS-1$
+ convertModifier.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+ convertModifier.addTypeMapping("double precision", FunctionModifier.DOUBLE); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(38, 0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+ convertModifier.addTypeMapping("numeric(38, 19)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+ convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+ convertModifier.addTypeMapping("varchar(40)", FunctionModifier.STRING); //$NON-NLS-1$
+ convertModifier.addTypeMapping("datetime", FunctionModifier.DATE, FunctionModifier.TIME, FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ List<Object> result = new ArrayList<Object>();
+ result.add("cast("); //$NON-NLS-1$
+ result.add("'1970-01-01 ' + "); //$NON-NLS-1$
+ result.addAll(convertTimeToString(function));
+ result.add(" AS datetime)"); //$NON-NLS-1$
+ return result;
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ List<Object> result = new ArrayList<Object>();
+ result.add("cast("); //$NON-NLS-1$
+ result.addAll(convertDateToString(function));
+ result.add(" AS datetime)"); //$NON-NLS-1$
+ return result;
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return convertTimeToString(function);
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return convertDateToString(function);
+ }
+ });
+ convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new FunctionModifier() {
+ @Override
+ public List<?> translate(Function function) {
+ return convertTimestampToString(function);
+ }
+ });
+ convertModifier.addNumericBooleanConversions();
+ registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+ }
+
+ private List<Object> convertTimeToString(Function function) {
+ return Arrays.asList("convert(varchar, ", function.getParameters().get(0), ", 8)"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ protected List<Object> convertDateToString(Function function) {
+ return Arrays.asList("stuff(stuff(convert(varchar, ", function.getParameters().get(0), ", 102), 5, 1, '-'), 8, 1, '-')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Written to only support version 15
+ * @param function
+ * @return
+ */
+ protected List<?> convertTimestampToString(Function function) {
+ return Arrays.asList("stuff(convert(varchar, ", function.getParameters().get(0), ", 123), 11, 1, ' ')"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ @Override
+ public boolean useAsInGroupAlias() {
+ return false;
+ }
+
+ @Override
+ public boolean hasTimeType() {
+ return false;
+ }
+
+ @Override
+ public int getTimestampNanoPrecision() {
+ return 3;
+ }
+
+ /**
+ * SetQueries don't have a concept of TOP, an inline view is needed.
+ */
+ @Override
+ public List<?> translateCommand(Command command, ExecutionContext context) {
+ if (!(command instanceof SetQuery)) {
+ return null;
+ }
+ SetQuery queryCommand = (SetQuery)command;
+ if (queryCommand.getLimit() == null) {
+ return null;
+ }
+ Limit limit = queryCommand.getLimit();
+ OrderBy orderBy = queryCommand.getOrderBy();
+ queryCommand.setLimit(null);
+ queryCommand.setOrderBy(null);
+ List<Object> parts = new ArrayList<Object>(6);
+ parts.add("SELECT "); //$NON-NLS-1$
+ parts.addAll(translateLimit(limit, context));
+ parts.add(" * FROM ("); //$NON-NLS-1$
+ parts.add(queryCommand);
+ parts.add(") AS X"); //$NON-NLS-1$
+ if (orderBy != null) {
+ parts.add(" "); //$NON-NLS-1$
+ parts.add(orderBy);
+ }
+ return parts;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<?> translateLimit(Limit limit, ExecutionContext context) {
+ return Arrays.asList("TOP ", limit.getRowLimit()); //$NON-NLS-1$
+ }
+
+ @Override
+ public boolean useSelectLimit() {
+ return true;
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return SybaseCapabilities.class;
+ }
+
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,167 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.teiid;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+/**
+ * @since 4.3
+ */
+public class TeiidCapabilities extends JDBCCapabilities {
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#getSupportedFunctions()
+ * @since 4.3
+ */
+ public List<String> getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("CEILING"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("COT"); //$NON-NLS-1$
+ supportedFunctions.add("DEGREES"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+ supportedFunctions.add("FLOOR"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATBIGDECIMAL"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATBIGINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATDOUBLE"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATFLOAT"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATLONG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG"); //$NON-NLS-1$
+ supportedFunctions.add("LOG10"); //$NON-NLS-1$
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEBIGDECIMAL"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEBIGINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEDOUBLE"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEFLOAT"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("PARSELONG"); //$NON-NLS-1$
+ supportedFunctions.add("PI"); //$NON-NLS-1$
+ supportedFunctions.add("POWER"); //$NON-NLS-1$
+ supportedFunctions.add("RADIANS"); //$NON-NLS-1$
+ supportedFunctions.add("RAND"); //$NON-NLS-1$
+ supportedFunctions.add("ROUND"); //$NON-NLS-1$
+ supportedFunctions.add("SIGN"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("ASCII"); //$NON-NLS-1$
+ supportedFunctions.add("CHAR"); //$NON-NLS-1$
+ supportedFunctions.add("CHR"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT"); //$NON-NLS-1$
+ supportedFunctions.add("CONCAT2"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+ supportedFunctions.add("INITCAP"); //$NON-NLS-1$
+ supportedFunctions.add("INSERT"); //$NON-NLS-1$
+ supportedFunctions.add("LCASE"); //$NON-NLS-1$
+ supportedFunctions.add("LENGTH"); //$NON-NLS-1$
+ supportedFunctions.add("LEFT"); //$NON-NLS-1$
+ supportedFunctions.add("LOCATE"); //$NON-NLS-1$
+ supportedFunctions.add("LPAD"); //$NON-NLS-1$
+ supportedFunctions.add("LTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("REPEAT"); //$NON-NLS-1$
+ supportedFunctions.add("REPLACE"); //$NON-NLS-1$
+ supportedFunctions.add("RPAD"); //$NON-NLS-1$
+ supportedFunctions.add("RIGHT"); //$NON-NLS-1$
+ supportedFunctions.add("RTRIM"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+ supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+ supportedFunctions.add("UCASE"); //$NON-NLS-1$
+ supportedFunctions.add("CURDATE"); //$NON-NLS-1$
+ supportedFunctions.add("CURTIME"); //$NON-NLS-1$
+ supportedFunctions.add("NOW"); //$NON-NLS-1$
+ supportedFunctions.add("DAYNAME"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFMONTH"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFWEEK"); //$NON-NLS-1$
+ supportedFunctions.add("DAYOFYEAR"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATDATE"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATTIME"); //$NON-NLS-1$
+ supportedFunctions.add("FORMATTIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("MONTHNAME"); //$NON-NLS-1$
+ supportedFunctions.add("PARSEDATE"); //$NON-NLS-1$
+ supportedFunctions.add("PARSETIME"); //$NON-NLS-1$
+ supportedFunctions.add("PARSETIMESTAMP"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPADD"); //$NON-NLS-1$
+ supportedFunctions.add("TIMESTAMPDIFF"); //$NON-NLS-1$
+ supportedFunctions.add("WEEK"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("MODIFYTIMEZONE"); //$NON-NLS-1$
+ supportedFunctions.add("DECODESTRING"); //$NON-NLS-1$
+ supportedFunctions.add("DECODEINTEGER"); //$NON-NLS-1$
+ supportedFunctions.add("IFNULL"); //$NON-NLS-1$
+ supportedFunctions.add("NVL"); //$NON-NLS-1$
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ supportedFunctions.add("CONVERT"); //$NON-NLS-1$
+ supportedFunctions.add("USER"); //$NON-NLS-1$
+ supportedFunctions.add("FROM_UNIXTIME"); //$NON-NLS-1$
+ supportedFunctions.add("NULLIF"); //$NON-NLS-1$
+ supportedFunctions.add("COALESCE"); //$NON-NLS-1$
+ return supportedFunctions;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.ConnectorCapabilities#supportsFunctionsInGroupBy()
+ * @since 5.0
+ */
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataCapabilities.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,87 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.teradata;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.jdbc.JDBCCapabilities;
+
+
+
+/**
+ * for Teradata database Release V2R5.1
+ */
+public class TeradataCapabilities extends JDBCCapabilities {
+
+ public TeradataCapabilities() {
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsFullOuterJoins()
+ */
+ public boolean supportsFullOuterJoins() {
+ return false;
+ }
+
+ /**
+ * @see org.teiid.resource.cci.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List getSupportedFunctions() {
+ List supportedFunctions = new ArrayList();
+ supportedFunctions.addAll(super.getSupportedFunctions());
+ supportedFunctions.add("ABS"); //$NON-NLS-1$
+ supportedFunctions.add("ACOS"); //$NON-NLS-1$
+ supportedFunctions.add("ASIN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN"); //$NON-NLS-1$
+ supportedFunctions.add("ATAN2"); //$NON-NLS-1$
+ supportedFunctions.add("COS"); //$NON-NLS-1$
+ supportedFunctions.add("EXP"); //$NON-NLS-1$
+// supportedFunctions.add("LOG"); //$NON-NLS-1$ // "LN"
+// supportedFunctions.add("LOG10"); //$NON-NLS-1$ // "LOG"
+ supportedFunctions.add("MOD"); //$NON-NLS-1$
+ supportedFunctions.add("SIN"); //$NON-NLS-1$
+ supportedFunctions.add("SQRT"); //$NON-NLS-1$
+ supportedFunctions.add("TAN"); //$NON-NLS-1$
+ supportedFunctions.add("||"); //$NON-NLS-1$
+// supportedFunctions.add("CONCAT"); //$NON-NLS-1$ // "||"
+// supportedFunctions.add("LCASE"); //$NON-NLS-1$ // "LOWER"
+// supportedFunctions.add("LOCATE"); //$NON-NLS-1$ //"POSITION", "INDEX" ?
+ supportedFunctions.add("LOWER"); //$NON-NLS-1$
+ supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+// supportedFunctions.add("UCASE"); //$NON-NLS-1$ // "UPPER"
+ supportedFunctions.add("UPPER"); //$NON-NLS-1$
+ supportedFunctions.add("HOUR"); //$NON-NLS-1$
+ supportedFunctions.add("MONTH"); //$NON-NLS-1$
+ supportedFunctions.add("YEAR"); //$NON-NLS-1$
+ supportedFunctions.add("DAY"); //$NON-NLS-1$
+ supportedFunctions.add("MINUTE"); //$NON-NLS-1$
+ supportedFunctions.add("SECOND"); //$NON-NLS-1$
+
+ supportedFunctions.add("CAST"); //$NON-NLS-1$
+ //supportedFunctions.add("CONVERT"); //$NON-NLS-1$ "CAST"
+
+ return supportedFunctions;
+ }
+
+}
Deleted: trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-jdbc/src/main/rar/META-INF/ra.xml 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,150 +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 JDBC 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.connector.basic.BasicResourceAdapter</resourceadapter-class>
-
- <outbound-resourceadapter>
- <connection-definition>
- <managedconnectionfactory-class>org.teiid.connector.jdbc.JDBCManagedConnectionFactory</managedconnectionfactory-class>
-
- <config-property>
- <description>{$display:"Connector Class",$advanced:"true"}</description>
- <config-property-name>ConnectorClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>org.teiid.connector.jdbc.JDBCConnector</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Connector Capabilities",$description:"The class to use to provide the Connector Capabilities",$advanced:"true"}</description>
- <config-property-name>CapabilitiesClass</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </config-property>
-
- <config-property>
- <description>{$display:"Is Immutable",$description:"Is Immutable, True if the source never changes.",$advanced:"true"}</description>
- <config-property-name>Immutable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Is XA Capable",$description:"True, if this connector supports XA Transactions",$advanced:"true"}</description>
- <config-property-name>XaCapable</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Exception on Exceeding Max Rows",$description:"Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",$advanced:"true"}</description>
- <config-property-name>ExceptionOnMaxRows</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>true</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Maximum Result Rows",$description:"Maximum Result Rows allowed",$advanced:"true"}</description>
- <config-property-name>MaxResultRows</config-property-name>
- <config-property-type>java.lang.Integer</config-property-type>
- <config-property-value>-1</config-property-value>
- </config-property>
-
- <!-- JDBC Specific properties -->
-
- <config-property>
- <description>{$display:"Use prepared statements and bind variables",$advanced:"true"}</description>
- <config-property-name>UseBindVariables</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"fetch size used from the connector to its underlying source.",$advanced:"true"}</description>
- <config-property-name>FetchSize</config-property-name>
- <config-property-type>java.lang.Integer</config-property-type>
- <config-property-value>1024</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Database time zone",$description:"Time zone of the database, if different than Integration Server",$advanced:"true"}</description>
- <config-property-name>DatabaseTimeZone</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </config-property>
-
- <config-property>
- <description>{$display:"Extension SQL Translation Class",$required:"true",$advanced:"true",$allowed:["org.teiid.connector.jdbc.translator.Translator","org.teiid.connector.jdbc.oracle.OracleSQLTranslator","org.teiid.connector.jdbc.db2.DB2SQLTranslator", "org.teiid.connector.jdbc.sqlserver.SqlServerSQLTranslator", "org.teiid.connector.jdbc.mysql.MySQLTranslator","org.teiid.connector.jdbc.mysql.MySQL5Translator", "org.teiid.connector.jdbc.postgresql.PostgreSQLTranslator", "org.teiid.connector.jdbc.derby.DerbySQLTranslator", "org.teiid.connector.jdbc.access.AccessSQLTranslator","org.teiid.connector.jdbc.h2.H2Translator","org.teiid.connector.jdbc.h2.H2Translator"]}</description>
- <config-property-name>ExtensionTranslationClassName</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- <config-property-value>org.teiid.connector.jdbc.translator.Translator</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Source Connection JNDI Name",$required:"true"}</description>
- <description>JNDI Name of the physical resource.</description>
- <config-property-name>SourceJNDIName</config-property-name>
- <config-property-type>java.lang.String</config-property-type>
- </config-property>
-
- <config-property>
- <description>{$display:"Trim string flag",$description:"Right Trim fixed character types returned as Strings - note that the native type must be char or nchar and the source must support the rtrim function.",$advanced:"true"}</description>
- <config-property-name>TrimStrings</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <config-property>
- <description>{$display:"Use informational comments in Source Queries",$description:"This will embed /*comment*/ style comment with session/request id in source SQL query for informational purposes",$advanced:"true"}</description>
- <config-property-name>UseCommentsInSourceQuery</config-property-name>
- <config-property-type>java.lang.Boolean</config-property-type>
- <config-property-value>false</config-property-value>
- </config-property>
-
- <connectionfactory-interface>org.teiid.connector.api.Connector</connectionfactory-interface>
- <connectionfactory-impl-class>org.teiid.connector.basic.WrappedConnector</connectionfactory-impl-class>
- <connection-interface>org.teiid.connector.api.Connection</connection-interface>
- <connection-impl-class>org.teiid.connector.basic.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: trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml (from rev 2084, trunk/connectors/connector-jdbc/src/main/rar/META-INF/ra.xml)
===================================================================
--- trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/rar/META-INF/ra.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,151 @@
+<?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 JDBC 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.connector.basic.BasicResourceAdapter</resourceadapter-class>
+
+ <outbound-resourceadapter>
+ <connection-definition>
+ <managedconnectionfactory-class>org.teiid.connector.jdbc.JDBCManagedConnectionFactory</managedconnectionfactory-class>
+
+ <config-property>
+ <!-- This property is for the auto creation of the Connector from DS -->
+ <description>{$display:"Connection Factory Class",$required:"true"}</description>
+ <config-property-name>ConnectionFactoryClass</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>org.teiid.connector.jdbc.JDBCManagedConnectionFactory</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Connector Class"}</description>
+ <config-property-name>ConnectorClass</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>org.teiid.connector.jdbc.JDBCConnector</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Connector Capabilities",$description:"The class to use to provide the Connector Capabilities"}</description>
+ <config-property-name>CapabilitiesClass</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Is Immutable",$description:"Is Immutable, True if the source never changes.",$advanced:"true"}</description>
+ <config-property-name>Immutable</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>false</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Is XA Capable",$description:"True, if this connector supports XA Transactions"}</description>
+ <config-property-name>XaCapable</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>false</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Exception on Exceeding Max Rows",$description:"Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned",$advanced:"true"}</description>
+ <config-property-name>ExceptionOnMaxRows</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>true</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Maximum Result Rows",$description:"Maximum Result Rows allowed",$advanced:"true"}</description>
+ <config-property-name>MaxResultRows</config-property-name>
+ <config-property-type>java.lang.Integer</config-property-type>
+ <config-property-value>-1</config-property-value>
+ </config-property>
+
+ <!-- JDBC Specific properties -->
+
+ <config-property>
+ <description>{$display:"Use prepared statements and bind variables",$advanced:"true"}</description>
+ <config-property-name>UseBindVariables</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>false</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"fetch size used from the connector to its underlying source.",$advanced:"true"}</description>
+ <config-property-name>FetchSize</config-property-name>
+ <config-property-type>java.lang.Integer</config-property-type>
+ <config-property-value>1024</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Database time zone",$description:"Time zone of the database, if different than Integration Server",$advanced:"true"}</description>
+ <config-property-name>DatabaseTimeZone</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Extension SQL Translation Class",$required:"true",$allowed:["org.teiid.connector.jdbc.translator.Translator","org.teiid.connector.jdbc.oracle.OracleSQLTranslator","org.teiid.connector.jdbc.db2.DB2SQLTranslator", "org.teiid.connector.jdbc.sqlserver.SqlServerSQLTranslator", "org.teiid.connector.jdbc.mysql.MySQLTranslator","org.teiid.connector.jdbc.mysql.MySQL5Translator", "org.teiid.connector.jdbc.postgresql.PostgreSQLTranslator", "org.teiid.connector.jdbc.derby.DerbySQLTranslator", "org.teiid.connector.jdbc.access.AccessSQLTranslator","org.teiid.connector.jdbc.h2.H2Translator","org.teiid.connector.jdbc.h2.H2Translator"]}</description>
+ <config-property-name>ExtensionTranslationClassName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>org.teiid.connector.jdbc.translator.Translator</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Trim string flag",$description:"Right Trim fixed character types returned as Strings - note that the native type must be char or nchar and the source must support the rtrim function.",$advanced:"true"}</description>
+ <config-property-name>TrimStrings</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>false</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Use informational comments in Source Queries",$description:"This will embed /*comment*/ style comment with session/request id in source SQL query for informational purposes",$advanced:"true"}</description>
+ <config-property-name>UseCommentsInSourceQuery</config-property-name>
+ <config-property-type>java.lang.Boolean</config-property-type>
+ <config-property-value>false</config-property-value>
+ </config-property>
+
+ <connectionfactory-interface>org.teiid.connector.api.Connector</connectionfactory-interface>
+ <connectionfactory-impl-class>org.teiid.connector.basic.WrappedConnector</connectionfactory-impl-class>
+ <connection-interface>org.teiid.connector.api.Connection</connection-interface>
+ <connection-impl-class>org.teiid.connector.basic.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>
Added: trunk/connectors/translator-jdbc/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-jdbc/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.jdbc.JDBCExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/translator-jdbc/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/jdbc/i18n.properties
===================================================================
--- trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/jdbc/i18n.properties (rev 0)
+++ trunk/connectors/translator-jdbc/src/main/resources/org/teiid/translator/jdbc/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,76 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+JDBCSourceConnectionFactory.Missing_JDBC_jndi_1=Missing JDBC Source JNDI Name
+JDBCSourceConnectionFactory.Missing_JDBC_protocol_name_2=Missing JDBC protocol name
+JDBCSourceConnectionFactory.Missing_JDBC_database_name_3=Missing JDBC database name
+JDBCSourceConnectionFactory.Unable_to_load_the_JDBC_driver_class_6=Unable to load the JDBC driver class "{0}".
+JDBCSourceConnectionFactory.Driver__7=Driver "{0}" can not load "{1}".
+JDBCUpdateExecution.batch_prep_stmt=Executing batched prepared statements is not supported: {0}
+JDBCUpdateExecution.batch_stored_proc=Executing batched stored procedures is not supported: {0}
+JDBCSourceConnectionFactory.til=Unsupported transaction isolation level "{0}".
+JDBCSourceConnectionFactory.MissingProp=Missing required property: {0}
+JDBCSourceXAConnecton.Connection_still_leased=Connection is still leased to connector worker. However, transaction ended, so terminating the lease.
+JDBCSourceConnectionFactory.Unable_to_find_jndi_ds=Failed to locate data source named {0} through JNDI lookup.
+
+JDBCTranslator.Unexpected_exception_translating_results___8=Unexpected exception while translating results: {0}
+JDBCTranslator.Unknown_error_translating_results___9=Unknown error translating results: {0}
+
+JDBCTranslator._Unable_to_get_Blob_and_set_parameter._{0}=\ Unable to get Blob and set parameter. {0}
+JDBCTranslator._Unable_to_get_Clob_and_set_parameter._{0}=\ Unable to get Clob and set parameter. {0}
+JDBCTranslator.Unable_to_set_appropriate_output_parameter_type_of_class({0})=Unable to set the appropriate output parameter type of class({0}) to JDBC Driver
+
+JDBCConnector.No_license_found_for_{0}=No license found for {0}
+JDBCConnector.JDBCConnector_initialized._1=JDBCConnector initialized.
+JDBCConnector.JDBCConnector_stopped._3=JDBCConnector stopped.
+JDBCConnector.JDBCConnector_started._4=JDBCConnector started.
+JDBCConnector.JDBCConnector_is_not_started._5=JDBCConnector is not started.
+JDBCConnector.unsupported_identity_type=Unsupported identity type.
+JDBCConnector.non_xa_connection_source=Connection source does not support XA.
+JDBCConnector.invalid_source=Specified connection source {0} is not a XADataSource, DataSource, or Driver
+
+BlobValueReference.Unable_to_read_BLOB_data=Unable to read BLOB data from InputStream.
+ClobValueReference.Unable_to_read_CLOB_data=Unable to read CLOB data from character stream.
+BasicSQLTranslator.The_format_of_set_criteria_batch_size_is_incorrect._1=The format of set criteria batch size is incorrect.
+JDBCSynchExecution.Statement_type_not_support_for_command_1=Statement type {0} not support for command {1}
+JDBCSourceConnection.Property_{0}_is_required,_but_not_defined_1=Property {0} is required, but not defined
+DropFunctionModifier.DropFunctionModifier_can_only_be_used_on_functions_with___1=DropFunctionModifier can only be used on functions with minimum or more number of arguments:
+JDBCSourceConnection.Execution_mode_not_supported__{0}_1=Execution mode not supported: {0}
+JDBCProcedureExecution.The_parameter_direction_must_be_out_or_inout_1=The parameter direction must be out or inout
+JDBCProcedureExecution.Unexpected_exception_1=Unexpected exception
+JDBCQueryExecution.Error_executing_query__1 = {0}\n\nExecuting statement:\n\n {1}
+JDBCQueryExecution.Error_executing_query__2 = {0}\n\nAfter executing batch statements:\n
+JDBCQueryExecution.Error_executing_query__3 = {0}\n\nWhile executing batch statements:\n
+
+JDBCSingleIdentityDSConnectionFactory.Unable_to_set_DataSource_property=Unable to set DataSource property name \"{0}\" to value \"{1}"
+JDBCXAConnector.Connector_use_exclusive_mode_1=Connector uses exclusive connections for transactions.
+
+ConnectionListener.failed_to_report_jdbc_connection_details=Failed to report the JDBC driver and connection information
+ConnectionListener.failed_to_report_oracle_connection_details=Failed to report Oracle driver and connection information, consider making the V$ tables public for providing useful information for tuning purposes
+StringToTimestampWithTimeZoneTransform=Unable to parse timestamp string: {0}
+
+JDBCUserIdentityConnectionFactory.Unable_to_get_credentials=Unable to extract credentials from command payload or trusted session payload for per-user connection.
+JDBCUserIdentityConnectionFactory.Connection_property_missing=Required connection property "{0}" missing for system "{1}".
+
+BasicResultsTranslator.Couldn__t_parse_property=Could not parse property: {0}
+
+JDBCMetadataProcessor.cannot_find_primary=Cannot find primary key table {0}
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/FakeMetadataFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,11 +26,11 @@
import junit.framework.Assert;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
import com.metamatrix.cdk.api.TranslationUtility;
import com.metamatrix.cdk.unittest.FakeTranslationFactory;
@@ -56,7 +56,7 @@
// Convert from sql to objects
Command obj = helpTranslate(vdb, input);
- TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator); //$NON-NLS-1$
+ TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), translator);
tc.translateCommand(obj);
// Check stuff
Added: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,44 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.jdbc;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator;
+public class TestJDBCExecutionFactory {
+
+ @Test public void testGetExtensionTranslationClassDefault() throws Exception {
+ JDBCExecutionFactory mcf = new JDBCExecutionFactory();
+ assertSame(Translator.class, mcf.getTranslator().getClass());
+ }
+
+ @Test public void testGetExtensionTranslationClass() throws Exception {
+ JDBCExecutionFactory mcf = new JDBCExecutionFactory();
+ mcf.setExtensionTranslationClassName(SQLServerSQLTranslator.class.getName());
+ assertSame(SQLServerSQLTranslator.class, mcf.getTranslator().getClass());
+ }
+
+}
Property changes on: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCExecutionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCManagedConnectionFactory.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCManagedConnectionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,43 +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.jdbc;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.teiid.connector.jdbc.sqlserver.SQLServerSQLTranslator;
-import org.teiid.connector.jdbc.translator.Translator;
-public class TestJDBCManagedConnectionFactory {
-
- @Test public void testGetExtensionTranslationClassDefault() throws Exception {
- JDBCManagedConnectionFactory mcf = new JDBCManagedConnectionFactory();
- assertSame(Translator.class, mcf.getTranslator().getClass());
- }
-
- @Test public void testGetExtensionTranslationClass() throws Exception {
- JDBCManagedConnectionFactory mcf = new JDBCManagedConnectionFactory();
- mcf.setExtensionTranslationClassName(SQLServerSQLTranslator.class.getName());
- assertSame(SQLServerSQLTranslator.class, mcf.getTranslator().getClass());
- }
-
-}
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,10 +31,11 @@
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.JDBCProcedureExecution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.Translator;
public class TestJDBCProcedureExecution {
@@ -47,11 +48,10 @@
Mockito.stub(connection.prepareCall("{ call spTest8a(?)}")).toReturn(cs); //$NON-NLS-1$
Translator sqlTranslator = new Translator();
- JDBCManagedConnectionFactory config = Mockito.mock(JDBCManagedConnectionFactory.class);
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config);
+ JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
procedureExecution.execute();
assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
Mockito.verify(cs, Mockito.times(1)).registerOutParameter(1, Types.INTEGER);
@@ -65,11 +65,10 @@
Mockito.stub(connection.prepareCall("{ call spTest8(?,?)}")).toReturn(cs); //$NON-NLS-1$
Translator sqlTranslator = new Translator();
- JDBCManagedConnectionFactory config = Mockito.mock(JDBCManagedConnectionFactory.class);
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
Mockito.stub(config.getTranslator()).toReturn(sqlTranslator);
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config );
+ JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), config, sqlTranslator);
procedureExecution.execute();
assertEquals(Arrays.asList(5), procedureExecution.getOutputParameterValues());
Mockito.verify(cs, Mockito.times(1)).registerOutParameter(2, Types.INTEGER);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TestJDBCUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,13 +28,14 @@
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
+import org.teiid.connector.language.ExpressionValueSource;
import org.teiid.connector.language.Insert;
-import org.teiid.connector.language.ExpressionValueSource;
import org.teiid.connector.language.Literal;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.adapter.jdbc.JDBCUpdateExecution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.Translator;
public class TestJDBCUpdateExecution {
@@ -53,11 +54,10 @@
Mockito.stub(p.executeBatch()).toReturn(new int [] {1, 1});
Mockito.stub(connection.prepareStatement("INSERT INTO SmallA (IntKey, IntNum) VALUES (?, ?)")).toReturn(p); //$NON-NLS-1$
- JDBCManagedConnectionFactory config = Mockito.mock(JDBCManagedConnectionFactory.class);
+ JDBCExecutionFactory config = Mockito.mock(JDBCExecutionFactory.class);
Mockito.stub(config.getTranslator()).toReturn(new Translator());
- Mockito.stub(config.getLogger()).toReturn(Mockito.mock(ConnectorLogger.class));
- JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, Mockito.mock(ExecutionContext.class), config);
+ JDBCUpdateExecution updateExecution = new JDBCUpdateExecution(command, connection, Mockito.mock(ExecutionContext.class), config, config.getTranslator());
updateExecution.execute();
Mockito.verify(p, Mockito.times(2)).addBatch();
}
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/TranslationHelper.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,11 +30,11 @@
import junit.framework.Assert;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
import com.metamatrix.cdk.api.TranslationUtility;
import com.metamatrix.cdk.unittest.FakeTranslationFactory;
@@ -66,7 +66,7 @@
Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
util.setUDF(methods);
} catch (IOException e) {
- throw new MetaMatrixRuntimeException("failed to load UDF");
+ throw new MetaMatrixRuntimeException("failed to load UDF"); //$NON-NLS-1$
}
}
return util.parseCommand(sql);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access/TestAccessSQLTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/access/TestAccessSQLTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/access/TestAccessSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,12 +25,13 @@
import junit.framework.TestCase;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.access.AccessSQLTranslator;
import com.metamatrix.cdk.unittest.FakeTranslationFactory;
@@ -45,7 +46,7 @@
static {
try {
TRANSLATOR = new AccessSQLTranslator();
- TRANSLATOR.initialize( Mockito.mock(JDBCManagedConnectionFactory.class));
+ TRANSLATOR.initialize(Mockito.mock(JDBCExecutionFactory.class));
} catch(ConnectorException e) {
e.printStackTrace();
}
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2ConvertModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2ConvertModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2ConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,12 +29,13 @@
import junit.framework.TestCase;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.db2.DB2SQLTranslator;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -54,7 +55,7 @@
public String helpGetString(Expression expr) throws Exception {
DB2SQLTranslator trans = new DB2SQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(expr);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2SqlTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2SqlTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/db2/TestDB2SqlTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,12 +27,13 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.db2.DB2SQLTranslator;
import com.metamatrix.cdk.api.TranslationUtility;
import com.metamatrix.cdk.unittest.FakeTranslationFactory;
@@ -47,7 +48,7 @@
@BeforeClass
public static void setUp() throws ConnectorException {
TRANSLATOR = new DB2SQLTranslator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
public String getTestVDB() {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbyCapabilities.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbyCapabilities.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbyCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,6 +25,7 @@
import static org.junit.Assert.*;
import org.junit.Test;
+import org.teiid.translator.jdbc.derby.DerbyCapabilities;
public class TestDerbyCapabilities {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbySQLTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbySQLTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/derby/TestDerbySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,9 +24,11 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
+import org.mockito.Mockito;
import org.teiid.connector.jdbc.TranslationHelper;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.derby.DerbySQLTranslator;
/**
@@ -38,7 +40,7 @@
@BeforeClass
public static void setUp() throws ConnectorException {
TRANSLATOR = new DerbySQLTranslator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(Mockito.mock(JDBCExecutionFactory.class));
}
@Test
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/extension/TestSQLConversionVisitor.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/extension/TestSQLConversionVisitor.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/extension/TestSQLConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,16 +22,11 @@
package org.teiid.connector.jdbc.extension;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.LanguageObject;
import org.teiid.connector.metadata.runtime.RuntimeMetadata;
import org.teiid.dqp.internal.datamgr.impl.ExecutionContextImpl;
@@ -41,6 +36,11 @@
import org.teiid.dqp.internal.datamgr.language.TestQueryImpl;
import org.teiid.dqp.internal.datamgr.language.TestUpdateImpl;
import org.teiid.dqp.internal.datamgr.language.TstLanguageBridgeFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
/**
*/
@@ -59,7 +59,7 @@
@BeforeClass public static void oneTimeSetup() throws ConnectorException {
TRANSLATOR = new Translator();
- JDBCManagedConnectionFactory env = new JDBCManagedConnectionFactory();
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
env.setTrimStrings(true);
TRANSLATOR.initialize(env);
}
@@ -74,7 +74,7 @@
public void helpTestVisitor(String vdb, String input, String expectedOutput, boolean usePreparedStatement) {
Translator trans = new Translator();
- JDBCManagedConnectionFactory env = new JDBCManagedConnectionFactory();
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
if (usePreparedStatement) {
env.setUseBindVariables(true);
}
@@ -89,7 +89,7 @@
public static final RuntimeMetadata metadata = TstLanguageBridgeFactory.metadataFactory;
private String getStringWithContext(LanguageObject obj) throws ConnectorException {
- JDBCManagedConnectionFactory env = new JDBCManagedConnectionFactory();
+ JDBCExecutionFactory env = new JDBCExecutionFactory();
env.setUseCommentsInSourceQuery(true);
Translator trans = new Translator();
trans.initialize(env);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2/TestH2Translator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/h2/TestH2Translator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/h2/TestH2Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,9 +24,10 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.h2.H2Translator;
public class TestH2Translator {
@@ -35,7 +36,7 @@
@BeforeClass
public static void setUp() throws ConnectorException {
TRANSLATOR = new H2Translator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
@Test public void testTimestampDiff() throws Exception {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQL5Translator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQL5Translator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQL5Translator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,9 +24,10 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.mysql.MySQL5Translator;
/**
*/
@@ -36,7 +37,7 @@
@BeforeClass public static void oneTimeSetup() throws ConnectorException {
TRANSLATOR = new MySQL5Translator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
@Test public void testChar() throws Exception {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQLTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQLTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/mysql/TestMySQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,9 +25,10 @@
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.mysql.MySQLTranslator;
/**
*/
@@ -37,7 +38,7 @@
@BeforeClass public static void oneTimeSetup() throws ConnectorException {
TRANSLATOR = new MySQLTranslator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
private String getTestVDB() {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestDayWeekQuarterFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,12 +27,13 @@
import junit.framework.TestCase;
-import org.teiid.connector.api.SourceSystemFunctions;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -56,7 +57,7 @@
String.class);
OracleSQLTranslator trans = new OracleSQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLeftOrRightFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLeftOrRightFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLeftOrRightFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,11 +26,12 @@
import junit.framework.TestCase;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
/**
*/
@@ -52,7 +53,7 @@
String.class);
OracleSQLTranslator trans = new OracleSQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLog10FunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLog10FunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestLog10FunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -32,6 +32,7 @@
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
import org.teiid.connector.visitor.util.SQLStringVisitor;
+import org.teiid.translator.jdbc.oracle.Log10FunctionModifier;
/**
*/
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestMonthOrDayNameFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,11 +27,12 @@
import junit.framework.TestCase;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -55,7 +56,7 @@
String.class);
OracleSQLTranslator trans = new OracleSQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleConvertModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleConvertModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.connector.jdbc.oracle;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -31,13 +31,14 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -50,12 +51,12 @@
private static Translator TRANSLATOR = new OracleSQLTranslator();
@BeforeClass public static void oneTimeSetup() throws Exception {
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
public String helpGetString(Expression expr) throws Exception {
OracleSQLTranslator trans = new OracleSQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = TRANSLATOR.getSQLConversionVisitor();
sqlVisitor.append(expr);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,12 +28,7 @@
import org.junit.Before;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
-import org.teiid.connector.jdbc.translator.Translator;
import org.teiid.connector.language.Command;
import org.teiid.connector.metadata.runtime.Column;
import org.teiid.connector.metadata.runtime.MetadataStore;
@@ -43,6 +38,12 @@
import org.teiid.dqp.internal.datamgr.impl.FakeExecutionContextImpl;
import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.Translator;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
import com.metamatrix.cdk.CommandBuilder;
import com.metamatrix.cdk.api.TranslationUtility;
@@ -64,7 +65,7 @@
@Before
public void setup() throws Exception {
TRANSLATOR = new OracleSQLTranslator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
private void helpTestVisitor(String input, String expectedOutput) throws ConnectorException {
@@ -140,6 +141,17 @@
input, output,
TRANSLATOR);
}
+
+ /**
+ * here we use the date form of the conversion
+ */
+ @Test public void testConversion6a() throws Exception {
+ String input = "SELECT convert(timestampvalue, string) FROM BQT1.SMALLA"; //$NON-NLS-1$
+ String output = "SELECT to_char(SmallishA.timestampvalue, 'YYYY-MM-DD HH24:MI:SS') FROM SmallishA"; //$NON-NLS-1$
+
+ helpTestVisitor(getOracleSpecificMetadata(), input, EMPTY_CONTEXT, null, output);
+ }
+
@Test public void testConversion8() throws Exception {
String input = "SELECT nvl(INTNUM, 'otherString') FROM BQT1.SMALLA"; //$NON-NLS-1$
String output = "SELECT nvl(to_char(SmallA.IntNum), 'otherString') FROM SmallA"; //$NON-NLS-1$
@@ -414,12 +426,7 @@
*/
@Test public void test_sdo_within_distance3() throws Exception {
String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance(STRINGKEY, 'SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- // using ? for bind value as r marks the criteria as bindEligible
- // due to literal of type Object appearing in left side of criteria.
- // The literal Object is a result of the sdo_within_distance function
- // signature being sdo_within_distance(string, object, string) : string
- // as the signature was the best match for this query.
- String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SmallA.StringKey, SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = ?"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SmallA.StringKey, SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
input, output,
@@ -435,12 +442,7 @@
*/
@Test public void test_sdo_within_distance4() throws Exception {
String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- // using ? for bind value as r marks the criteria as bindEligible
- // due to literal of type Object appearing in left side of criteria.
- // The literal Object is a result of the sdo_within_distance function
- // signature being sdo_within_distance(string, object, string) : string
- // as the signature was the best match for this query.
- String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = ?"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
input, output,
@@ -521,7 +523,7 @@
private void helpTestVisitor(Command obj, ExecutionContext context, String dbmsTimeZone, String expectedOutput) throws ConnectorException {
OracleSQLTranslator translator = new OracleSQLTranslator();
- JDBCManagedConnectionFactory f = new JDBCManagedConnectionFactory();
+ JDBCExecutionFactory f = new JDBCExecutionFactory();
if (dbmsTimeZone != null) {
f.setDatabaseTimeZone(dbmsTimeZone);
}
@@ -705,14 +707,17 @@
String[] elemNames = new String[] {
"DoubleNum", //$NON-NLS-1$
"ID", //$NON-NLS-1$
+ "timestampvalue", //$NON-NLS-1$
};
String[] elemTypes = new String[] {
DataTypeManager.DefaultDataTypes.DOUBLE,
DataTypeManager.DefaultDataTypes.INTEGER,
+ DataTypeManager.DefaultDataTypes.TIMESTAMP,
};
List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
cols.get(1).setAutoIncremented(true);
cols.get(1).setNameInSource("ID:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
+ cols.get(2).setNativeType("date"); //$NON-NLS-1$
RealMetadataFactory.createElements(dual, new String[] {"something"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$
CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
@@ -757,9 +762,15 @@
String input = "(select intkey from bqt1.smalla limit 50, 100) union select intnum from bqt1.smalla order by intkey"; //$NON-NLS-1$
String output = "SELECT c_0 FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT g_1.IntKey AS c_0 FROM SmallA g_1) VIEW_FOR_LIMIT WHERE ROWNUM <= 150) WHERE ROWNUM_ > 50 UNION SELECT g_0.IntNum AS c_0 FROM SmallA g_0 ORDER BY c_0 NULLS FIRST"; //$NON-NLS-1$
- CommandBuilder commandBuilder = new CommandBuilder(FakeMetadataFactory.exampleBQTCached());
+ CommandBuilder commandBuilder = new CommandBuilder(FakeMetadataFactory.exampleBQTCached());
Command obj = commandBuilder.getCommand(input, true, true);
this.helpTestVisitor(obj, EMPTY_CONTEXT, null, output);
}
+
+ @Test public void testCot() throws Exception {
+ String sql = "select cot(doublenum) from BQT1.Smalla"; //$NON-NLS-1$
+ String expected = "SELECT (1 / tan(SmallA.DoubleNum)) FROM SmallA"; //$NON-NLS-1$
+ helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+ }
}
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestSubstringFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestSubstringFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestSubstringFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,12 +26,13 @@
import junit.framework.TestCase;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.oracle.OracleSQLTranslator;
/**
*/
@@ -53,7 +54,7 @@
Arrays.asList(args), TypeFacility.RUNTIME_TYPES.STRING);
OracleSQLTranslator trans = new OracleSQLTranslator();
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/TestPostgreSQLTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/TestPostgreSQLTranslator.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/postgresql/TestPostgreSQLTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,9 +24,10 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.postgresql.PostgreSQLTranslator;
public class TestPostgreSQLTranslator {
@@ -34,7 +35,7 @@
@BeforeClass public static void setupOnce() throws Exception {
TRANSLATOR = new PostgreSQLTranslator();
- TRANSLATOR.initialize(new JDBCManagedConnectionFactory());
+ TRANSLATOR.initialize(new JDBCExecutionFactory());
}
public String getTestVDB() {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/TestSqlServerConversionVisitor.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sqlserver/TestSqlServerConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,8 +26,6 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
import org.teiid.connector.language.Command;
import org.teiid.connector.metadata.runtime.Column;
@@ -36,6 +34,9 @@
import org.teiid.connector.metadata.runtime.Table;
import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.sqlserver.SQLServerSQLTranslator;
import com.metamatrix.cdk.api.TranslationUtility;
import com.metamatrix.common.types.DataTypeManager;
@@ -50,7 +51,7 @@
@BeforeClass
public static void setup() throws ConnectorException {
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
}
public String getTestVDB() {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseConvertModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseConvertModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseConvertModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.connector.jdbc.sybase;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -30,13 +30,14 @@
import org.junit.BeforeClass;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
-import org.teiid.connector.jdbc.translator.SQLConversionVisitor;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.sybase.SybaseSQLTranslator;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -50,7 +51,7 @@
@BeforeClass
public static void setup() throws ConnectorException {
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
}
public String helpGetString(Expression expr) throws Exception {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseSQLConversionVisitor.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseSQLConversionVisitor.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/sybase/TestSybaseSQLConversionVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,17 +22,18 @@
package org.teiid.connector.jdbc.sybase;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.jdbc.TranslationHelper;
-import org.teiid.connector.jdbc.translator.TranslatedCommand;
import org.teiid.connector.language.Command;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.sybase.SybaseSQLTranslator;
/**
*/
@@ -42,7 +43,7 @@
@BeforeClass
public static void setup() throws ConnectorException {
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
}
public String getTestVDB() {
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestEscapeSyntaxModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestEscapeSyntaxModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestEscapeSyntaxModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,10 +26,10 @@
import java.util.Arrays;
import java.util.List;
-import org.teiid.connector.jdbc.translator.EscapeSyntaxModifier;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.Literal;
import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.translator.jdbc.EscapeSyntaxModifier;
import junit.framework.TestCase;
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestExtractFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestExtractFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestExtractFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,15 +27,18 @@
import junit.framework.TestCase;
-import org.teiid.connector.api.SourceSystemFunctions;
-import org.teiid.connector.api.TypeFacility;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.language.ColumnReference;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
import org.teiid.connector.language.Literal;
import org.teiid.connector.language.NamedTable;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.translator.jdbc.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
import com.metamatrix.query.unittest.TimestampUtil;
@@ -61,7 +64,7 @@
ExtractFunctionModifier mod = new ExtractFunctionModifier ();
Translator trans = new Translator();
trans.registerFunctionModifier(target, mod);
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestLocateFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestLocateFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestLocateFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,17 +22,20 @@
package org.teiid.connector.jdbc.translator;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.SourceSystemFunctions;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
/**
* Test <code>LOCATEFunctionModifier</code> by invoking its methods with varying
@@ -97,14 +100,14 @@
Translator trans = new Translator() {
@Override
- public void initialize(JDBCManagedConnectionFactory env)
+ public void initialize(JDBCExecutionFactory env)
throws ConnectorException {
super.initialize(env);
registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory(), locateFunctionName, parameterOrder));
}
};
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Modified: trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestModFunctionModifier.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestModFunctionModifier.java 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-jdbc/src/test/java/org/teiid/connector/jdbc/translator/TestModFunctionModifier.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,15 +28,16 @@
import junit.framework.TestCase;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.SourceSystemFunctions;
-import org.teiid.connector.jdbc.JDBCManagedConnectionFactory;
import org.teiid.connector.language.Expression;
import org.teiid.connector.language.Function;
import org.teiid.connector.language.LanguageFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.jdbc.JDBCExecutionFactory;
+import org.teiid.resource.cci.SourceSystemFunctions;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.Translator;
-import com.metamatrix.cdk.CommandBuilder;
-
/**
* Test <code>ModFunctionModifier</code> by invoking its methods with varying
* parameters to validate it performs as designed and expected.
@@ -92,14 +93,14 @@
Translator trans = new Translator() {
@Override
- public void initialize(JDBCManagedConnectionFactory env)
+ public void initialize(JDBCExecutionFactory env)
throws ConnectorException {
super.initialize(env);
registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier(modFunctionName, getLanguageFactory()));
}
};
- trans.initialize(new JDBCManagedConnectionFactory());
+ trans.initialize(new JDBCExecutionFactory());
SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor();
sqlVisitor.append(func);
Property changes on: trunk/connectors/translator-ldap
___________________________________________________________________
Name: svn:ignore
+ target
.settings
.classpath
.project
Added: trunk/connectors/translator-ldap/pom.xml
===================================================================
--- trunk/connectors/translator-ldap/pom.xml (rev 0)
+++ trunk/connectors/translator-ldap/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.0.0-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-connector-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>
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/IQueryToLdapSearchParser.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/IQueryToLdapSearchParser.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/IQueryToLdapSearchParser.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,654 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+/**
+ * Utility class to handle the parsing of an IQuery object into all the relevant LDAP search
+ * information. Uses LdapSearchDetails class to store this information and return the search details.
+ * This class was intended for use by the execution classes that need to translate SQL. As new capabilities
+ * are implemented, this class will be expanded to accommodate the appropriate SQL.
+ *
+ * This class should remove all the MMX-specific stuff, and turn it into something any
+ * LDAP implementation can understand.
+ *
+ */
+
+package org.teiid.resource.adapter.ldap;
+
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.ListIterator;
+
+import javax.naming.NamingException;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.SearchControls;
+import javax.naming.ldap.SortKey;
+
+import org.teiid.connector.language.AggregateFunction;
+import org.teiid.connector.language.AndOr;
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.Condition;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Exists;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.In;
+import org.teiid.connector.language.Like;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.Not;
+import org.teiid.connector.language.OrderBy;
+import org.teiid.connector.language.ScalarSubquery;
+import org.teiid.connector.language.SearchedCase;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.language.SortSpecification;
+import org.teiid.connector.language.TableReference;
+import org.teiid.connector.language.Comparison.Operator;
+import org.teiid.connector.language.SortSpecification.Ordering;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+
+
+
+/**
+ * Utility class which translates a SQL query into an LDAP search.
+ */
+public class IQueryToLdapSearchParser {
+ LDAPExecutionFactory executionFactory;
+
+ /**
+ * Constructor.
+ * @param logger the connector logger
+ * @param rm the RuntimeMetadata
+ */
+ public IQueryToLdapSearchParser(LDAPExecutionFactory factory) {
+ this.executionFactory = factory;
+ }
+
+ /**
+ * Public entry point to the parser.
+ * Parses the IQuery object, and constructs an equivalent LDAP search filter,
+ * keeping track of the attributes of interest.
+ * Here are some example SQL queries, and the equivalent LDAP search info:
+ * SQL: select cn, managerName from people_table where managerName LIKE "John%" and cn!="Mar()"
+ * Context name: [people_table's NameInSource, e.g. (ou=people,dc=company,dc=com)]
+ * LDAP attributes: (cn, String), (managerName, String)
+ * LDAP search filter: (&(managerName="John*")(!(cn="Mar\(\)")))
+ *
+ * @param query the query
+ * @return the LDAPSearchDetails object
+ */
+ // GHH 20080326 - added ability to restrict queries to only values where
+ // objectClass = table name. This is done by adding a third parameter,
+ // RESTRICT, to the NameInSource property in the model:
+ // ou=people,dc=company,dc=com?SUBTREE_SCOPE?RESTRICT
+ // TODO - change method for calling RESTRICT to also specify
+ // object class name (RESTRICT=inetOrgPerson)
+ public LDAPSearchDetails translateSQLQueryToLDAPSearch(Select query) throws ConnectorException {
+ // Parse SELECT symbols.
+ // The columns will be translated into LDAP attributes of interest.
+ ArrayList attributeList = getAttributesFromSelectSymbols(query);
+ ArrayList elementList = getElementsFromSelectSymbols(query);
+
+ // Parse FROM table.
+ // Only one table is expected here.
+ List fromList = query.getFrom();
+ Iterator itr = fromList.listIterator();
+ if(!itr.hasNext()) {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.noTablesInFromError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ TableReference fItm = (TableReference)itr.next();
+ if(itr.hasNext()) {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.multiItemsInFromError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ String contextName = getContextNameFromFromItem(fItm);
+ int searchScope = getSearchScopeFromFromItem(fItm);
+ // GHH 20080326 - added check for RESTRICT parameter in
+ // NameInSource of from item
+ String classRestriction = getRestrictToNamedClass(fItm);
+
+ // Parse the WHERE clause.
+ // Create an equivalent LDAP search filter.
+ List searchStringList = new LinkedList();
+ searchStringList = getSearchFilterFromWhereClause(query.getWhere(), searchStringList);
+ String filter = new String();
+ ListIterator filterItr = searchStringList.listIterator();
+ while(filterItr.hasNext()) {
+ filter += filterItr.next();
+ }
+ // GHH 20080326 - if there is a class restriction,
+ // add it to the search filter
+ if (classRestriction != null && classRestriction.trim().length()>0) {
+ filter = "(&"+filter+"(objectClass="+classRestriction+"))"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ // Parse the ORDER BY clause.
+ // Create an ordered sort list.
+ OrderBy orderBy = (OrderBy)query.getOrderBy();
+ // Referenced the JNDI standard...arguably, this should not be done inside this
+ // class, and we should make our own key class. In practice, this makes things simpler.
+ SortKey[] sortKeys = getSortKeysFromOrderByClause(orderBy);
+
+ // Parse LIMIT clause.
+ // Note that offsets are not supported.
+ Limit limit = (Limit)query.getLimit();
+ long countLimit = -1;
+ if(limit != null) {
+ countLimit = limit.getRowLimit();
+ }
+
+ // Create Search Details
+ LDAPSearchDetails sd = new LDAPSearchDetails(contextName, searchScope, filter, attributeList, sortKeys, countLimit, elementList);
+ // Search Details logging
+ try {
+ sd.printDetailsToLog();
+ } catch (NamingException nme) {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.searchDetailsLoggingError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+
+ return sd;
+
+ }
+
+ /**
+ * get SortKeys from the supplied ORDERBY clause.
+ * @param orderBy the OrderBy clause
+ * @param the array of SortKeys
+ */
+ private SortKey[] getSortKeysFromOrderByClause(OrderBy orderBy) throws ConnectorException {
+ SortKey[] sortKeys = null;
+ if(orderBy != null) {
+ List orderItems = orderBy.getSortSpecifications();
+ if(orderItems == null) {
+ return null;
+ }
+ SortKey sortKey = null;
+ sortKeys = new SortKey[orderItems.size()];
+ Iterator orderItr = orderItems.iterator();
+ int i = 0;
+ while(orderItr.hasNext()) {
+ SortSpecification item = (SortSpecification)orderItr.next();
+ if(item != null) {
+ String itemName = getExpressionString((Expression)item.getExpression());
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Adding sort key for item: " + itemName); //$NON-NLS-1$
+ if(item.getOrdering() == Ordering.ASC) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "with ASC ordering."); //$NON-NLS-1$
+ sortKey = new SortKey(itemName, true, null);
+ } else if(item.getOrdering() == Ordering.DESC){
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "with DESC ordering."); //$NON-NLS-1$
+ sortKey = new SortKey(itemName, false, null);
+ }
+ }
+ sortKeys[i] = sortKey;
+ i++;
+ }
+
+ } else {
+ // Insert a default? No, allow the Execution to do this. Just return a null list.
+ }
+ return sortKeys;
+ }
+
+ /**
+ * Utility method to pull the name in source (or, base DN/context name) from the table.
+ * @param fromItem
+ * @return name in source
+ */
+ // GHH 20080409 - changed to fall back on new connector property
+ // for default base DN if available
+ private String getContextNameFromFromItem(TableReference fromItem) throws ConnectorException {
+ String nameInSource;
+ String contextName;
+
+ // TODO: Re-use the getExpressionString method if possible, rather than
+ // rewriting the same code twice.
+ if(fromItem instanceof NamedTable) {
+ Table group = ((NamedTable)fromItem).getMetadataObject();
+ nameInSource = group.getNameInSource();
+ // if NameInSource is null set it to an empty
+ // string instead so we can safely call split on it
+ if(nameInSource == null) {
+ nameInSource = ""; //$NON-NLS-1$
+ }
+ // now split it on ? to find the part of it that specifies context name
+ String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
+ contextName = nameInSourceArray[0];
+ // if there is no context name specified
+ // try the default in the connector properties
+ if(contextName.equals("")) { //$NON-NLS-1$
+ contextName = this.executionFactory.getSearchDefaultBaseDN();
+ }
+ } else {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ // if the context name is not specified either in Name in Source
+ // or in the default connector properties it'll be either
+ // null or an empty string
+ if(contextName == null || contextName.equals("")) { //$NON-NLS-1$
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.baseContextNameError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ return contextName;
+
+ }
+
+ // GHH 20080326 - added below method to check for RESTRICT parameter in
+ // from item's NameInSource, and if true return name (not NameInSource)
+ // of from item as the objectClass name on to which the query should
+ // be restricted
+ private String getRestrictToNamedClass(TableReference fromItem) throws ConnectorException {
+ String nameInSource;
+ String namedClass = null;
+ if(fromItem instanceof NamedTable) {
+ // Here we use slightly different logic than in
+ // getContextNameFromFromItem so it is easier to get
+ // the group name later if needed
+ Table mdIDGroup = ((NamedTable)fromItem).getMetadataObject();
+ nameInSource = mdIDGroup.getNameInSource();
+ // groupName = mdIDGroup.getName();
+ // if NameInSource is null set it to an empty
+ // string instead so we can safely call split on it
+ if(nameInSource == null) {
+ nameInSource = ""; //$NON-NLS-1$
+ }
+ // now split it on ? to find the part of it that specifies the objectClass we should restrict on
+ String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
+ if(nameInSourceArray.length >= 3) {
+ namedClass = nameInSourceArray[2];
+ }
+ // if there is no specification in the Name In Source,
+ // see if the connector property is set to true. If
+ // it is, use the Name of the class for the restriction.
+ if(namedClass == null || namedClass.equals("")) { //$NON-NLS-1$
+ if (!this.executionFactory.isRestrictToObjectClass()) {
+ namedClass = ""; //$NON-NLS-1$
+ } else {
+ namedClass = mdIDGroup.getName();
+ }
+ }
+ } else {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ return namedClass;
+ }
+
+ private int getSearchScopeFromFromItem(TableReference fromItem) throws ConnectorException {
+ String searchScopeString = ""; //$NON-NLS-1$
+ int searchScope = LDAPConnectorConstants.ldapDefaultSearchScope;
+ // TODO: Re-use the getExpressionString method if possible, rather than
+ // rewriting the same code twice.
+ if(fromItem instanceof NamedTable) {
+ Table group = ((NamedTable)fromItem).getMetadataObject();
+ String nameInSource = group.getNameInSource();
+ // if NameInSource is null set it to an empty
+ // string instead so we can safely call split on it
+ if(nameInSource == null) {
+ nameInSource = ""; //$NON-NLS-1$
+ }
+ // now split it on ? to find the part of it that specifies search scope
+ String nameInSourceArray[] = nameInSource.split("\\?"); //$NON-NLS-1$
+ if(nameInSourceArray.length >= 2) {
+ searchScopeString = nameInSourceArray[1];
+ }
+ // if there is no search scope specified
+ // try the default in the connector properties
+ if(searchScopeString.equals("")) { //$NON-NLS-1$
+ searchScopeString = this.executionFactory.getSearchDefaultScope();
+ // protect against getting null back from the property
+ if(searchScopeString == null) {
+ searchScopeString = ""; //$NON-NLS-1$
+ }
+ }
+ if(searchScopeString.equals("SUBTREE_SCOPE")) { //$NON-NLS-1$
+ searchScope = SearchControls.SUBTREE_SCOPE;
+ } else if(searchScopeString.equals("ONELEVEL_SCOPE")) { //$NON-NLS-1$
+ searchScope = SearchControls.ONELEVEL_SCOPE;
+ } else if(searchScopeString.equals("OBJECT_SCOPE")) { //$NON-NLS-1$
+ searchScope = SearchControls.OBJECT_SCOPE;
+ }
+ } else {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.groupCountExceededError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ return searchScope;
+ }
+
+ /**
+ * Utility method to convert operator to the appropriate string value for LDAP.
+ * @param op operator to evaluate
+ * @return LDAP-specific string equivalent of the operator
+ */
+ private String parseCompoundCriteriaOp(AndOr.Operator op) throws ConnectorException {
+ switch(op) {
+ case AND:
+ return "&"; //$NON-NLS-1$
+ case OR:
+ return "|"; //$NON-NLS-1$
+ default:
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.criteriaNotParsableError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ }
+
+ /**
+ * Utility method to convert expression to the appropriate string value for LDAP.
+ * @param e expression to evaluate
+ * @return LDAP-specific string equivalent of the expression
+ */
+ // GHH 20080326 - found that code to fall back on Name if NameInSource
+ // was null wasn't working properly, so replaced with tried and true
+ // code from another custom connector.
+ private String getExpressionString(Expression e) throws ConnectorException {
+ String expressionName = null;
+ // GHH 20080326 - changed around the IElement handling here
+ // - the rest of this method is unchanged
+ if(e instanceof ColumnReference) {
+ Column mdIDElement = ((ColumnReference)e).getMetadataObject();
+ expressionName = mdIDElement.getNameInSource();
+ if(expressionName == null || expressionName.equals("")) { //$NON-NLS-1$
+ expressionName = mdIDElement.getName();
+ }
+ } else if(e instanceof Literal) {
+ try {
+ if(((Literal)e).getType().equals(Class.forName(Timestamp.class.getName()))) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Found an expression that uses timestamp; converting to LDAP string format."); //$NON-NLS-1$
+ Timestamp ts = (Timestamp)((Literal)e).getValue();
+ Date dt = new Date(ts.getTime());
+ //TODO: Fetch format if provided.
+ SimpleDateFormat sdf = new SimpleDateFormat(LDAPConnectorConstants.ldapTimestampFormat);
+ expressionName = sdf.format(dt);
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Timestamp to stsring is: " + expressionName); //$NON-NLS-1$
+ }
+ else {
+ expressionName = ((Literal)e).getValue().toString();
+ }
+ } catch (ClassNotFoundException cce) {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.timestampClassNotFoundError"); //$NON-NLS-1$
+ throw new ConnectorException(cce, msg);
+ }
+
+ } else {
+ if(e instanceof AggregateFunction) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IAggregate, but it is not supported. Check capabilities."); //$NON-NLS-1$
+ } else if(e instanceof Function) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IFunction, but it is not supported. Check capabilties."); //$NON-NLS-1$
+ } else if(e instanceof ScalarSubquery) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IScalarSubquery, but it is not supported. Check capabilties."); //$NON-NLS-1$
+ } else if (e instanceof SearchedCase) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Received ISearchedCaseExpression, but it is not supported. Check capabilties."); //$NON-NLS-1$
+ }
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.unsupportedElementError"); //$NON-NLS-1$
+ throw new ConnectorException(msg + e.toString());
+ }
+ expressionName = escapeReservedChars(expressionName);
+ return expressionName;
+ }
+
+ private String escapeReservedChars(String expr) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < expr.length(); i++) {
+ char curChar = expr.charAt(i);
+ switch (curChar) {
+ case '\\':
+ sb.append("\\5c"); //$NON-NLS-1$
+ break;
+ case '*':
+ sb.append("\\2a"); //$NON-NLS-1$
+ break;
+ case '(':
+ sb.append("\\28"); //$NON-NLS-1$
+ break;
+ case ')':
+ sb.append("\\29"); //$NON-NLS-1$
+ break;
+ case '\u0000':
+ sb.append("\\00"); //$NON-NLS-1$
+ break;
+ default:
+ sb.append(curChar);
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Recursive method to translate the where clause into an LDAP search filter.
+ * The goal is to convert infix notation to prefix (Polish) notation.
+ * TODO: There's probably a clever way to do this with a Visitor.
+ * @param criteria Criteria to evaluate.
+ * @param List list to hold each pre-fix character of the search filter.
+ * @return list list that can be traversed in order to construct the search filter.
+ */
+ private List<String> getSearchFilterFromWhereClause(Condition criteria, List<String> filterList) throws ConnectorException {
+ if(criteria == null) {
+ filterList.add("(objectClass=*)"); //$NON-NLS-1$
+ }
+ boolean isNegated = false;
+ // Recursive case: compound criteria
+ if(criteria instanceof AndOr) {
+ AndOr crit = (AndOr)criteria;
+ AndOr.Operator op = crit.getOperator();
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing compound criteria."); //$NON-NLS-1$
+ String stringOp = parseCompoundCriteriaOp(op);
+
+ filterList.add("("); //$NON-NLS-1$
+ filterList.add(stringOp);
+ filterList.addAll(getSearchFilterFromWhereClause(crit.getLeftCondition(), new LinkedList<String>()));
+ filterList.addAll(getSearchFilterFromWhereClause(crit.getRightCondition(), new LinkedList<String>()));
+ filterList.add(")"); //$NON-NLS-1$
+ // Base case
+ } else if(criteria instanceof Comparison) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing compare criteria."); //$NON-NLS-1$
+ Comparison.Operator op = ((Comparison) criteria).getOperator();
+
+ isNegated = op == Operator.NE || op == Operator.GT || op == Operator.LT;
+
+ Expression lhs = ((Comparison) criteria).getLeftExpression();
+ Expression rhs = ((Comparison) criteria).getRightExpression();
+
+ String lhsString = getExpressionString(lhs);
+ String rhsString = getExpressionString(rhs);
+ if(lhsString == null || rhsString == null) {
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.missingNISError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+
+ addCompareCriteriaToList(filterList, op, lhsString, rhsString);
+ // Base case
+ } else if(criteria instanceof Exists) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing EXISTS criteria: NOT IMPLEMENTED YET"); //$NON-NLS-1$
+ // TODO Exists should be supported in a future release.
+ // Base case
+ } else if(criteria instanceof Like) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing LIKE criteria."); //$NON-NLS-1$
+ isNegated = ((Like) criteria).isNegated();
+ // Convert LIKE to Equals, where any "%" symbol is replaced with "*".
+ Comparison.Operator op = Operator.EQ;
+ Expression lhs = ((Like) criteria).getLeftExpression();
+ Expression rhs = ((Like) criteria).getRightExpression();
+
+ String lhsString = getExpressionString(lhs);
+ String rhsString = getExpressionString(rhs);
+ rhsString = rhsString.replace("%", "*"); //$NON-NLS-1$ //$NON-NLS-2$
+ addCompareCriteriaToList(filterList, op, lhsString, rhsString);
+
+ // Base case
+ } else if(criteria instanceof In) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); //$NON-NLS-1$
+ isNegated = ((In) criteria).isNegated();
+ Expression lhs = ((In)criteria).getLeftExpression();
+ List rhsList = ((In)criteria).getRightExpressions();
+ // Recursively add each IN expression to the filter list.
+ processInCriteriaList(filterList, rhsList, lhs);
+ } else if (criteria instanceof Not) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing NOT criteria."); //$NON-NLS-1$
+ isNegated = true;
+ filterList.addAll(getSearchFilterFromWhereClause(((Not)criteria).getCriteria(), new LinkedList()));
+ }
+
+ if (isNegated) {
+ filterList.add(0, "("); //$NON-NLS-1$
+ filterList.add(1, "!"); //$NON-NLS-1$
+ filterList.add(")"); //$NON-NLS-1$
+ }
+
+ return filterList;
+ }
+
+ /**
+ * Process a list of right-hand side IN expresssions and add the corresponding LDAP filter
+ * clause string to the given filterList.
+ */
+ private void processInCriteriaList(List filterList, List rhsList, Expression lhs) throws ConnectorException {
+ if(rhsList.size() == 0) {
+ return;
+ }
+ filterList.add("("); //$NON-NLS-1$
+ filterList.add(parseCompoundCriteriaOp(org.teiid.connector.language.AndOr.Operator.OR));
+ Iterator rhsItr = rhsList.iterator();
+ while(rhsItr.hasNext()) {
+ addCompareCriteriaToList(filterList, Operator.EQ, getExpressionString(lhs),
+ getExpressionString((Expression)rhsItr.next()));
+ }
+ filterList.add(")"); //$NON-NLS-1$
+ }
+
+ /**
+ * Add Compare Criteria to List
+ * @param filterList the filter list
+ * @param op
+ * @param lhs left hand side expression
+ * @param rhs right hand side expression
+ */
+ private void addCompareCriteriaToList(List filterList, Comparison.Operator op, String lhs, String rhs) throws ConnectorException {
+ // Push the comparison statement into the list, e.g.:
+ // (sn=Mike)
+ // !(empNum>=100)
+ filterList.add("("); //$NON-NLS-1$
+ filterList.add(lhs);
+
+ switch(op) {
+ case NE:
+ case EQ:
+ filterList.add("="); //$NON-NLS-1$
+ break;
+ case LT:
+ case GE:
+ filterList.add(">="); //$NON-NLS-1$
+ break;
+ case GT:
+ case LE:
+ filterList.add("<="); //$NON-NLS-1$
+ break;
+ default:
+ final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.criteriaNotSupportedError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+
+ }
+ filterList.add(rhs);
+ filterList.add(")"); //$NON-NLS-1$
+ }
+
+ /**
+ * Method to get name from the supplied Element
+ * @param e the supplied Element
+ * @return the name
+ */
+ // GHH 20080326 - found that code to fall back on Name if NameInSource
+ // was null wasn't working properly, so replaced with tried and true
+ // code from another custom connector.
+ public String getNameFromElement(Column e) throws ConnectorException {
+ String ldapAttributeName = null;
+ ldapAttributeName = e.getNameInSource();
+ if (ldapAttributeName == null || ldapAttributeName.equals("")) { //$NON-NLS-1$
+ ldapAttributeName = e.getName();
+ // If name in source is not set, then fall back to the column name.
+ }
+ return ldapAttributeName;
+ }
+
+ /**
+ * Method to get SELECT Element list from the supplied query
+ * @param query the supplied Query
+ * @return the list of SELECT elements
+ */
+ private ArrayList getElementsFromSelectSymbols(Select query) throws ConnectorException {
+ ArrayList selectElementList = new ArrayList();
+ Iterator selectSymbolItr = query.getDerivedColumns().iterator();
+
+ while(selectSymbolItr.hasNext()) {
+ Column e = getElementFromSymbol((DerivedColumn)selectSymbolItr.next());
+ selectElementList.add(e);
+ }
+ return selectElementList;
+ }
+
+ /**
+ * Method to get attribute list from the supplied query
+ * @param query the supplied Query
+ * @return the list of attributes
+ */
+ private ArrayList getAttributesFromSelectSymbols(Select query) throws ConnectorException {
+ ArrayList ldapAttributeList = new ArrayList();
+
+ Iterator selectSymbolItr = query.getDerivedColumns().iterator();
+ int i=0;
+ while(selectSymbolItr.hasNext()) {
+ Column e = getElementFromSymbol((DerivedColumn)selectSymbolItr.next());
+ String ldapAttributeName = this.getNameFromElement(e);
+ Object ldapAttributeClass = e.getJavaType();
+
+ // Store the element's name and class type, so that we know what to look for in the search results.
+ BasicAttribute newAttr = new BasicAttribute(ldapAttributeName, ldapAttributeClass);
+ ldapAttributeList.add(newAttr);
+ i++;
+ }
+ return ldapAttributeList;
+ }
+
+ /**
+ * Helper method for getting runtime {@link org.teiid.connector.metadata.runtime.Element} from a
+ * {@link org.teiid.connector.language.DerivedColumn}.
+ * @param symbol Input ISelectSymbol
+ * @return Element returned metadata runtime Element
+ */
+ private Column getElementFromSymbol(DerivedColumn symbol) throws ConnectorException {
+ ColumnReference expr = (ColumnReference) symbol.getExpression();
+ return expr.getMetadataObject();
+ }
+
+
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnection.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnection.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,29 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import javax.naming.NamingException;
+
+public interface LDAPConnection {
+ Object lookup(String context) throws NamingException;
+ void close();
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorCapabilities.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorCapabilities.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,82 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+/**
+ * This class extends the BasicConnectorCapabilities class, and establishes
+ * the capabilities that are supported by the LDAPConnector.
+ */
+public class LDAPConnectorCapabilities extends BasicConnectorCapabilities {
+
+ @Override
+ public int getMaxInCriteriaSize() {
+ return 1000;
+ }
+
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ public boolean supportsOrderBy() {
+ // Removed this support -- see LDAPSyncQueryExecution comments for details.
+ return false;
+ }
+
+ public boolean supportsRowLimit() {
+ // GHH 20080408 - turned this on, because I fixed issue
+ // in nextBatch that was causing this to fail
+ return true;
+ }
+
+ public boolean supportsRowOffset() {
+ // TODO This might actually be possible in future releases,
+ // when using virtual list views/Sun. note that this requires the ability
+ // to set the count limit, as well as an offset, so setCountLimit::searchControls
+ // won't do it alone.
+ return false;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorConstants.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorConstants.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPConnectorConstants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,38 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import javax.naming.directory.*;
+
+/**
+ * Utility class to maintain list of constants for the LDAPConnector.
+ * Please modify constants here; changes should be reflected throughout
+ * the connector code.
+ */
+public class LDAPConnectorConstants {
+
+ public static final String ldapDefaultSortName = "guid"; //$NON-NLS-1$
+ public static final int ldapDefaultSearchScope = SearchControls.ONELEVEL_SCOPE;
+ public static final boolean ldapDefaultIsAscending = true;
+
+ public static final String ldapTimestampFormat = "yyyyMMddhhmmss\'Z\'"; //$NON-NLS-1$
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPExecutionFactory.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,102 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.ConnectionFactory;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TranslatorProperty;
+import org.teiid.resource.cci.UpdateExecution;
+
+
+/**
+ * LDAPConnector. This is responsible for initializing
+ * a connection factory, and obtaining connections to LDAP.
+ */
+public class LDAPExecutionFactory extends BasicExecutionFactory {
+
+ private String searchDefaultBaseDN;
+ private boolean restrictToObjectClass = false;
+ private String searchDefaultScope = "SUBTREE_SCOPE"; //$NON-NLS-1$
+
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return LDAPConnectorCapabilities.class;
+ }
+
+ @TranslatorProperty(name="SearchDefaultBaseDN", display="Default Search Base DN", description="Default Base DN for LDAP Searches",advanced=true, defaultValue="")
+ public String getSearchDefaultBaseDN() {
+ return searchDefaultBaseDN;
+ }
+
+ public void setSearchDefaultBaseDN(String searchDefaultBaseDN) {
+ this.searchDefaultBaseDN = searchDefaultBaseDN;
+ }
+
+ @TranslatorProperty(name="RestrictToObjectClass", display="Restrict Searches To Named Object Class", description="Restrict Searches to objectClass named in the Name field for a table", advanced=true, defaultValue="false")
+ public boolean isRestrictToObjectClass() {
+ return restrictToObjectClass;
+ }
+
+ public void setRestrictToObjectClass(Boolean restrictToObjectClass) {
+ this.restrictToObjectClass = restrictToObjectClass.booleanValue();
+ }
+
+ @TranslatorProperty(name="SearchDefaultScope", display="Default Search Scope", description="Default Scope for LDAP Searches", allowed={"OBJECT_SCOPE","ONELEVEL_SCOPE","SUBTREE_SCOPE"},required=true, defaultValue="SUBTREE_SCOPE")
+ public String getSearchDefaultScope() {
+ return searchDefaultScope;
+ }
+
+ public void setSearchDefaultScope(String searchDefaultScope) {
+ this.searchDefaultScope = searchDefaultScope;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command,ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+ return new LDAPSyncQueryExecution((Select)command, this, (LDAPConnection)cf.getConnection());
+ } catch (ResourceException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public UpdateExecution createUpdateExecution(Command command,ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+ return new LDAPUpdateExecution(command, (LDAPConnection)cf.getConnection());
+ } catch (ResourceException e) {
+ throw new ConnectorException(e);
+ }
+ }
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPPlugin.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPPlugin.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.adapter.ldap;
+
+import java.util.ResourceBundle;
+
+import com.metamatrix.core.BundleUtil;
+
+/**
+ * LDAPPlugin
+ */
+public class LDAPPlugin {
+
+ public static final String PLUGIN_ID = "org.teiid.resource.adapter.ldap" ; //$NON-NLS-1$
+
+ /**
+ * Provides access to the plugin's log and to it's resources.
+ */
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID, PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSearchDetails.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSearchDetails.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSearchDetails.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,193 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.SearchControls;
+import javax.naming.ldap.SortKey;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
+
+
+/**
+ * Utility class used to maintain the details of a particular LDAP search,
+ * such as the context, the attributes of interest, the filter, and the
+ * search scope.
+ */
+public class LDAPSearchDetails {
+ private String contextName;
+ private int searchScope;
+ private String contextFilter;
+ private ArrayList attributeList;
+ private SortKey[] keys;
+// private LdapSortKey[] netscapeKeys;
+ // If limit is set to -1, this means no limit (return all rows)
+ private long limit;
+ private ArrayList elementList;
+
+ /**
+ * Constructor
+ * @param name the context name
+ * @param searchScope the search scope
+ * @param filter the context filter
+ * @param attributeList the list of attributes
+ * @param keys
+ * @param limit
+ * @param elementList
+ */
+ public LDAPSearchDetails(String name, int searchScope, String filter, ArrayList attributeList, SortKey[] keys, long limit, ArrayList elementList) {
+
+ this.contextName = name;
+ this.searchScope = searchScope;
+ this.contextFilter = filter;
+ this.attributeList = attributeList;
+ this.keys = keys;
+ this.limit = limit;
+ this.elementList = elementList;
+ }
+
+ /**
+ * get the context name
+ * @return the context name
+ */
+ public String getContextName() {
+ return contextName;
+ }
+
+ /**
+ * get the context name
+ * @return the context name
+ */
+ public int getSearchScope() {
+ return searchScope;
+ }
+
+ /**
+ * get the context filter
+ * @return the context filter
+ */
+ public String getContextFilter() {
+ return contextFilter;
+ }
+
+ /**
+ * get the attribute list
+ * @return the attribute list
+ */
+ public ArrayList getAttributeList() {
+ return attributeList;
+ }
+
+ /**
+ * get the element list
+ * @return the element list
+ */
+ public ArrayList getElementList() {
+ return elementList;
+ }
+
+ /**
+ * get the sort keys
+ * @return the sort keys
+ */
+ public SortKey[] getSortKeys() {
+ return keys;
+ }
+
+ /**
+ * get the count limit
+ * @return the count limit
+ */
+ public long getCountLimit() {
+ return limit;
+ }
+ /*
+ public LdapSortKey[] getNetscapeSortKeys() {
+ return netscapeKeys;
+ }
+ private void createNetscapeKeys() {
+ if(keys != null) {
+ netscapeKeys = new LdapSortKey[keys.length];
+ for(int i=0; i<keys.length; i++) {
+ LdapSortKey nKey = new LdapSortKey(keys[i].getAttributeID(),
+ keys[i].isAscending());
+ netscapeKeys[i] = nKey;
+ }
+ } else {
+ // set it null
+ netscapeKeys = null;
+ }
+ }
+ */
+
+ /**
+ * Print Method for Logging - (Detail level logging)
+ * @param logger the connector logger.
+ */
+ public void printDetailsToLog() throws NamingException {
+ // Log Search Scope
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Search context: " + contextName); //$NON-NLS-1$
+ if(searchScope == SearchControls.SUBTREE_SCOPE) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Search scope = SUBTREE_SCOPE"); //$NON-NLS-1$
+ } else if(searchScope == SearchControls.OBJECT_SCOPE) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Search scope = OBJECT_SCOPE"); //$NON-NLS-1$
+ } else if(searchScope == SearchControls.ONELEVEL_SCOPE) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Search scope = ONELEVEL_SCOPE"); //$NON-NLS-1$
+ }
+
+ // Log Search Attributes
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Search attributes: "); //$NON-NLS-1$
+ Iterator itr = this.attributeList.iterator();
+ int i = 0;
+ while(itr.hasNext()) {
+ Attribute attr = (Attribute)itr.next();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Attribute [" + i + "]: " + attr.getID() + " (" +attr.get().toString() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ i++;
+ }
+
+ // Log Context Filter
+ if(contextFilter != null && (!contextFilter.equals(""))) { //$NON-NLS-1$
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Where clause was translated into Ldap search filter: " + contextFilter); //$NON-NLS-1$
+ }
+
+ // Log Sort Keys
+ if(keys != null) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"Sort keys: "); //$NON-NLS-1$
+ for(int j=0; j<keys.length; j++) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"\tName: " + keys[j].getAttributeID()); //$NON-NLS-1$
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"\tOrder: "); //$NON-NLS-1$
+ if(keys[j].isAscending()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"ASC"); //$NON-NLS-1$
+ } else {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR,"DESC"); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSyncQueryExecution.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSyncQueryExecution.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPSyncQueryExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,487 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+/**
+ *
+ * Please see the user's guide for a full description of capabilties, etc.
+ *
+ * Description/Assumptions:
+ * 1. Table's name in source defines the base DN (or context) for the search.
+ * Example: Table.NameInSource=ou=people,dc=gene,dc=com
+ * [Optional] The table's name in source can also define a search scope. Append
+ * a "?" character as a delimiter to the base DN, and add the search scope string.
+ * The following scopes are available:
+ * SUBTREE_SCOPE
+ * ONELEVEL_SCOPE
+ * OBJECT_SCOPE
+ * [Default] LDAPConnectorConstants.ldapDefaultSearchScope
+ * is the default scope used, if no scope is defined (currently, ONELEVEL_SCOPE).
+ *
+ * 2. Column's name in source defines the LDAP attribute name.
+ * [Default] If no name in source is defined, then we attempt to use the column name
+ * as the LDAP attribute name.
+ *
+ *
+ * TODO: Implement paged searches -- the LDAP server must support VirtualListViews.
+ * TODO: Implement cancel.
+ * TODO: Add Sun/Netscape implementation, AD/OpenLDAP implementation.
+ *
+ *
+ * Note:
+ * Greater than is treated as >=
+ * Less-than is treater as <=
+ * If an LDAP entry has more than one entry for an attribute of interest (e.g. a select item), we only return the
+ * first occurrance. The first occurance is not predictably the same each time, either, according to the LDAP spec.
+ * If an attribute is not present, we return the empty string. Arguably, we could throw an exception.
+ *
+ * Sun LDAP won't support Sort Orders for very large datasets. So, we've set the sorting to NONCRITICAL, which
+ * allows Sun to ignore the sort order. This will result in the results to come back as unsorted, without any error.
+ *
+ * Removed support for ORDER BY for two reasons:
+ * 1: LDAP appears to have a limit to the number of records that
+ * can be server-side sorted. When the limit is reached, two things can happen:
+ * a. If sortControl is set to CRITICAL, then the search fails.
+ * b. If sortControl is NONCRITICAL, then the search returns, unsorted.
+ * We'd like to support ORDER BY, no matter how large the size, so we turn it off,
+ * and allow MetaMatrix to do it for us.
+ * 2: Supporting ORDER BY appears to negatively effect the query plan
+ * when cost analysis is used. We stop using dependent queries, and start
+ * using inner joins.
+ *
+ */
+
+package org.teiid.resource.adapter.ldap;
+
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.SizeLimitExceededException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.Control;
+import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.SortControl;
+import javax.naming.ldap.SortKey;
+
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.ResultSetExecution;
+
+
+
+/**
+ * LDAPSyncQueryExecution is responsible for executing an LDAP search
+ * corresponding to a read-only "select" query from MetaMatrix.
+ */
+public class LDAPSyncQueryExecution extends BasicExecution implements ResultSetExecution {
+
+ private LDAPSearchDetails searchDetails;
+ private LDAPConnection ldapConnection;
+ private LdapContext ldapCtx;
+ private NamingEnumeration searchEnumeration;
+ private IQueryToLdapSearchParser parser;
+ private Select query;
+ private LDAPExecutionFactory executionFactory;
+
+ /**
+ * Constructor
+ * @param executionMode the execution mode.
+ * @param ctx the execution context.
+ * @param rm the runtimeMetadata
+ * @param logger the ConnectorLogger
+ * @param ldapCtx the LDAP Context
+ */
+ public LDAPSyncQueryExecution(Select query, LDAPExecutionFactory factory, LDAPConnection ldapCtx) {
+ this.ldapConnection = ldapCtx;
+ this.query = query;
+ this.executionFactory = factory;
+ }
+
+ /**
+ * method to execute the supplied query
+ * @param query the query object.
+ * @param maxBatchSize the max batch size.
+ */
+ @Override
+ public void execute() throws ConnectorException {
+ // Parse the IQuery, and translate it into an appropriate LDAP search.
+ this.parser = new IQueryToLdapSearchParser(this.executionFactory);
+ searchDetails = parser.translateSQLQueryToLDAPSearch(query);
+
+ // Create and configure the new search context.
+ createSearchContext();
+ SearchControls ctrls = setSearchControls();
+ setStandardRequestControls();
+ // Execute the search.
+ executeSearch(ctrls);
+ }
+
+ /**
+ * Set the standard request controls
+ */
+ private void setStandardRequestControls() throws ConnectorException {
+ Control[] sortCtrl = new Control[1];
+ SortKey[] keys = searchDetails.getSortKeys();
+ if (keys != null) {
+ try {
+ sortCtrl[0] = new SortControl(keys, Control.NONCRITICAL);
+ this.ldapCtx.setRequestControls(sortCtrl);
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Sort ordering was requested, and sort control was created successfully."); //$NON-NLS-1$
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError") + //$NON-NLS-1$
+ " : "+ne.getExplanation(); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ } catch(IOException e) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError"); //$NON-NLS-1$
+ throw new ConnectorException(e,msg);
+ }
+ }
+ }
+
+ /**
+ * Perform a lookup against the initial LDAP context, which
+ * sets the context to something appropriate for the search that is about to occur.
+ *
+ */
+ private void createSearchContext() throws ConnectorException {
+ try {
+ ldapCtx = (LdapContext) this.ldapConnection.lookup(searchDetails.getContextName());
+ } catch (NamingException ne) {
+ if (searchDetails.getContextName() != null) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Attempted to search context: " //$NON-NLS-1$
+ + searchDetails.getContextName());
+ }
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.createContextError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ }
+
+
+ /**
+ * Set the search controls
+ */
+ private SearchControls setSearchControls() throws ConnectorException {
+ SearchControls ctrls = new SearchControls();
+ //ArrayList modelAttrList = searchDetails.getAttributeList();
+ ArrayList modelAttrList = searchDetails.getElementList();
+ String[] attrs = new String[modelAttrList.size()];
+ Iterator itr = modelAttrList.iterator();
+ int i = 0;
+ while(itr.hasNext()) {
+ attrs[i] = (parser.getNameFromElement((Column)itr.next()));
+ //attrs[i] = (((Attribute)itr.next()).getID();
+ //logger.logTrace("Adding attribute named " + attrs[i] + " to the search list.");
+ i++;
+ }
+
+ ctrls.setSearchScope(searchDetails.getSearchScope());
+ ctrls.setReturningAttributes(attrs);
+
+ long limit = searchDetails.getCountLimit();
+ if(limit != -1) {
+ ctrls.setCountLimit(limit);
+ }
+ return ctrls;
+ }
+
+ /**
+ * Perform the LDAP search against the subcontext, using the filter and
+ * search controls appropriate to the query and model metadata.
+ */
+ private void executeSearch(SearchControls ctrls) throws ConnectorException {
+ String ctxName = searchDetails.getContextName();
+ String filter = searchDetails.getContextFilter();
+ if (ctxName == null || filter == null || ctrls == null) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Search context, filter, or controls were null. Cannot execute search."); //$NON-NLS-1$
+ }
+ try {
+ searchEnumeration = this.ldapCtx.search("", filter, ctrls); //$NON-NLS-1$
+ } catch (NamingException ne) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "LDAP search failed. Attempted to search context " //$NON-NLS-1$
+ + ctxName + " using filter " + filter); //$NON-NLS-1$
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
+ throw new ConnectorException(msg + " : " + ne.getExplanation()); //$NON-NLS-1$
+ } catch(Exception e) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "LDAP search failed. Attempted to search context " //$NON-NLS-1$
+ + ctxName + " using filter " + filter); //$NON-NLS-1$
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
+ throw new ConnectorException(e, msg);
+ }
+ }
+
+ // GHH 20080326 - attempt to implement cancel here. First try to
+ // close the searchEnumeration, then the search context.
+ // We are very conservative when closing the enumeration
+ // but less so when closing context, since it is safe to call close
+ // on contexts multiple times
+ @Override
+ public void cancel() throws ConnectorException {
+ close();
+ }
+
+ // GHH 20080326 - replaced existing implementation with the same
+ // code as used by cancel method. First try to
+ // close the searchEnumeration, then the search context
+ // We are very conservative when closing the enumeration
+ // but less so when closing context, since it is safe to call close
+ // on contexts multiple times
+ @Override
+ public void close() throws ConnectorException {
+ if (searchEnumeration != null) {
+ try {
+ searchEnumeration.close();
+ } catch (Exception e) { } // catch everything, because NamingEnumeration has undefined behavior if it previously hit an exception
+ }
+ if (ldapCtx != null) {
+ try {
+ ldapCtx.close();
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.closeContextError",ne.getExplanation()); //$NON-NLS-1$
+ LogManager.logError(LogConstants.CTX_CONNECTOR, msg);
+ }
+ }
+ }
+
+ /**
+ * Fetch the next batch of data from the LDAP searchEnumerationr result.
+ * @return the next Batch of results.
+ */
+ // GHH 20080326 - set all batches as last batch after an exception
+ // is thrown calling a method on the enumeration. Per Javadoc for
+ // javax.naming.NamingEnumeration, enumeration is invalid after an
+ // exception is thrown - by setting last batch indicator we prevent
+ // it from being used again.
+ // GHH 20080326 - also added return of explanation for generic
+ // NamingException
+ public List next() throws ConnectorException {
+ try {
+ // The search has been executed, so process up to one batch of
+ // results.
+ List result = null;
+ while (result == null && searchEnumeration != null && searchEnumeration.hasMore())
+ {
+ SearchResult searchResult = (SearchResult) searchEnumeration.next();
+ result = getRow(searchResult);
+ }
+
+ return result;
+ } catch (SizeLimitExceededException e) {
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, "Search results exceeded size limit. Results may be incomplete."); //$NON-NLS-1$
+ searchEnumeration = null; // GHH 20080326 - NamingEnumartion's are no longer good after an exception so toss it
+ return null; // GHH 20080326 - if size limit exceeded don't try to read more results
+ } catch (NamingException ne) {
+ final String msg = "Ldap error while processing next batch of results: " + ne.getExplanation(); //$NON-NLS-1$
+ LogManager.logError(LogConstants.CTX_CONNECTOR, msg); // GHH 20080326 - changed to output explanation from LDAP server
+ searchEnumeration = null; // GHH 20080326 - NamingEnumertion's are no longer good after an exception so toss it
+ throw new ConnectorException(msg);
+ }
+ }
+
+ /**
+ * Create a row using the searchResult and add it to the supplied batch.
+ * @param batch the supplied batch
+ * @param result the search result
+ */
+ // GHH 20080326 - added fetching of DN of result, for directories that
+ // do not include it as an attribute
+ private List getRow(SearchResult result) throws ConnectorException {
+ Attributes attrs = result.getAttributes();
+ String resultDN = result.getNameInNamespace(); // added GHH 20080326
+ ArrayList attributeList = searchDetails.getElementList();
+ List row = new ArrayList();
+
+ if (attrs != null && attrs.size()>0) {
+ Iterator itr = attributeList.iterator();
+ while(itr.hasNext()) {
+ addResultToRow((Column)itr.next(), resultDN, attrs, row); // GHH 20080326 - added resultDN parameter to call
+ }
+ return row;
+ }
+ return null;
+ }
+
+ /**
+ * Add Result to Row
+ * @param modelElement the model element
+ * @param attrs the attributes
+ * @param row the row
+ */
+ // GHH 20080326 - added resultDistinguishedName to method signature. If
+ // there is an element in the model named "DN" and there is no attribute
+ // with this name in the search result, we return this new parameter
+ // value for that column in the result
+ // GHH 20080326 - added handling of ClassCastException when non-string
+ // attribute is returned
+ private void addResultToRow(Column modelElement, String resultDistinguishedName, Attributes attrs, List row) throws ConnectorException {
+
+ String strResult;
+ String modelAttrName = parser.getNameFromElement(modelElement);
+ Class modelAttrClass = modelElement.getJavaType();
+ if(modelAttrName == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.nullAttrError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+
+ Attribute resultAttr = attrs.get(modelAttrName);
+
+ // If the attribute is not present, we return NULL.
+ if(resultAttr == null) {
+ // MPW - 2-20-07 - Changed from returning empty string to returning null.
+ //row.add("");
+ //logger.logTrace("Did not find a match for attribute named: " + modelAttrName);
+ // GHH 20080326 - return DN from input parameter
+ // if DN attribute is not present in search result
+ if (modelAttrName.toUpperCase().equals("DN")) { //$NON-NLS-1$
+ row.add(resultDistinguishedName);
+ }
+ else {
+ row.add(null);
+ }
+ return;
+ }
+ // TODO: Currently, if an LDAP entry contains more than one matching
+ // attribute, we only return the first.
+ // Since attribute order is not guaranteed, this means that we may not
+ // always return the exact same information.
+ // Putting multi-valued attributes into a single row (or multiple rows) requires
+ // some design decisions.
+ // GHH 20080326 - first get attribute as generic object
+ // so we can check to make sure it is a string separately - previously it was just put straight into a string.
+ Object objResult = null;
+ try {
+ objResult = resultAttr.get();
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.attrValueFetchError",modelAttrName); //$NON-NLS-1$
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, msg+" : "+ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg+" : "+ne.getExplanation()); //$NON-NLS-1$
+ }
+
+ // GHH 20080326 - if attribute is not a string, just
+ // return an empty string.
+ // TODO - allow return of non-strings (always byte[]) as
+ // MM object. Perhaps also add directory-specific logic
+ // to deserialize byte[] attributes into Java objects
+ // when appropriate
+ try {
+ strResult = (String)objResult;
+ } catch (ClassCastException cce) {
+ strResult = ""; //$NON-NLS-1$
+ }
+
+ // MPW - 3.9.07 - Also return NULL when attribute is unset or empty string.
+ // There is no way to differentiate between being unset and being the empty string.
+ if(strResult.equals("")) { //$NON-NLS-1$
+ strResult = null;
+ }
+
+ // MPW: 3-11-07: Added support for java.lang.Integer conversion.
+ try {
+ if(modelAttrClass.equals(Class.forName(Integer.class.getName()))) {
+ try {
+ // Throw an exception if class cast fails.
+ if(strResult != null) {
+ Integer intResult = new Integer(strResult);
+ row.add(intResult);
+ } else {
+ row.add(null);
+ }
+ } catch(NumberFormatException nfe) {
+ throw new ConnectorException(nfe, "Element " + modelAttrName + " is typed as Integer, " + //$NON-NLS-1$ //$NON-NLS-2$
+ "but it's value (" + strResult + ") cannot be converted from string " + //$NON-NLS-1$ //$NON-NLS-2$
+ "to Integer. Please change type to String, or modify the data."); //$NON-NLS-1$
+ }
+ // java.lang.String
+ } else if(modelAttrClass.equals(Class.forName(String.class.getName()))) {
+ row.add(strResult);
+ // java.sql.Timestamp
+ } else if(modelAttrClass.equals(Class.forName(java.sql.Timestamp.class.getName()))) {
+ Map<String, String> p = modelElement.getProperties();
+
+ String timestampFormat = p.get("Format"); //$NON-NLS-1$
+ SimpleDateFormat dateFormat;
+ if(timestampFormat == null) {
+ timestampFormat = LDAPConnectorConstants.ldapTimestampFormat;
+
+ }
+ dateFormat = new SimpleDateFormat(timestampFormat);
+ try {
+ if(strResult != null) {
+ Date dateResult = dateFormat.parse(strResult);
+ Timestamp tsResult = new Timestamp(dateResult.getTime());
+ row.add(tsResult);
+ } else {
+ row.add(null);
+ }
+ } catch(ParseException pe) {
+ throw new ConnectorException(pe, "Timestamp could not be parsed. Please check to ensure the " //$NON-NLS-1$
+ + " Format field for attribute " //$NON-NLS-1$
+ + modelAttrName + " is configured using SimpleDateFormat conventions."); //$NON-NLS-1$
+ }
+
+ // TODO: Extend support for more types in the future.
+ // Specifically, add support for byte arrays, since that's actually supported
+ // in the underlying data source.
+ } else {
+ throw new ConnectorException("Base type " + modelAttrClass.toString() //$NON-NLS-1$
+ + " is not supported in the LDAP connector. " //$NON-NLS-1$
+ + " Please modify the base model to use a supported type."); //$NON-NLS-1$
+ }
+ } catch(ClassNotFoundException cne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.supportedClassNotFoundError"); //$NON-NLS-1$
+ throw new ConnectorException(cne, msg);
+ }
+ }
+
+
+ /**
+ * Active Directory and OpenLDAP supports PagedResultsControls, so I left
+ * this method in here in case we decide to extend support for this control
+ * in the future.
+ */
+// private void setADRequestControls(int maxBatchSize) {
+// try {
+// ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(
+// maxBatchSize, Control.CRITICAL) });
+// } catch (NamingException ne) {
+// logger.logError("Failed to set page size for LDAP results. Please ensure that paged results controls are supported by the LDAP server implementation."); //$NON-NLS-1$
+// ne.printStackTrace();
+// } catch (IOException ioe) {
+// logger.logError("IO Exception while setting paged results control."); //$NON-NLS-1$
+// ioe.printStackTrace();
+// }
+// }
+}
Added: trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPUpdateExecution.java
===================================================================
--- trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPUpdateExecution.java (rev 0)
+++ trunk/connectors/translator-ldap/src/main/java/org/teiid/resource/adapter/ldap/LDAPUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,450 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import java.util.List;
+
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.BasicAttributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.ModificationItem;
+import javax.naming.ldap.LdapContext;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.Condition;
+import org.teiid.connector.language.Delete;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.ExpressionValueSource;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SetClause;
+import org.teiid.connector.language.Update;
+import org.teiid.connector.language.Comparison.Operator;
+import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.UpdateExecution;
+
+
+
+/**
+ * Please see the user's guide for a full description of capabilties, etc.
+ *
+ * Description/Assumptions:
+ * 1. Table's name in source defines the base DN (or context) for the search.
+ * Example: Table.NameInSource=ou=people,dc=gene,dc=com
+ * 2. Column's name in source defines the LDAP attribute name.
+ * [Default] If no name in source is defined, then we attempt to use the column name
+ * as the LDAP attribute name.
+ * 3. Since all of the underlying LDAP methods for adding/deleting/updating
+ * require specification of the LDAP distinguished name (DN) to change, for all
+ * corresponding MetaMatrix operations the DN must be specified (as the sole
+ * item in the WHERE clause for UPDATE and DELETE operations, and in the list
+ * of attributes to assign values in an INSERT operation * Responsible for update/insert/delete operations against LDAP
+ */
+public class LDAPUpdateExecution extends BasicExecution implements UpdateExecution {
+ private LDAPConnection ldapConnection;
+ private LdapContext ldapCtx;
+ private Command command;
+
+ public LDAPUpdateExecution(Command command, LDAPConnection ldapCtx) {
+ this.ldapConnection = ldapCtx;
+ this.command = command;
+ }
+
+ /** execute generic update-class (either an update, delete, or insert)
+ * operation and returns a count of affected rows. Since underlying
+ * LDAP operations (and this connector) can modify at most one LDAP
+ * leaf context at a time, this will always return 1. It will never
+ * actually return 0, because if an operation fails, a
+ * ConnectorException will be thrown instead.
+ * Note that really it should return 0 if a delete is performed on
+ * an entry that doesn't exist (but whose parent does exist), but
+ * since the underlying LDAP operation will return success for such a
+ * delete, we just blindly return 1. To return 0 would mean performing
+ * a search for the entry first before deleting it (to confirm that it
+ * did exist prior to the delete), so right now we sacrifice accuracy
+ * here for the sake of efficiency.
+ */
+ @Override
+ public void execute() throws ConnectorException {
+ // first make a copy of the initial LDAP context we got from
+ // the connection. The actual update-class operation will use
+ // this copy. This will enable the close and cancel methods
+ // to stop any LDAP operations we are making by calling the
+ // close() method of the copy context, without closing our
+ // real connection to the LDAP server
+ try {
+ ldapCtx = (LdapContext)this.ldapConnection.lookup(""); //$NON-NLS-1$
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.createContextError",ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+
+ if (command instanceof Update) {
+ executeUpdate();
+ }
+ else if (command instanceof Delete) {
+ executeDelete();
+ }
+ else if (command instanceof Insert) {
+ executeInsert();
+ }
+ else {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.incorrectCommandError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ }
+
+ @Override
+ public int[] getUpdateCounts() throws DataNotAvailableException,
+ ConnectorException {
+ return new int[] {1};
+ }
+
+
+ // Private method to actually do an insert operation. Per JNDI doc at
+ // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html, JNDI method to add new entry to LDAP that does not contain a Java object is
+ // DirContext.createSubContext(), so that is what is used here.
+ //
+ // The insert must include an element named "DN" (case insensitive)
+ // which will be the fully qualified LDAP distinguished name of the
+ // entry to add.
+ //
+ // Also, while we make no effort to prevent insert operations that
+ // break these rules, the underlying LDAP operation will fail (and
+ // pass back an explanatory message, which we will return in a
+ // ConnectorException, in the following cases:
+ // -if the parent context for this entry does not exist in the directory
+ // -if the insert does not specify values for all required attributes
+ // of the class. Since objectClass is required for all LDAP entries,
+ // if it is not specified this condition will apply - and once it is
+ // specified then all of the other required attributes for that
+ // objectClass will of course also be required.
+ //
+ // Just as with the read support in the LDAPSyncQueryExecution class,
+ // multi-value attributes are not supported by this implementation.
+ //
+ // TODO - maybe automatically specify objectClass based off of
+ // Name/NameInSource RESTRICT property settings, like with read support
+ private void executeInsert()
+ throws ConnectorException {
+
+ List<ColumnReference> insertElementList = ((Insert)command).getColumns();
+ List<Expression> insertValueList = ((ExpressionValueSource)((Insert)command).getValueSource()).getValues();
+ // create a new attribute list with case ignored in attribute
+ // names
+ Attributes insertAttrs = new BasicAttributes(true);
+ Attribute insertAttr; // what we will use to populate the attribute list
+ ColumnReference insertElement;
+ String nameInsertElement;
+ Object insertValue;
+ String distinguishedName = null;
+ // The IInsert interface uses separate List objects for
+ // the element names and values to be inserted, limiting
+ // the potential for code reuse in reading them (since all
+ // other interfaces use ICriteria-based mechanisms for such
+ // input).
+ for (int i=0; i < insertElementList.size(); i++) {
+ insertElement = insertElementList.get(i);
+ // call utility class to get NameInSource/Name of element
+ nameInsertElement = getNameFromElement(insertElement);
+ // special handling for DN attribute - use it to set
+ // distinguishedName value.
+ if (nameInsertElement.toUpperCase().equals("DN")) { //$NON-NLS-1$
+ insertValue = ((Literal)insertValueList.get(i)).getValue();
+ if (insertValue == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.columnSourceNameDNNullError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ if (!(insertValue instanceof java.lang.String)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.columnSourceNameDNTypeError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ distinguishedName = (String)insertValue;
+ }
+ // for other attributes specified in the insert command,
+ // create a new
+ else {
+ insertAttr = new BasicAttribute(nameInsertElement);
+ insertValue = ((Literal)insertValueList.get(i)).getValue();
+ insertAttr.add(insertValue);
+ insertAttrs.put(insertAttr);
+ }
+ }
+ // if the DN is not specified, we don't know enough to attempt
+ // the LDAP add operation, so throw an exception
+ if (distinguishedName == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.noInsertSourceNameDNError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ // just try to create a new LDAP entry using the DN and
+ // attributes specified in the INSERT operation. If it isn't
+ // legal, we'll get a NamingException back, whose explanation
+ // we'll return in a ConnectorException
+ try {
+ ldapCtx.createSubcontext(distinguishedName, insertAttrs);
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.insertFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ } catch (Exception e) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.insertFailedUnexpected",distinguishedName); //$NON-NLS-1$
+ throw new ConnectorException(e, msg);
+ }
+ }
+
+ // Private method to actually do a delete operation. Per JNDI doc at
+ // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html,
+ // a good JNDI method to delete an entry to LDAP is
+ // DirContext.destroySubContext(), so that is what is used here.
+ //
+ // The delete criteria must include only an equals comparison
+ // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
+ // Note that the underlying LDAP operations here return successfully
+ // even if the named entry doesn't exist (as long as its parent does
+ // exist).
+ private void executeDelete()
+ throws ConnectorException {
+
+ Condition criteria = ((Delete)command).getWhere();
+
+ // since we have the exact same processing rules for criteria
+ // for updates and deletes, we use a common private method to do this.
+ // note that this private method will throw a ConnectorException
+ // for illegal criteria, which we deliberately don't catch
+ // so it gets passed on as is.
+ String distinguishedName = getDNFromCriteria(criteria);
+
+ // just try to delete an LDAP entry using the DN
+ // specified in the DELETE operation. If it isn't
+ // legal, we'll get a NamingException back, whose explanation
+ // we'll return in a ConnectorException
+ try {
+ ldapCtx.destroySubcontext(distinguishedName);
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.deleteFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ // don't remember why I added this generic catch of Exception,
+ // but it does no harm...
+ } catch (Exception e) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.deleteFailedUnexpected",distinguishedName); //$NON-NLS-1$
+ throw new ConnectorException(e, msg);
+ }
+ }
+
+ // Private method to actually do an update operation. Per JNDI doc at
+ // http://java.sun.com/products/jndi/tutorial/ldap/models/operations.html,
+ // the JNDI method to use to update an entry to LDAP is one of the
+ // DirContext.modifyAttributes() methods that takes ModificationItem[]
+ // as a parameter, so that is what is used here.
+ // Note that this method does not allow for changing of the DN - to
+ // implement that we would need to use Context.rename(). Since right
+ // now we only call modifyAttributes(), and don't check for the DN
+ // in the list of updates, we will attempt to update the DN using
+ // modifyAttributes(), and let the LDAP server fail the request (and
+ // send us the explanation for the failure, which is returned in
+ // a ConnectorException)
+ //
+ // The update criteria must include only an equals comparison
+ // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
+ private void executeUpdate()
+ throws ConnectorException {
+
+ List<SetClause> updateList = ((Update)command).getChanges();
+ Condition criteria = ((Update)command).getWhere();
+
+ // since we have the exact same processing rules for criteria
+ // for updates and deletes, we use a common private method to do this.
+ // note that this private method will throw a ConnectorException
+ // for illegal criteria, which we deliberately don't catch
+ // so it gets passed on as is.
+ String distinguishedName = getDNFromCriteria(criteria);
+
+
+ // this will be the list of modifications to attempt. Since
+ // we currently blindly try all the updates the query
+ // specifies, right now this is the same size as the updateList.
+ // When we start filtering out DN changes (which would need to
+ // be performed separately using Context.rename()), we will
+ // need to account for this in determining this list size.
+ ModificationItem[] updateMods = new ModificationItem[updateList.size()];
+ ColumnReference leftElement;
+ Expression rightExpr;
+ String nameLeftElement;
+ Object valueRightExpr;
+ // iterate through the supplied list of updates (each of
+ // which is an ICompareCriteria with an IElement on the left
+ // side and an IExpression on the right, per the Connector
+ // API).
+ for (int i=0; i < updateList.size(); i++) {
+ SetClause setClause = updateList.get(i);
+ // trust that connector API is right and left side
+ // will always be an IElement
+ leftElement = setClause.getSymbol();
+ // call utility method to get NameInSource/Name for element
+ nameLeftElement = getNameFromElement(leftElement);
+ // get right expression - if it is not a literal we
+ // can't handle that so throw an exception
+ rightExpr = setClause.getValue();
+ if (!(rightExpr instanceof Literal)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.valueNotLiteralError",nameLeftElement); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ valueRightExpr = ((Literal)rightExpr).getValue();
+ // add in the modification as a replacement - meaning
+ // any existing value(s) for this attribute will
+ // be replaced by the new value. If the attribute
+ // didn't exist, it will automatically be created
+ // TODO - since null is a valid attribute
+ // value, we don't do any special handling of it right
+ // now. But maybe null should mean to delete an
+ // attribute?
+ updateMods[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(nameLeftElement, valueRightExpr));
+ }
+ // just try to update an LDAP entry using the DN and
+ // attributes specified in the UPDATE operation. If it isn't
+ // legal, we'll get a NamingException back, whose explanation
+ // we'll return in a ConnectorException
+ try {
+ ldapCtx.modifyAttributes(distinguishedName, updateMods);
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.updateFailed",distinguishedName,ne.getExplanation()); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ // don't remember why I added this generic catch of Exception,
+ // but it does no harm...
+ } catch (Exception e) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.updateFailedUnexpected",distinguishedName); //$NON-NLS-1$
+ throw new ConnectorException(e, msg);
+ }
+ }
+
+ // private method for extracting the distinguished name from
+ // the criteria, which must include only an equals comparison
+ // on the "DN" column ("WHERE DN='cn=John Doe,ou=people,dc=company,dc=com'")
+ // most of this code is to check the criteria to make sure it is in
+ // this form and throw an appropriate exception if it is not
+ // since there is no way to specify this granularity of criteria
+ // right now in the connector capabilities
+ private String getDNFromCriteria(Condition criteria)
+ throws ConnectorException {
+ if (criteria == null) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaEmptyError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ if (!(criteria instanceof Comparison)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaNotSimpleError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ Comparison compareCriteria = (Comparison)criteria;
+ if (compareCriteria.getOperator() != Operator.EQ) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaNotEqualsError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ Expression leftExpr = compareCriteria.getLeftExpression();
+ if (!(leftExpr instanceof ColumnReference)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaLHSNotElementError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ // call utility method to get NameInSource/Name for element
+ String nameLeftExpr = getNameFromElement((ColumnReference)leftExpr);
+ if (!(nameLeftExpr.toUpperCase().equals("DN"))) { //$NON-NLS-1$
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaSrcColumnError",nameLeftExpr); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ Expression rightExpr = compareCriteria.getRightExpression();
+ if (!(rightExpr instanceof Literal)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaRHSNotLiteralError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ Object valueRightExpr = ((Literal)rightExpr).getValue();
+ if (!(valueRightExpr instanceof java.lang.String)) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.criteriaRHSNotStringError"); //$NON-NLS-1$
+ throw new ConnectorException(msg);
+ }
+ return (String)valueRightExpr;
+ }
+
+ // This is an exact copy of the method with the same name in
+ // IQueryToLdapSearchParser - really should be in a utility class
+ private String getNameFromElement(ColumnReference e) {
+ String ldapAttributeName = null;
+ String elementNameDirect = e.getName();
+ if (elementNameDirect == null) {
+ } else {
+ }
+ AbstractMetadataRecord mdObject = e.getMetadataObject();
+ if (mdObject == null) {
+ return ""; //$NON-NLS-1$
+ }
+ ldapAttributeName = mdObject.getNameInSource();
+ if(ldapAttributeName == null || ldapAttributeName.equals("")) { //$NON-NLS-1$
+ ldapAttributeName = mdObject.getName();
+ // If name in source is not set, then fall back to the column name.
+ }
+ return ldapAttributeName;
+ }
+
+
+ // cancel here by closing the copy of the ldap context (if it was
+ // initialized, which is only true if execute() was previously called)
+ // calling close on already closed context is safe per
+ // javax.naming.Context javadoc so we won't worry about this also
+ // happening in our close method
+ public void cancel() throws ConnectorException {
+ close();
+ }
+
+ // close here by closing the copy of the ldap context (if it was
+ // initialized, which is only true if execute() was previously called)
+ // calling close on already closed context is safe per
+ // javax.naming.Context javadoc so we won't worry about this also
+ // happening in our close method
+ public void close() throws ConnectorException {
+ try {
+ if(ldapCtx != null) {
+ ldapCtx.close();
+ }
+ } catch (NamingException ne) {
+ final String msg = LDAPPlugin.Util.getString("LDAPUpdateExecution.closeContextError",ne.getExplanation()); //$NON-NLS-1$
+ LogManager.logError(LogConstants.CTX_CONNECTOR,msg);
+ }
+ }
+
+}
+
+
+
+
+
+
+
+
+
+
Added: trunk/connectors/translator-ldap/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-ldap/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-ldap/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.ldap.LDAPExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/translator-ldap/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/ldap/i18n.properties
===================================================================
--- trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/ldap/i18n.properties (rev 0)
+++ trunk/connectors/translator-ldap/src/main/resources/org/teiid/resource/adapter/ldap/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,37 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+#
+LDAPConnection.urlPropNotFound=Ldap URL property not found.
+LDAPConnection.adminUserDNPropNotFound=Ldap Admin User DN property not found.
+LDAPConnection.adminUserPassPropNotFound=Ldap Admin password property not found.
+LDAPConnection.maxCriteriaParseError=Ldap Max Criteria property has an invalid format.
+LDAPConnection.maxCriteriaPropNotFound=Ldap Max Criteria property not found.
+LDAPConnection.contextInitFailed=LDAP context initialization failed. Please check connector properties, and verify against LDAP server.
+LDAPConnection.propertyFileParseFailed=The Properties file could not be parsed.
+LDAPConnection.directoryNamingError=Initializing LDAP directory context failed. Please check LDAP connection properties, including username and password: {0}
+LDAPConnection.directoryInitError=Initializing LDAP directory context failed.
+LDAPConnection.unsupportedExecMode=LDAPConnector does not support requested execution mode.
+LDAPConnection.contextCloseError=The Connection failed to close LDAP context: {0}
+#
+ILDAPSourceConnectionFactory.creatingConnection=LDAPSourceConnectionFactory is creating a new connection.
+
Added: trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/ldap/TestIQueryToLdapSearchParser.java
===================================================================
--- trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/ldap/TestIQueryToLdapSearchParser.java (rev 0)
+++ trunk/connectors/translator-ldap/src/test/java/org/teiid/resource/adapter/ldap/TestIQueryToLdapSearchParser.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,309 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.ldap;
+
+import static org.mockito.Mockito.mock;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.naming.directory.Attribute;
+import javax.naming.directory.SearchControls;
+import javax.naming.ldap.SortKey;
+
+import junit.framework.TestCase;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.MetadataStore;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Schema;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.connector.metadata.runtime.Column.SearchType;
+import org.teiid.dqp.internal.datamgr.metadata.RuntimeMetadataImpl;
+import org.teiid.metadata.CompositeMetadataStore;
+import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.ldap.IQueryToLdapSearchParser;
+import org.teiid.resource.adapter.ldap.LDAPExecutionFactory;
+import org.teiid.resource.adapter.ldap.LDAPSearchDetails;
+
+import com.metamatrix.cdk.CommandBuilder;
+import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.query.metadata.QueryMetadataInterface;
+import com.metamatrix.query.unittest.RealMetadataFactory;
+
+/**
+ * Test IQueryToLdapSearchParser.
+ */
+/**
+ * @author mdrilling
+ *
+ */
+public class TestIQueryToLdapSearchParser extends TestCase {
+
+ public TestIQueryToLdapSearchParser(String name) {
+ super(name);
+ }
+
+ /**
+ * Get Resolved Command using SQL String and metadata.
+ */
+ public Command getCommand(String sql, QueryMetadataInterface metadata) {
+ CommandBuilder builder = new CommandBuilder(metadata);
+ return builder.getCommand(sql);
+ }
+
+ /**
+ * Helper method for testing the provided LDAPSearchDetails against expected values
+ * @param searchDetails the LDAPSearchDetails object
+ * @param expectedContextName the expected context name
+ * @param expectedContextFilter the expected context filter string
+ * @param expectedAttrNameList list of expected attribute names
+ * @param expectedCountLimit the expected count limit
+ * @param expectedSearchScope the expected search scope
+ * @param expectedSortKeys the expected sortKeys list.
+ */
+ public void helpTestSearchDetails(final LDAPSearchDetails searchDetails, final String expectedContextName,
+ final String expectedContextFilter, final List expectedAttrNameList, final long expectedCountLimit,
+ final int expectedSearchScope, final SortKey[] expectedSortKeys) {
+
+ // Get all of the actual values
+ String contextName = searchDetails.getContextName();
+ String contextFilter = searchDetails.getContextFilter();
+ List attrList = searchDetails.getAttributeList();
+ long countLimit = searchDetails.getCountLimit();
+ int searchScope = searchDetails.getSearchScope();
+ SortKey[] sortKeys = searchDetails.getSortKeys();
+
+ // Compare actual with Expected
+ assertEquals(expectedContextName, contextName);
+ assertEquals(expectedContextFilter, contextFilter);
+
+ assertEquals(attrList.size(),expectedAttrNameList.size());
+ Iterator iter = attrList.iterator();
+ Iterator eIter = expectedAttrNameList.iterator();
+ while(iter.hasNext()&&eIter.hasNext()) {
+ String actualName = ((Attribute)iter.next()).getID();
+ String expectedName = (String)eIter.next();
+ assertEquals(actualName, expectedName);
+ }
+
+ assertEquals(expectedCountLimit, countLimit);
+ assertEquals(expectedSearchScope, searchScope);
+ assertEquals(expectedSortKeys, sortKeys);
+ }
+
+ /**
+ * Test a Query without criteria
+ */
+ public void testSelectFrom1() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(objectClass=*)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ /**
+ * Test a Query with a criteria
+ */
+ public void testSelectFromWhere1() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R%'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(cn=R%)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ /**
+ * Test a Query with a criteria
+ */
+ public void testEscaping() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name = 'R*'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(cn=R\\2a)"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ public void testNot() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE not (Name like 'R%' or Name like 'S%')"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(&(!(cn=R*))(!(cn=S*)))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+
+ }
+
+ public void testGT() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name > 'R'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(!(cn<=R))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+ }
+
+ public void testLT() throws Exception {
+ LDAPSearchDetails searchDetails = helpGetSearchDetails("SELECT UserID, Name FROM LdapModel.People WHERE Name < 'R'"); //$NON-NLS-1$
+
+ //-----------------------------------
+ // Set Expected SearchDetails Values
+ //-----------------------------------
+ String expectedContextName = "ou=people,dc=metamatrix,dc=com"; //$NON-NLS-1$
+ String expectedContextFilter = "(!(cn>=R))"; //$NON-NLS-1$
+
+ List expectedAttrNameList = new ArrayList();
+ expectedAttrNameList.add("uid"); //$NON-NLS-1$
+ expectedAttrNameList.add("cn"); //$NON-NLS-1$
+
+ long expectedCountLimit = -1;
+ int expectedSearchScope = SearchControls.ONELEVEL_SCOPE;
+ SortKey[] expectedSortKeys = null;
+
+ helpTestSearchDetails(searchDetails, expectedContextName, expectedContextFilter, expectedAttrNameList,
+ expectedCountLimit, expectedSearchScope, expectedSortKeys);
+ }
+
+ private LDAPSearchDetails helpGetSearchDetails(String queryString) throws ConnectorException {
+ QueryMetadataInterface metadata = exampleLdap();
+ RuntimeMetadata rm = new RuntimeMetadataImpl(metadata);
+
+ LDAPExecutionFactory config = mock(LDAPExecutionFactory.class);
+
+ IQueryToLdapSearchParser searchParser = new IQueryToLdapSearchParser(config);
+
+ Select query = (Select)getCommand(queryString, metadata);
+
+ LDAPSearchDetails searchDetails = searchParser.translateSQLQueryToLDAPSearch(query);
+ return searchDetails;
+ }
+
+ public static QueryMetadataInterface exampleLdap() {
+ MetadataStore metadataStore = new MetadataStore();
+
+ // Create models
+ Schema ldapModel = RealMetadataFactory.createPhysicalModel("LdapModel", metadataStore); //$NON-NLS-1$
+
+ // Create physical groups
+ Table table = RealMetadataFactory.createPhysicalGroup("People", ldapModel); //$NON-NLS-1$
+ table.setNameInSource("ou=people,dc=metamatrix,dc=com"); //$NON-NLS-1$
+
+ // Create physical elements
+ String[] elemNames = new String[] {
+ "UserID", "Name" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+ };
+
+ List<Column> cols = RealMetadataFactory.createElements(table, elemNames, elemTypes);
+
+ // Set name in source on each column
+ String[] nameInSource = new String[] {
+ "uid", "cn" //$NON-NLS-1$ //$NON-NLS-2$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = cols.get(i);
+ obj.setNameInSource(nameInSource[i]);
+ }
+
+ // Set column-specific properties
+ for(int i=1; i<2; i++) {
+ cols.get(i).setSearchType(SearchType.Unsearchable);
+ }
+
+ // Create the facade from the store
+ return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, null);
+ }
+}
+
Copied: trunk/connectors/translator-loopback (from rev 2083, trunk/connectors/connector-loopback)
Modified: trunk/connectors/translator-loopback/pom.xml
===================================================================
--- trunk/connectors/connector-loopback/pom.xml 2010-04-27 17:56:40 UTC (rev 2083)
+++ trunk/connectors/translator-loopback/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -8,11 +8,10 @@
<version>7.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
- <artifactId>connector-loopback</artifactId>
+ <artifactId>translator-loopback</artifactId>
<groupId>org.jboss.teiid.connectors</groupId>
- <name>Loopback Connector</name>
- <packaging>rar</packaging>
- <description>Loopback Connector</description>
+ <name>Loopback Translator</name>
+ <description>Loopback Translator</description>
<dependencies>
<dependency>
@@ -31,33 +30,26 @@
<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
+ <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>
Added: trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackCapabilities.java
===================================================================
--- trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackCapabilities.java (rev 0)
+++ trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,317 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.loopback;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+
+/**
+ * Specifies the capabilities of this connector. Since we want this
+ * connector to be able to emulate most other connectors, these
+ * capabilities support everything.
+ */
+public class LoopbackCapabilities extends BasicConnectorCapabilities {
+
+ /**
+ * Construct the capabilities class
+ */
+ public LoopbackCapabilities() {
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#getSupportedFunctions()
+ */
+ public List getSupportedFunctions() {
+ List functions = Arrays.asList(new String[] {
+ "+", "-", "*", "/", "abs", "acos", "asin", "atan", "atan2", "ceiling", //$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$
+ "bitand", "bitnot", "bitor", "bitxor", "cos", "cot", "degrees", "cos", "cot", //$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$
+ "degrees", "exp", "floor", "log", "log10", "mod", "pi", "power", "radians", //$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$
+ "round", "sign", "sin", "sqrt", "tan", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ "ascii", "chr", "char", "concat", "initcap", "insert", "lcase", "left", "length", //$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$
+ "locate", "lower", "lpad", "ltrim", "repeat", "replace", "right", "rpad", "rtrim", //$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$
+ "substring", "translate", "ucase", "upper", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ "curdate", "curtime", "now", "dayname", "dayofmonth", "dayofweek", "dayofyear", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "hour", "minute", "month", "monthname", "quarter", "second", "timestampadd", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+ "timestampdiff", "week", "year", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ "cast", "convert", "ifnull", "nvl" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ });
+ return functions;
+ }
+
+ @Override
+ public boolean supportsGroupBy() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesAvg()
+ */
+ public boolean supportsAggregatesAvg() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCount()
+ */
+ public boolean supportsAggregatesCount() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesCountStar()
+ */
+ public boolean supportsAggregatesCountStar() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesDistinct()
+ */
+ public boolean supportsAggregatesDistinct() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMax()
+ */
+ public boolean supportsAggregatesMax() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesMin()
+ */
+ public boolean supportsAggregatesMin() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAggregatesSum()
+ */
+ public boolean supportsAggregatesSum() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsAliasedGroup()
+ */
+ public boolean supportsAliasedGroup() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsBetweenCriteria()
+ */
+ public boolean supportsBetweenCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCaseExpressions()
+ */
+ public boolean supportsCaseExpressions() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCompareCriteriaEquals()
+ */
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsCorrelatedSubqueries()
+ */
+ public boolean supportsCorrelatedSubqueries() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsExistsCriteria()
+ */
+ public boolean supportsExistsCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsFullOuterJoins()
+ */
+ public boolean supportsFullOuterJoins() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteria()
+ */
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsInCriteriaSubquery()
+ */
+ public boolean supportsInCriteriaSubquery() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsIsNullCriteria()
+ */
+ public boolean supportsIsNullCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteria()
+ */
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsLikeCriteriaEscapeCharacter()
+ */
+ public boolean supportsLikeCriteriaEscapeCharacter() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsNotCriteria()
+ */
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrCriteria()
+ */
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOrderBy()
+ */
+ public boolean supportsOrderBy() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsOuterJoins()
+ */
+ public boolean supportsOuterJoins() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsQuantifiedCompareCriteriaAll()
+ */
+ public boolean supportsQuantifiedCompareCriteriaAll() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsScalarSubqueries()
+ */
+ public boolean supportsScalarSubqueries() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSearchedCaseExpressions()
+ */
+ public boolean supportsSearchedCaseExpressions() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSelectDistinct()
+ */
+ public boolean supportsSelectDistinct() {
+ return true;
+ }
+
+ /*
+ * @see com.metamatrix.data.ConnectorCapabilities#supportsSelfJoins()
+ */
+ public boolean supportsSelfJoins() {
+ return true;
+ }
+
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ public boolean supportsQuantifiedCompareCriteriaSome() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSelectExpression() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSetQueryOrderBy() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsUnions() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsInnerJoins() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsHaving() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+}
Added: trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecution.java
===================================================================
--- trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecution.java (rev 0)
+++ trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,265 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.loopback;
+
+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.Calendar;
+import java.util.List;
+import java.util.Random;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Argument.Direction;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.TypeFacility;
+import org.teiid.resource.cci.UpdateExecution;
+
+
+/**
+ * Represents the execution of a command.
+ */
+public class LoopbackExecution extends BasicExecution implements UpdateExecution, ProcedureExecution {
+
+ private static final String ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$
+
+ // Connector resources
+ private LoopbackExecutionFactory config;
+ private Command command;
+
+ // Execution state
+ private Random randomNumber = new Random(System.currentTimeMillis());
+ private List<Object> row;
+ private boolean waited = false;
+ private int rowsReturned = 0;
+ private int rowsNeeded = 1;
+
+ public LoopbackExecution(Command command, LoopbackExecutionFactory config) {
+ this.config = config;
+ this.command = command;
+ }
+
+ @Override
+ public List<?> next() throws ConnectorException, DataNotAvailableException {
+ // Wait on first batch if necessary
+ if(this.config.getWaitTime() > 0 && !waited) {
+ // Wait a random amount of time up to waitTime milliseconds
+ int randomTimeToWait = randomNumber.nextInt(this.config.getWaitTime());
+
+ // If we're asynch and the wait time was longer than the poll interval,
+ // then just say we don't have results instead
+ if(randomTimeToWait > this.config.getPollIntervalInMilli()) {
+ waited = true;
+ throw new DataNotAvailableException(randomTimeToWait);
+ }
+ try {
+ Thread.sleep(randomTimeToWait);
+ } catch(InterruptedException e) {
+ }
+ waited = true;
+ }
+
+ if(rowsReturned < this.rowsNeeded && row.size() > 0) {
+ rowsReturned++;
+ return row;
+ }
+
+ return null;
+ }
+
+ /*
+ * @see com.metamatrix.data.SynchQueryExecution#execute(com.metamatrix.data.language.IQuery, int)
+ */
+ @Override
+ public void execute() throws ConnectorException {
+
+ // Log our command
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Loopback executing command: " + command); //$NON-NLS-1$
+
+ if(this.config.isThrowError()) {
+ throw new ConnectorException("Failing because Error=true"); //$NON-NLS-1$
+ }
+
+ this.rowsNeeded = this.config.getRowCount();
+
+ if (command instanceof QueryExpression) {
+ QueryExpression queryCommand = (QueryExpression)command;
+ if (queryCommand.getLimit() != null) {
+ this.rowsNeeded = queryCommand.getLimit().getRowLimit();
+ }
+ }
+
+ // Prepare for execution
+ List types = determineOutputTypes(this.command);
+ createDummyRow(types);
+ }
+
+ @Override
+ public int[] getUpdateCounts() throws DataNotAvailableException,
+ ConnectorException {
+ return new int [] {0};
+ }
+
+ @Override
+ public List<?> getOutputParameterValues() throws ConnectorException {
+ Call proc = (Call)this.command;
+ int count = proc.getReturnType() != null ? 1:0;
+ for (Argument param : proc.getArguments()) {
+ if (param.getDirection() == Direction.INOUT || param.getDirection() == Direction.OUT) {
+ count++;
+ }
+ }
+ return Arrays.asList(new Object[count]);
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#close()
+ */
+ @Override
+ public void close() throws ConnectorException {
+ // nothing to do
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#cancel()
+ */
+ @Override
+ public void cancel() throws ConnectorException {
+
+ }
+
+ private List determineOutputTypes(Command command) {
+ // Get select columns and lookup the types in metadata
+ if(command instanceof QueryExpression) {
+ QueryExpression query = (QueryExpression) command;
+ return Arrays.asList(query.getColumnTypes());
+ }
+ if (command instanceof Call) {
+ return Arrays.asList(((Call)command).getResultSetColumnTypes());
+ }
+ List<Class<?>> types = new ArrayList<Class<?>>(1);
+ types.add(Integer.class);
+ return types;
+ }
+
+ private void createDummyRow(List<Class<?>> types) {
+ row = new ArrayList<Object>(types.size());
+
+ for (Class<?> type : types) {
+ row.add( getValue(type) );
+ }
+ }
+
+ /**
+ * Get a variable-sized string.
+ * @param size The size (in characters) of the string
+ */
+ private String getVariableString( int size ) {
+ int multiplier = size / ALPHA.length();
+ int remainder = size % ALPHA.length();
+ String value = ""; //$NON-NLS-1$
+ for ( int k = 0; k < multiplier; k++ ) {
+ value += ALPHA;
+ }
+ value += ALPHA.substring(0,remainder);
+ return value;
+ }
+
+ 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$
+ public static java.sql.Date SQL_DATE_VAL;
+ public static java.sql.Time TIME_VAL;
+ public static java.sql.Timestamp TIMESTAMP_VAL;
+
+ /*
+ * Set the date/time fields to UTC 0 as displayed in US/Central
+ */
+ static {
+ Calendar cal = Calendar.getInstance();
+ cal.clear();
+ cal.set(1969, 11, 31, 18, 0, 0);
+ SQL_DATE_VAL = new Date(cal.getTimeInMillis());
+ TIME_VAL = new Time(cal.getTimeInMillis());
+ TIMESTAMP_VAL = new Timestamp(cal.getTimeInMillis());
+ }
+
+ private Object getValue(Class type) {
+ if(type.equals(java.lang.String.class)) {
+ return getVariableString(10);
+ } else if(type.equals(java.lang.Integer.class)) {
+ return INTEGER_VAL;
+ } else if(type.equals(java.lang.Short.class)) {
+ return SHORT_VAL;
+ } else if(type.equals(java.lang.Long.class)) {
+ return LONG_VAL;
+ } else if(type.equals(java.lang.Float.class)) {
+ return FLOAT_VAL;
+ } else if(type.equals(java.lang.Double.class)) {
+ return DOUBLE_VAL;
+ } else if(type.equals(java.lang.Character.class)) {
+ return CHAR_VAL;
+ } else if(type.equals(java.lang.Byte.class)) {
+ return BYTE_VAL;
+ } else if(type.equals(java.lang.Boolean.class)) {
+ return BOOLEAN_VAL;
+ } else if(type.equals(java.math.BigInteger.class)) {
+ return BIG_INTEGER_VAL;
+ } else if(type.equals(java.math.BigDecimal.class)) {
+ return BIG_DECIMAL_VAL;
+ } else if(type.equals(java.sql.Date.class)) {
+ return SQL_DATE_VAL;
+ } else if(type.equals(java.sql.Time.class)) {
+ return TIME_VAL;
+ } else if(type.equals(java.sql.Timestamp.class)) {
+ return TIMESTAMP_VAL;
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.CLOB)) {
+ return this.config.getTypeFacility().convertToRuntimeType(ALPHA.toCharArray());
+ } else if(type.equals(TypeFacility.RUNTIME_TYPES.BLOB)) {
+ return this.config.getTypeFacility().convertToRuntimeType(ALPHA.getBytes());
+ } else {
+ return getVariableString(10);
+ }
+ }
+
+}
Added: trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecutionFactory.java
===================================================================
--- trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-loopback/src/main/java/org/teiid/resource/adapter/loopback/LoopbackExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,100 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.loopback;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.Execution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.TranslatorProperty;
+
+/**
+ * Loopback connector.
+ */
+public class LoopbackExecutionFactory extends BasicExecutionFactory {
+
+ private int waitTime = 0;
+ private int rowCount = 1;
+ private boolean throwError = false;
+ private long pollIntervalInMilli = -1;
+
+ @TranslatorProperty(name="wait-time", display="Max Random Wait Time",required=true, advanced=true, defaultValue="0")
+ public int getWaitTime() {
+ return waitTime;
+ }
+
+ public void setWaitTime(Integer waitTime) {
+ this.waitTime = waitTime.intValue();
+ }
+
+ @TranslatorProperty(name="row-count", display="Rows Per Query",required=true, advanced=true, defaultValue="1")
+ public int getRowCount() {
+ return rowCount;
+ }
+
+ public void setRowCount(Integer rowCount) {
+ this.rowCount = rowCount;
+ }
+
+ @TranslatorProperty(name="throw-error", display="Always Throw Error", defaultValue="false")
+ public boolean isThrowError() {
+ return this.throwError;
+ }
+
+ public void setThrowError(Boolean error) {
+ this.throwError = error.booleanValue();
+ }
+
+ @TranslatorProperty(name="poll-intervel", display="Poll interval if using a Asynchronous Connector", defaultValue="-1")
+ public long getPollIntervalInMilli() {
+ return this.pollIntervalInMilli;
+ }
+
+ public void setPollIntervalInMilli(Long intervel) {
+ this.pollIntervalInMilli = intervel.longValue();
+ }
+
+ @Override
+ public void start() throws ConnectorException {
+ super.start();
+ }
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return LoopbackCapabilities.class;
+ }
+
+ @Override
+ public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionfactory)
+ throws ConnectorException {
+ return new LoopbackExecution(command, this);
+ }
+
+ @Override
+ public boolean isSourceRequired() {
+ return false;
+ }
+}
Added: trunk/connectors/translator-loopback/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-loopback/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-loopback/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.loopback.LoopbackExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/translator-loopback/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoobackAsynch.java
===================================================================
--- trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoobackAsynch.java (rev 0)
+++ trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoobackAsynch.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.adaptor.loopback;
+
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.resource.adapter.loopback.LoopbackExecutionFactory;
+
+import com.metamatrix.cdk.api.ConnectorHost;
+import com.metamatrix.cdk.unittest.FakeTranslationFactory;
+
+
+/**
+ * @since 4.3
+ */
+public class TestLoobackAsynch extends TestCase {
+
+ public void test() throws Exception {
+ LoopbackExecutionFactory connector = new LoopbackExecutionFactory();
+ connector.setWaitTime(200);
+ connector.setRowCount(1000);
+ connector.setPollIntervalInMilli(100L);
+
+ ConnectorHost host = new ConnectorHost(connector, FakeTranslationFactory.getInstance().getBQTTranslationUtility());
+ List results = host.executeCommand("SELECT intkey from bqt1.smalla", null); //$NON-NLS-1$
+ assertEquals(1000, results.size());
+ }
+
+}
Added: trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoopbackExecution.java
===================================================================
--- trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoopbackExecution.java (rev 0)
+++ trunk/connectors/translator-loopback/src/test/java/org/teiid/resource/adaptor/loopback/TestLoopbackExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,172 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.adaptor.loopback;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.loopback.LoopbackExecution;
+import org.teiid.resource.adapter.loopback.LoopbackExecutionFactory;
+
+import com.metamatrix.cdk.api.ConnectorHost;
+import com.metamatrix.cdk.api.TranslationUtility;
+import com.metamatrix.cdk.unittest.FakeTranslationFactory;
+
+public class TestLoopbackExecution extends TestCase {
+
+ public TestLoopbackExecution(String name) {
+ super(name);
+ }
+
+ public LoopbackExecutionFactory exampleProperties(int waitTime, int rowCount) {
+ LoopbackExecutionFactory config = new LoopbackExecutionFactory();
+ config.setWaitTime(waitTime);
+ config.setRowCount(rowCount);
+ return config;
+ }
+
+ public void helpTestQuery(String sql, TranslationUtility metadata, Object[][] expectedResults) throws ConnectorException {
+ helpTestQuery(sql, metadata, 0, 1, expectedResults);
+ }
+
+ public void helpTestQuery(String sql, TranslationUtility metadata, int waitTime, int rowCount, Object[][] expectedResults) throws ConnectorException {
+ ConnectorHost host = new ConnectorHost(exampleProperties(waitTime, rowCount), metadata);
+
+ List actualResults = host.executeCommand(sql, null);
+
+ // Compare actual and expected results
+ assertEquals("Did not get expected number of rows", expectedResults.length, actualResults.size()); //$NON-NLS-1$
+
+ if(expectedResults.length > 0) {
+ // Compare column sizes
+ assertEquals("Did not get expected number of columns", expectedResults[0].length, ((List)actualResults.get(0)).size()); //$NON-NLS-1$
+
+ // Compare results
+ for(int r=0; r<expectedResults.length; r++) {
+ Object[] expectedRow = expectedResults[r];
+ List actualRow = (List) actualResults.get(r);
+
+ for(int c=0; c<expectedRow.length; c++) {
+ Object expectedValue = expectedRow[c];
+ Object actualValue = actualRow.get(c);
+
+ if(expectedValue == null) {
+ if(actualValue != null) {
+ fail("Row " + r + ", Col " + c + ": Expected null but got " + actualValue + " of type " + actualValue.getClass().getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+ } else if(actualValue == null) {
+ fail("Row " + r + ", Col " + c + ": Expected " + expectedValue + " but got null"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ } else {
+ assertEquals("Row " + r + ", Col " + c + ": Expected " + expectedValue + " but got " + actualValue, expectedValue, actualValue); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+ }
+ }
+ }
+ }
+
+ public void testSimple() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { new Integer(0) }
+ };
+ helpTestQuery("SELECT intkey FROM BQT1.SmallA", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testMostTypes() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { new Integer(0), "ABCDEFGHIJ", new Float(0), new Long(0), new Double(0), new Byte((byte)0), //$NON-NLS-1$
+ LoopbackExecution.SQL_DATE_VAL, LoopbackExecution.TIME_VAL,
+ LoopbackExecution.TIMESTAMP_VAL, Boolean.FALSE,
+ new BigInteger("0"), new BigDecimal("0"), "ABCDEFGHIJ", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ new Short((short)0), new Character('c')
+ }
+ };
+
+ helpTestQuery("SELECT intkey, StringKey, floatnum, longnum, doublenum, bytenum, " + //$NON-NLS-1$
+ "datevalue, timevalue, timestampvalue, booleanvalue, bigintegervalue, bigdecimalvalue, " + //$NON-NLS-1$
+ "objectvalue, shortvalue, charvalue FROM BQT1.SmallA", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testInsert() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { new Integer(0) }
+ };
+ helpTestQuery("INSERT INTO BQT1.SmallA (stringkey) VALUES ('x')", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testUpdate() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { new Integer(0) }
+ };
+ helpTestQuery("UPDATE BQT1.SmallA SET stringkey = 'x'", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testDelete() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { new Integer(0) }
+ };
+ helpTestQuery("DELETE FROM BQT1.SmallA", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testExec() throws Exception {
+ Object[][] results = new Object[][] {
+ new Object[] { "ABCDEFGHIJ" } //$NON-NLS-1$
+ };
+ helpTestQuery("EXEC mmspTest1.MMSP1()", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ public void testExecWithoutResultSet() throws Exception {
+ Object[][] results = new Object[][] {
+ };
+ helpTestQuery("exec pm4.spTest9(1)", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), results); //$NON-NLS-1$
+ }
+
+ /**
+ * wait time is implemented as a random value up to the specified value. assertions are then not really possible
+ * based upon that time.
+ */
+ public void defer_testWaitTime() throws Exception {
+ int waitTime = 100;
+ int testCount = 10;
+
+ ConnectorHost host = new ConnectorHost(exampleProperties(waitTime, 1), FakeTranslationFactory.getInstance().getBQTTranslationUtility());
+
+ for(int i=0; i<testCount; i++) {
+ long before = System.currentTimeMillis();
+ host.executeCommand("SELECT intkey FROM BQT1.SmallA", null); //$NON-NLS-1$
+ long after = System.currentTimeMillis();
+ assertTrue("Waited too long", (after-before) <= waitTime); //$NON-NLS-1$
+ }
+ }
+
+ public void testQueryWithLimit() throws Exception {
+ Object[][] expected = {{new Integer(0)},
+ {new Integer(0)},
+ {new Integer(0)}};
+ helpTestQuery("SELECT intkey FROM BQT1.SmallA LIMIT 3", FakeTranslationFactory.getInstance().getBQTTranslationUtility(), 0, 100, expected); //$NON-NLS-1$
+ }
+
+}
Property changes on: trunk/connectors/translator-salesforce
___________________________________________________________________
Name: svn:ignore
+ target
.classpath
.project
.settings
Added: trunk/connectors/translator-salesforce/pom.xml
===================================================================
--- trunk/connectors/translator-salesforce/pom.xml (rev 0)
+++ trunk/connectors/translator-salesforce/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-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-connector-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>
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Constants.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Constants.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Constants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+package org.teiid.resource.adapter.salesforce;
+
+public interface Constants {
+
+ public static final String PICKLIST_TYPE = "picklist"; //$NON-NLS-1$
+
+ public static final String MULTIPICKLIST_TYPE = "multipicklist"; //$NON-NLS-1$
+
+ public static final String COMBOBOX_TYPE = "combobox"; //$NON-NLS-1$
+
+ public static final String ANYTYPE_TYPE = "anyType"; //$NON-NLS-1$
+
+ public static final String REFERENCE_TYPE = "reference"; //$NON-NLS-1$
+
+ public static final String STRING_TYPE = "string"; //$NON-NLS-1$
+
+ public static final String BASE64_TYPE = "base64"; //$NON-NLS-1$
+
+ public static final String BOOLEAN_TYPE = "boolean"; //$NON-NLS-1$
+
+ public static final String CURRENCY_TYPE = "currency"; //$NON-NLS-1$
+
+ public static final String TEXTAREA_TYPE = "textarea"; //$NON-NLS-1$
+
+ public static final String INT_TYPE = "int"; //$NON-NLS-1$
+
+ public static final String DOUBLE_TYPE = "double"; //$NON-NLS-1$
+
+ public static final String PERCENT_TYPE = "percent"; //$NON-NLS-1$
+
+ public static final String PHONE_TYPE = "phone"; //$NON-NLS-1$
+
+ public static final String ID_TYPE = "id"; //$NON-NLS-1$
+
+ public static final String DATE_TYPE = "date"; //$NON-NLS-1$
+
+ public static final String DATETIME_TYPE = "datetime"; //$NON-NLS-1$
+
+ public static final String URL_TYPE = "url"; //$NON-NLS-1$
+
+ public static final String EMAIL_TYPE = "email"; //$NON-NLS-1$
+
+ public static final String RESTRICTED_PICKLIST_TYPE = "restrictedpicklist"; //$NON-NLS-1$
+
+ public static final String RESTRICTED_MULTISELECT_PICKLIST_TYPE = "restrictedmultiselectpicklist"; //$NON-NLS-1$
+
+ public static final String SUPPORTS_QUERY = "Supports Query";//$NON-NLS-1$
+
+ public static final String SUPPORTS_RETRIEVE = "Supports Retrieve";//$NON-NLS-1$
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Messages.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Messages.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Messages.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+public class Messages {
+
+ private static final String BUNDLE_NAME = "com.metamatrix.connector.salesforce.i18n"; //$NON-NLS-1$
+
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+
+ public static String getString(String key) {
+ try {
+ return RESOURCE_BUNDLE.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/MetadataProcessor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/MetadataProcessor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/MetadataProcessor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,292 @@
+package org.teiid.resource.adapter.salesforce;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.KeyRecord;
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.connector.metadata.runtime.BaseColumn.NullType;
+import org.teiid.connector.metadata.runtime.Column.SearchType;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+
+import com.metamatrix.common.types.DataTypeManager;
+import com.sforce.soap.partner.ChildRelationship;
+import com.sforce.soap.partner.DescribeGlobalResult;
+import com.sforce.soap.partner.DescribeGlobalSObjectResult;
+import com.sforce.soap.partner.DescribeSObjectResult;
+import com.sforce.soap.partner.Field;
+import com.sforce.soap.partner.FieldType;
+import com.sforce.soap.partner.PicklistEntry;
+
+public class MetadataProcessor {
+ private MetadataFactory metadataFactory;
+ private SalesforceConnection connection;
+ private SalesForceExecutionFactory connectorEnv;
+
+ private Map<String, Table> tableMap = new HashMap<String, Table>();
+ private List<Relationship> relationships = new ArrayList<Relationship>();
+ private boolean hasUpdateableColumn = false;
+ private List<Column> columns;
+
+ // Audit Fields
+ public static final String AUDIT_FIELD_CREATED_BY_ID = "CreatedById"; //$NON-NLS-1$
+ public static final String AUDIT_FIELD_CREATED_DATE = "CreatedDate"; //$NON-NLS-1$
+ public static final String AUDIT_FIELD_LAST_MODIFIED_BY_ID = "LastModifiedById"; //$NON-NLS-1$
+ public static final String AUDIT_FIELD_LAST_MODIFIED_DATE = "LastModifiedDate"; //$NON-NLS-1$
+ public static final String AUDIT_FIELD_SYSTEM_MOD_STAMP = "SystemModstamp"; //$NON-NLS-1$
+
+ // Model Extensions
+ static final String TABLE_SUPPORTS_CREATE = "Supports Create"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_DELETE = "Supports Delete"; //$NON-NLS-1$
+ static final String TABLE_CUSTOM = "Custom"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_LOOKUP = "Supports ID Lookup"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_MERGE = "Supports Merge"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_QUERY = "Supports Query"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_REPLICATE = "Supports Replicate"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_RETRIEVE = "Supports Retrieve"; //$NON-NLS-1$
+ static final String TABLE_SUPPORTS_SEARCH = "Supports Search"; //$NON-NLS-1$
+
+ static final String COLUMN_DEFAULTED = "Defaulted on Create"; //$NON-NLS-1$
+ static final String COLUMN_CUSTOM = "Custom"; //$NON-NLS-1$
+ static final String COLUMN_CALCULATED = "Calculated"; //$NON-NLS-1$
+ static final String COLUMN_PICKLIST_VALUES = "Picklist Values"; //$NON-NLS-1$
+
+ public MetadataProcessor(SalesforceConnection connection, MetadataFactory metadataFactory, SalesForceExecutionFactory env) {
+ this.connection = connection;
+ this.metadataFactory = metadataFactory;
+ this.connectorEnv = env;
+ }
+
+ public void processMetadata() throws ConnectorException {
+ DescribeGlobalResult globalResult = connection.getObjects();
+ List<DescribeGlobalSObjectResult> objects = globalResult.getSobjects();
+ for (DescribeGlobalSObjectResult object : objects) {
+ addTable(object);
+ }
+ addRelationships();
+ }
+
+ private void addRelationships() throws ConnectorException {
+ for (Iterator<Relationship> iterator = relationships.iterator(); iterator.hasNext();) {
+ Relationship relationship = iterator.next();
+ if (!this.connectorEnv.isModelAuditFields() && isAuditField(relationship.getForeignKeyField())) {
+ continue;
+ }
+
+ Table parent = tableMap.get(NameUtil.normalizeName(relationship.getParentTable()));
+ KeyRecord pk = parent.getPrimaryKey();
+ if (null == pk) {
+ throw new RuntimeException("ERROR !!primary key column not found!!"); //$NON-NLS-1$
+ }
+ ArrayList<String> columnNames = new ArrayList<String>();
+ columnNames.add(pk.getName());
+
+
+ Table child = tableMap.get(NameUtil.normalizeName(relationship.getChildTable()));
+
+ Column col = null;
+ columns = child.getColumns();
+ for (Iterator colIter = columns.iterator(); colIter.hasNext();) {
+ Column column = (Column) colIter.next();
+ if(column.getName().equals(relationship.getForeignKeyField())) {
+ col = column;
+ }
+ }
+ if (null == col) throw new RuntimeException(
+ "ERROR !!foreign key column not found!! " + child.getName() + relationship.getForeignKeyField()); //$NON-NLS-1$
+
+
+ String columnName = "FK_" + parent.getName() + "_" + col.getName();//$NON-NLS-1$ //$NON-NLS-2$
+ ArrayList<String> columnNames2 = new ArrayList<String>();
+ columnNames2.add(col.getName());
+ metadataFactory.addForiegnKey(columnName, columnNames2, parent, child);
+
+ }
+
+
+ }
+
+ public static boolean isAuditField(String name) {
+ boolean result = false;
+ if(name.equals(AUDIT_FIELD_CREATED_BY_ID) ||
+ name.equals(AUDIT_FIELD_CREATED_DATE) ||
+ name.equals(AUDIT_FIELD_LAST_MODIFIED_BY_ID) ||
+ name.equals(AUDIT_FIELD_LAST_MODIFIED_DATE) ||
+ name.equals(AUDIT_FIELD_SYSTEM_MOD_STAMP)) {
+ result = true;
+ }
+ return result;
+ }
+
+ private void addTable(DescribeGlobalSObjectResult object) throws ConnectorException {
+ DescribeSObjectResult objectMetadata = connection.getObjectMetaData(object.getName());
+ String name = NameUtil.normalizeName(objectMetadata.getName());
+ Table table = metadataFactory.addTable(name);
+
+ table.setNameInSource(objectMetadata.getName());
+ tableMap.put(name, table);
+ getRelationships(objectMetadata);
+
+ table.setProperty(TABLE_CUSTOM, String.valueOf(objectMetadata.isCustom()));
+ table.setProperty(TABLE_SUPPORTS_CREATE, String.valueOf(objectMetadata.isCreateable()));
+ table.setProperty(TABLE_SUPPORTS_DELETE, String.valueOf(objectMetadata.isDeletable()));
+ table.setProperty(TABLE_SUPPORTS_MERGE, String.valueOf(objectMetadata.isMergeable()));
+ table.setProperty(TABLE_SUPPORTS_QUERY, String.valueOf(objectMetadata.isQueryable()));
+ table.setProperty(TABLE_SUPPORTS_REPLICATE, String.valueOf(objectMetadata.isReplicateable()));
+ table.setProperty(TABLE_SUPPORTS_RETRIEVE, String.valueOf(objectMetadata.isRetrieveable()));
+ table.setProperty(TABLE_SUPPORTS_SEARCH, String.valueOf(objectMetadata.isSearchable()));
+
+ hasUpdateableColumn = false;
+ addColumns(objectMetadata, table);
+
+ // Some SF objects return true for isUpdateable() but have no updateable columns.
+ if(hasUpdateableColumn && objectMetadata.isUpdateable()) {
+ table.setSupportsUpdate(true);
+ }
+ }
+
+ private void getRelationships(DescribeSObjectResult objectMetadata) {
+ List<ChildRelationship> children = objectMetadata.getChildRelationships();
+ if(children != null && children.size() != 0) {
+ for (ChildRelationship childRelation : children) {
+ Relationship newRelation = new RelationshipImpl();
+ newRelation.setParentTable(objectMetadata.getName());
+ newRelation.setChildTable(childRelation.getChildSObject());
+ newRelation.setForeignKeyField(childRelation.getField());
+ newRelation.setCascadeDelete(childRelation.isCascadeDelete());
+ relationships.add(newRelation);
+ }
+ }
+ }
+
+ private void addColumns(DescribeSObjectResult objectMetadata, Table table) throws ConnectorException {
+ List<Field> fields = objectMetadata.getFields();
+ for (Field field : fields) {
+ String normalizedName = NameUtil.normalizeName(field.getName());
+ FieldType fieldType = field.getType();
+ if(!this.connectorEnv.isModelAuditFields() && isAuditField(field.getName())) {
+ continue;
+ }
+ String sfTypeName = fieldType.value();
+ Column column = null;
+ if(sfTypeName.equals(FieldType.STRING) || //string
+ sfTypeName.equals(FieldType.COMBOBOX) || //"combobox"
+ sfTypeName.equals(FieldType.REFERENCE) || //"reference"
+ sfTypeName.equals(FieldType.PHONE) || //"phone"
+ sfTypeName.equals(FieldType.ID) || //"id"
+ sfTypeName.equals(FieldType.URL) || //"url"
+ sfTypeName.equals(FieldType.EMAIL) || //"email"
+ sfTypeName.equals(FieldType.ENCRYPTEDSTRING) || //"encryptedstring"
+ sfTypeName.equals(FieldType.ANY_TYPE)) { //"anytype"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
+ column.setNativeType(sfTypeName);
+ if(sfTypeName.equals(FieldType.ID)) {
+ column.setNullType(NullType.No_Nulls);
+ ArrayList<String> columnNames = new ArrayList<String>();
+ columnNames.add(field.getName());
+ metadataFactory.addPrimaryKey(field.getName()+"_PK", columnNames, table);
+ }
+ }
+ else if(sfTypeName.equals(FieldType.PICKLIST)) { // "picklist"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
+ if(field.isRestrictedPicklist()) {
+ column.setNativeType("restrictedpicklist");
+ } else {
+ column.setNativeType(sfTypeName);
+ }
+
+ column.setProperty(COLUMN_PICKLIST_VALUES, getPicklistValues(field));
+ }
+ else if(sfTypeName.equals(FieldType.MULTIPICKLIST)) { //"multipicklist"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
+ if(field.isRestrictedPicklist()) {
+ column.setNativeType("restrictedmultiselectpicklist");
+ } else {
+ column.setNativeType(sfTypeName);
+ }
+ column.setProperty(COLUMN_PICKLIST_VALUES, getPicklistValues(field));
+ }
+ else if(sfTypeName.equals(FieldType.BASE_64)) { //"base64"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.BLOB, table);
+ column.setNativeType(sfTypeName);
+ }
+ else if(sfTypeName.equals(FieldType.BOOLEAN)) { //"boolean"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.BOOLEAN, table);
+ column.setNativeType(sfTypeName);
+ }
+ else if(sfTypeName.equals(FieldType.CURRENCY)) { //"currency"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DOUBLE, table);
+ column.setNativeType(sfTypeName);
+ column.setCurrency(true);
+ column.setScale(field.getScale());
+ column.setPrecision(field.getPrecision());
+ }
+ else if(sfTypeName.equals(FieldType.TEXTAREA)) { //"textarea"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.STRING, table);
+ column.setNativeType(sfTypeName);
+ column.setSearchType(SearchType.Unsearchable);
+ }
+ else if(sfTypeName.equals(FieldType.INT)) { //"int"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.INTEGER, table);
+ column.setNativeType(sfTypeName);
+ column.setPrecision(field.getPrecision());
+ }
+ else if(sfTypeName.equals(FieldType.DOUBLE) || //"double"
+ sfTypeName.equals(FieldType.PERCENT)) { //"percent"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DOUBLE, table);
+ column.setNativeType(sfTypeName);
+ column.setScale(field.getScale());
+ column.setPrecision(field.getPrecision());
+ }
+ else if(sfTypeName.equals(FieldType.DATE)) { //"date"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.DATE, table);
+ column.setNativeType(sfTypeName);
+ }
+ else if(sfTypeName.equals(FieldType.DATETIME)) { //"datetime"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.TIMESTAMP, table);
+ column.setNativeType(sfTypeName);
+ }
+ else if(sfTypeName.equals(FieldType.TIME)) { //"time"
+ column = metadataFactory.addColumn(normalizedName, DataTypeManager.DefaultDataTypes.TIME, table);
+ column.setNativeType(sfTypeName);
+ }
+ if(null == column) {
+ LogManager.logError(LogConstants.CTX_CONNECTOR, "Unknown type returned by SalesForce: " + sfTypeName);
+ continue;
+ } else {
+ column.setNameInSource(field.getName());
+ column.setLength(field.getLength());
+ if(field.isUpdateable()) {
+ column.setUpdatable(true);
+ hasUpdateableColumn = true;
+ }
+ column.setProperty(COLUMN_CALCULATED, String.valueOf(field.isCalculated()));
+ column.setProperty(COLUMN_CUSTOM, String.valueOf(field.isCustom()));
+ column.setProperty(COLUMN_DEFAULTED, String.valueOf(field.isDefaultedOnCreate()));
+ }
+
+ }
+ }
+
+ private String getPicklistValues(Field field) {
+ StringBuffer picklistValues = new StringBuffer();
+ if(null != field.getPicklistValues() && 0 != field.getPicklistValues().size()) {
+ List<PicklistEntry> entries = field.getPicklistValues();
+ for (Iterator<PicklistEntry> iterator = entries.iterator(); iterator.hasNext();) {
+ PicklistEntry entry = iterator.next();
+ picklistValues.append(entry.getValue());
+ if(iterator.hasNext()) {
+ picklistValues.append(',');
+ }
+ }
+ }
+ return picklistValues.toString();
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/NameUtil.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/NameUtil.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/NameUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,85 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ *
+ * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
+ *
+ * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
+ */
+package org.teiid.resource.adapter.salesforce;
+
+import org.teiid.connector.language.SQLReservedWords;
+
+public class NameUtil {
+
+ public static String normalizeName( String nameIn ) {
+ String normal = nameIn.trim();
+ normal = removeDuplicate(normal);
+ normal = removeSpaces(normal);
+ normal = removeIllegalChars(normal);
+ normal = removeTrailingUnderscore(normal);
+ normal = removeLeadingUnderscore(normal);
+ normal = checkReservedWords(normal);
+ return normal;
+
+ }
+
+ /**
+ * @param normal
+ * @return
+ */
+ private static String checkReservedWords( String normal ) {
+ if (SQLReservedWords.isReservedWord(normal)) {
+ normal = normal + "_"; //$NON-NLS-1$
+ }
+ return normal;
+ }
+
+ private static String removeTrailingUnderscore( String normal ) {
+ if (normal.endsWith("_")) { //$NON-NLS-1$
+ return normal.substring(0, normal.lastIndexOf('_'));
+ }
+ return normal;
+ }
+
+ private static String removeIllegalChars( String normal ) {
+ String edit = normal;
+ edit = edit.replace('.', '_');
+ edit = edit.replace('(', '_');
+ edit = edit.replace(')', '_');
+ edit = edit.replace('/', '_');
+ edit = edit.replace('\\', '_');
+ edit = edit.replace(':', '_');
+ edit = edit.replace('\'', '_');
+ edit = edit.replace('-', '_');
+ edit = edit.replace("%", "percentage");//$NON-NLS-1$ //$NON-NLS-2$
+ edit = edit.replace("#", "number");//$NON-NLS-1$ //$NON-NLS-2$
+ edit = edit.replace("$", "_");//$NON-NLS-1$ //$NON-NLS-2$
+ edit = edit.replace("{", "_");//$NON-NLS-1$ //$NON-NLS-2$
+ edit = edit.replace("}", "_");//$NON-NLS-1$ //$NON-NLS-2$
+ return edit;
+ }
+
+ private static String removeSpaces( String normal ) {
+ return normal.replace(' ', '_');
+ }
+
+ private static String removeDuplicate( String normal ) {
+ if (normal.indexOf('(') < 0 || normal.indexOf(')') != normal.length() - 1) return normal;
+ String firstPart = normal.substring(0, normal.indexOf('(')).trim();
+ String secondPart = normal.substring(normal.indexOf('(') + 1, normal.length() - 1).trim();
+ if (firstPart.equals(secondPart) || secondPart.equals("null")) return firstPart; //$NON-NLS-1$
+ return normal;
+ }
+
+ /**
+ * @param normal
+ * @return
+ */
+ private static String removeLeadingUnderscore( String normal ) {
+ while (normal.indexOf('_') == 0) {
+ normal = normal.substring(1);
+ }
+ return normal;
+ }
+
+}
\ No newline at end of file
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Relationship.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Relationship.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Relationship.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,21 @@
+package org.teiid.resource.adapter.salesforce;
+
+public interface Relationship {
+
+ void setParentTable(String name);
+
+ void setChildTable(String childSObject);
+
+ void setForeignKeyField(String field);
+
+ void setCascadeDelete(boolean cascadeDelete);
+
+ public boolean isCascadeDelete();
+
+ public String getChildTable();
+
+ public String getForeignKeyField();
+
+ public String getParentTable();
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/RelationshipImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/RelationshipImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/RelationshipImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,40 @@
+package org.teiid.resource.adapter.salesforce;
+
+public class RelationshipImpl implements Relationship {
+ boolean cascadeDelete;
+ public String childTablename;
+ public String parentTableName;
+ public String foreignKeyField;
+
+ public void setCascadeDelete(boolean delete) {
+ cascadeDelete = delete;
+ }
+
+ public boolean isCascadeDelete() {
+ return cascadeDelete;
+ }
+
+ public void setChildTable(String childTable) {
+ childTablename = childTable;
+ }
+
+ public String getChildTable() {
+ return childTablename;
+ }
+
+ public String getForeignKeyField() {
+ return foreignKeyField;
+ }
+
+ public void setForeignKeyField(String foreignKeyField) {
+ this.foreignKeyField = foreignKeyField;
+ }
+
+ public String getParentTable() {
+ return parentTableName;
+ }
+
+ public void setParentTable(String parentTableName) {
+ this.parentTableName = parentTableName;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceExecutionFactory.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForceExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,111 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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 org.teiid.connector.language.Call;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.execution.DeleteExecutionImpl;
+import org.teiid.resource.adapter.salesforce.execution.InsertExecutionImpl;
+import org.teiid.resource.adapter.salesforce.execution.ProcedureExecutionParentImpl;
+import org.teiid.resource.adapter.salesforce.execution.QueryExecutionImpl;
+import org.teiid.resource.adapter.salesforce.execution.UpdateExecutionImpl;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.MetadataProvider;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TranslatorProperty;
+import org.teiid.resource.cci.UpdateExecution;
+
+
+public class SalesForceExecutionFactory extends org.teiid.resource.adapter.BasicExecutionFactory implements MetadataProvider {
+
+ private String connectorStateClass;
+ private boolean auditModelFields = false;
+
+
+ public String getConnectorStateClass() {
+ return this.connectorStateClass;
+ }
+ public void setConnectorStateClass(String connectorStateClass) {
+ this.connectorStateClass = connectorStateClass;
+ }
+
+ @TranslatorProperty(name="ModelAuditFields", display="Audit Model Fields", advanced=true, defaultValue="false")
+ public boolean isModelAuditFields() {
+ return this.auditModelFields;
+ }
+
+ public void setModelAuditFields(boolean modelAuditFields) {
+ this.auditModelFields = modelAuditFields;
+ }
+
+ @Override
+ public void start() throws ConnectorException {
+ super.start();
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Started"); //$NON-NLS-1$
+ }
+
+
+ @Override
+ public Class<? extends ConnectorCapabilities> getDefaultCapabilities() {
+ return SalesforceCapabilities.class;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ return new QueryExecutionImpl(command, (SalesforceConnection)connectionFactory, metadata, executionContext);
+ }
+
+ @Override
+ public UpdateExecution createUpdateExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory) throws ConnectorException {
+ UpdateExecution result = null;
+ if(command instanceof org.teiid.connector.language.Delete) {
+ result = new DeleteExecutionImpl(command, (SalesforceConnection)connectionFactory, metadata, executionContext);
+ } else if (command instanceof org.teiid.connector.language.Insert) {
+ result = new InsertExecutionImpl(command, (SalesforceConnection)connectionFactory, metadata, executionContext);
+ } else if (command instanceof org.teiid.connector.language.Update) {
+ result = new UpdateExecutionImpl(command, (SalesforceConnection)connectionFactory, metadata, executionContext);
+ }
+ return result;
+
+ }
+
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command,ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ return new ProcedureExecutionParentImpl(command, (SalesforceConnection)connectionFactory, metadata, executionContext);
+ }
+ @Override
+ public void getConnectorMetadata(MetadataFactory metadataFactory, Object connectionFactory) throws ConnectorException {
+ MetadataProcessor processor = new MetadataProcessor((SalesforceConnection)connectionFactory,metadataFactory, this);
+ processor.processMetadata();
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForcePlugin.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForcePlugin.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesForcePlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,45 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.util.ResourceBundle;
+
+import com.metamatrix.core.BundleUtil;
+
+/**
+ * For logging purposes
+ */
+public class SalesForcePlugin {
+
+ /**
+ * The plug-in identifier of this plugin
+ */
+ public static final String PLUGIN_ID = "org.teiid.resource.adapter.salesforce" ; //$NON-NLS-1$
+
+ /**
+ * Provides access to the plugin's log and to it's resources.
+ */
+ private static final String BUNDLE_NAME = PLUGIN_ID + ".i18n"; //$NON-NLS-1$
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,BUNDLE_NAME,ResourceBundle.getBundle(BUNDLE_NAME));
+
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceCapabilities.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceCapabilities.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.salesforce;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+public class SalesforceCapabilities extends BasicConnectorCapabilities {
+
+ public int getMaxInCriteriaSize() {
+ return 700;
+ }
+
+ public List getSupportedFunctions() {
+ List<String> supportedFunctions = new ArrayList<String>();
+ supportedFunctions.add("includes");
+ supportedFunctions.add("excludes");
+ return supportedFunctions;
+ }
+
+ public boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ public boolean supportsInCriteria() {
+ return true;
+ }
+
+ public boolean supportsLikeCriteria() {
+ return true;
+ }
+
+ public boolean supportsRowLimit() {
+ return true;
+ }
+
+ // http://jira.jboss.org/jira/browse/JBEDSP-306
+ // Salesforce supports ORDER BY, but not on all column types
+ public boolean supportsOrderBy() {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAggregatesCountStar() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsNotCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrCriteria() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCompareCriteriaOrdered() {
+ return true;
+ }
+
+ @Override
+ public SupportedJoinCriteria getSupportedJoinCriteria() {
+ return SupportedJoinCriteria.KEY;
+ }
+
+ @Override
+ public boolean supportsOuterJoins() {
+ return true;
+ }
+
+
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnection.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnection.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/SalesforceConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,60 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.util.List;
+
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.execution.DataPayload;
+import org.teiid.resource.adapter.salesforce.execution.DeletedResult;
+import org.teiid.resource.adapter.salesforce.execution.UpdatedResult;
+
+import com.sforce.soap.partner.DescribeGlobalResult;
+import com.sforce.soap.partner.DescribeSObjectResult;
+import com.sforce.soap.partner.QueryResult;
+
+public interface SalesforceConnection {
+
+ public QueryResult query(String queryString, int maxBatchSize, Boolean queryAll) throws ConnectorException;
+
+ public QueryResult queryMore(String queryLocator, int batchSize) throws ConnectorException;
+
+ public boolean isAlive();
+
+ public int delete(String[] ids) throws ConnectorException ;
+
+ public int create(DataPayload data) throws ConnectorException;
+
+ public int update(List<DataPayload> updateDataList) throws ConnectorException;
+
+ public UpdatedResult getUpdated(String objectName, XMLGregorianCalendar startCalendar, XMLGregorianCalendar endCalendar) throws ConnectorException;
+
+ public DeletedResult getDeleted(String objectName, XMLGregorianCalendar startCalendar, XMLGregorianCalendar endCalendar) throws ConnectorException;
+
+ public QueryResult retrieve(String fieldList, String sObjectType, List<String> ids) throws ConnectorException;
+
+ public DescribeGlobalResult getObjects() throws ConnectorException;
+
+ public DescribeSObjectResult getObjectMetaData(String objectName) throws ConnectorException;
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Util.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Util.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/Util.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,71 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.salesforce;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+import org.teiid.resource.ConnectorException;
+
+
+public class Util {
+
+ public static String stripQutes(String id) {
+ if((id.startsWith("'") && id.endsWith("'"))) {
+ id = id.substring(1,id.length()-1);
+ } else if ((id.startsWith("\"") && id.endsWith("\""))) {
+ id = id.substring(1,id.length()-1);
+ }
+ return id;
+ }
+
+ public static String addSingleQuotes(String text) {
+ StringBuffer result = new StringBuffer();
+ if(!text.startsWith("'")) {
+ result.append('\'');
+ }
+ result.append(text);
+ if(!text.endsWith("'")) {
+ result.append('\'');
+ }
+ return result.toString();
+ }
+
+ public static void validateQueryLength(StringBuffer query) throws ConnectorException {
+ if(query.length() >= 10000) {
+ throw new ConnectorException(Messages.getString("Util.query.exceeds.max.length"));
+ }
+ }
+
+ public static SimpleDateFormat getSalesforceDateTimeFormat() {
+ return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ }
+
+ public static SimpleDateFormat getTimeZoneOffsetFormat() {
+ return new SimpleDateFormat("Z");
+ }
+
+ public static DateFormat getSalesforceDateFormat() {
+ return new SimpleDateFormat("yyyy-MM-dd");
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/AbstractUpdateExecution.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/AbstractUpdateExecution.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/AbstractUpdateExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,115 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution;
+
+import java.util.ArrayList;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.Condition;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.Util;
+import org.teiid.resource.adapter.salesforce.execution.visitors.IQueryProvidingVisitor;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.UpdateExecution;
+
+import com.sforce.soap.partner.QueryResult;
+import com.sforce.soap.partner.sobject.SObject;
+
+/**
+ *
+ * Parent class to the Update, Delete, and Insert execution classes.
+ * Provisions the correct impl and contains some common code to
+ * get IDs of Salesforce objects.
+ *
+ */
+public abstract class AbstractUpdateExecution extends BasicExecution implements UpdateExecution {
+
+ protected SalesforceConnection connection;
+ protected RuntimeMetadata metadata;
+ protected ExecutionContext context;
+ protected Command command;
+ protected int result;
+
+ public AbstractUpdateExecution(Command command,
+ SalesforceConnection salesforceConnection,
+ RuntimeMetadata metadata, ExecutionContext context) {
+ this.connection = salesforceConnection;
+ this.metadata = metadata;
+ this.context = context;
+ this.command = command;
+ }
+
+ @Override
+ public void cancel() throws ConnectorException {
+ }
+
+ @Override
+ public void close() throws ConnectorException {
+ }
+
+ @Override
+ public int[] getUpdateCounts() throws DataNotAvailableException,
+ ConnectorException {
+ return new int[] {result};
+ }
+
+ public RuntimeMetadata getMetadata() {
+ return metadata;
+ }
+
+ public SalesforceConnection getConnection() {
+ return connection;
+ }
+
+ String[] getIDs(Condition criteria, IQueryProvidingVisitor visitor) throws ConnectorException {
+ String[] Ids = null;
+ if (visitor.hasOnlyIDCriteria()) {
+ try {
+ String Id = ((Comparison)criteria).getRightExpression().toString();
+ Id = Util.stripQutes(Id);
+ Ids = new String[] { Id };
+ } catch (ClassCastException cce) {
+ throw new RuntimeException(
+ "Error: The delete criteria is not a CompareCriteria");
+ }
+
+ } else if (visitor.hasCriteria()) {
+ String query = visitor.getQuery();
+ QueryResult results = getConnection().query(query, context.getBatchSize(), Boolean.FALSE);
+ if (null != results && results.getSize() > 0) {
+ ArrayList<String> idList = new ArrayList<String>(results
+ .getRecords().size());
+ for (int i = 0; i < results.getRecords().size(); i++) {
+ SObject sObject = results.getRecords().get(i);
+ idList.add(sObject.getId());
+ }
+ Ids = idList.toArray(new String[0]);
+ }
+ }
+ return Ids;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DataPayload.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DataPayload.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DataPayload.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution;
+
+import java.util.List;
+
+import javax.xml.bind.JAXBElement;
+
+/**
+ *
+ * A bucket to pass data to the Salesforce connection.
+ *
+ */
+public class DataPayload {
+
+ private String type;
+ @SuppressWarnings("unchecked")
+ private List<JAXBElement> messageElements;
+ private String id;
+
+ public void setType(String typeName) {
+ type = typeName;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void setMessageElements(List<JAXBElement> elements) {
+ this.messageElements = elements;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<JAXBElement> getMessageElements() {
+ return messageElements;
+ }
+
+ public void setID(String id) {
+ this.id = id;
+ }
+
+ public String getID() {
+ return id;
+ }
+}
\ No newline at end of file
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeleteExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeleteExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeleteExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution;
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Delete;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.execution.visitors.DeleteVisitor;
+import org.teiid.resource.cci.ExecutionContext;
+
+
+public class DeleteExecutionImpl extends AbstractUpdateExecution {
+
+
+ public DeleteExecutionImpl(Command command,
+ SalesforceConnection salesforceConnection,
+ RuntimeMetadata metadata, ExecutionContext context) {
+ super(command, salesforceConnection, metadata, context);
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ DeleteVisitor dVisitor = new DeleteVisitor(getMetadata());
+ dVisitor.visitNode(command);
+ String[] Ids = getIDs(((Delete)command).getWhere(), dVisitor);
+ if(null != Ids && Ids.length > 0) {
+ result = getConnection().delete(Ids);
+ }
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedObject.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedObject.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedObject.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,22 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.util.Calendar;
+
+public class DeletedObject {
+
+ String ID;
+ Calendar deletedDate;
+
+ public String getID() {
+ return ID;
+ }
+ public void setID(String id) {
+ ID = id;
+ }
+ public Calendar getDeletedDate() {
+ return deletedDate;
+ }
+ public void setDeletedDate(Calendar deletedDate) {
+ this.deletedDate = deletedDate;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedResult.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedResult.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/DeletedResult.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,36 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.util.Calendar;
+import java.util.List;
+
+public class DeletedResult {
+
+ private Calendar latestDateCovered;
+ private Calendar earliestDateAvailable;
+ private List<DeletedObject> resultRecords;
+
+ public Calendar getLatestDateCovered() {
+ return latestDateCovered;
+ }
+
+ public void setLatestDateCovered(Calendar latestDateCovered) {
+ this.latestDateCovered = latestDateCovered;
+ }
+
+
+ public Calendar getEarliestDateAvailable() {
+ return earliestDateAvailable;
+ }
+
+ public void setEarliestDateAvailable(Calendar earliestDateAvailable) {
+ this.earliestDateAvailable = earliestDateAvailable;
+ }
+
+ public void setResultRecords(List<DeletedObject> resultRecords) {
+ this.resultRecords = resultRecords;
+ }
+
+ public List<DeletedObject> getResultRecords() {
+ return resultRecords;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetDeletedExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetDeletedExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetDeletedExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,106 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.GregorianCalendar;
+import java.util.List;
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.Call;
+import org.teiid.resource.ConnectorException;
+
+/**
+ *
+ * The structure of the getDeleted procedure is:
+ * Salesforce object type: String: IN param
+ * startDate: datatime: IN param
+ * enddate: datetime: IN param
+ * earliestDateAvailable: datetime: OUT param
+ * latestDateCovered: datetime: OUT param
+ * getUpdatedResult: resultset: OUT param
+ *
+ */
+
+public class GetDeletedExecutionImpl implements SalesforceProcedureExecution {
+
+ private static final int EARLIESTDATEAVAILABLE = 4;
+ private static final int RESULT = 5;
+
+ private ProcedureExecutionParent parent;
+
+ private DeletedResult deletedResult;
+ private int resultIndex = 0;
+ DatatypeFactory factory;
+
+ public GetDeletedExecutionImpl(
+ ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
+ this.parent = procedureExecutionParent;
+ try {
+ factory = DatatypeFactory.newInstance();
+ } catch (DatatypeConfigurationException e) {
+ throw new ConnectorException(e.getMessage());
+ }
+ }
+
+ @Override
+ public void cancel() {
+ // nothing to do here
+
+ }
+
+ @Override
+ public void close() {
+ // nothing to do here
+
+ }
+
+ @Override
+ public void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
+ Call command = parent.getCommand();
+ List<Argument> params = command.getArguments();
+
+ Argument object = params.get(OBJECT);
+ String objectName = (String) object.getArgumentValue().getValue();
+
+ Argument start = params.get(STARTDATE);
+ Timestamp startTime = (Timestamp) start.getArgumentValue().getValue();
+ GregorianCalendar tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
+ tempCalendar.setTime(startTime);
+ XMLGregorianCalendar startCalendar = factory.newXMLGregorianCalendar(tempCalendar);
+
+ Argument end = params.get(ENDDATE);
+ Timestamp endTime = (Timestamp) end.getArgumentValue().getValue();
+ tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
+ tempCalendar.setTime(endTime);
+ XMLGregorianCalendar endCalendar = factory.newXMLGregorianCalendar(tempCalendar);
+
+ deletedResult = parent.getConnection().getDeleted(objectName, startCalendar, endCalendar);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<?> getOutputParameterValues() {
+ List result = new ArrayList();
+ result.add(deletedResult.getLatestDateCovered());
+ result.add(deletedResult.getEarliestDateAvailable());
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<?> next() {
+ List result = null;
+ if(deletedResult.getResultRecords() != null && resultIndex < deletedResult.getResultRecords().size()){
+ result = new ArrayList(2);
+ result.add(deletedResult.getResultRecords().get(resultIndex).getID());
+ result.add(deletedResult.getResultRecords().get(resultIndex).getDeletedDate());
+ resultIndex++;
+ }
+ return result;
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetUpdatedExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetUpdatedExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/GetUpdatedExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,99 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.List;
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.teiid.connector.language.Argument;
+import org.teiid.connector.language.Call;
+import org.teiid.resource.ConnectorException;
+
+/**
+ *
+ * The structure of the getUpdated procedure is:
+ * Salesforce object type: String: IN param
+ * startDate: datatime: IN param
+ * enddate: datetime: IN param
+ * latestDateCovered: datetime: OUT param
+ * getUpdatedResult: resultset: OUT param
+ *
+ */
+
+public class GetUpdatedExecutionImpl implements SalesforceProcedureExecution {
+
+ private static final int RESULT = 4;
+
+ private ProcedureExecutionParent parent;
+ private UpdatedResult updatedResult;
+ private int idIndex = 0;
+ DatatypeFactory factory;
+
+ public GetUpdatedExecutionImpl(
+ ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
+ this.parent = procedureExecutionParent;
+ try {
+ factory = DatatypeFactory.newInstance();
+ } catch (DatatypeConfigurationException e) {
+ throw new ConnectorException(e.getMessage());
+ }
+ }
+
+ @Override
+ public void cancel() {
+ // nothing to do here
+ }
+
+ @Override
+ public void close() {
+ // nothing to do here
+ }
+
+ @Override
+ public void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException {
+ Call command = parent.getCommand();
+ List<Argument> params = command.getArguments();
+
+ Argument object = params.get(OBJECT);
+ String objectName = (String) object.getArgumentValue().getValue();
+
+ Argument start = params.get(STARTDATE);
+ Timestamp startTime = (Timestamp) start.getArgumentValue().getValue();
+ GregorianCalendar tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
+ tempCalendar.setTime(startTime);
+ XMLGregorianCalendar startCalendar = factory.newXMLGregorianCalendar(tempCalendar);
+
+ Argument end = params.get(ENDDATE);
+ Timestamp endTime = (Timestamp) end.getArgumentValue().getValue();
+ tempCalendar = (GregorianCalendar) GregorianCalendar.getInstance();
+ tempCalendar.setTime(endTime);
+ XMLGregorianCalendar endCalendar = factory.newXMLGregorianCalendar(tempCalendar);
+
+ updatedResult = parent.getConnection().getUpdated(objectName, startCalendar, endCalendar);
+ }
+
+ @Override
+ public List<Calendar> getOutputParameterValues() {
+ List<Calendar> result = new ArrayList<Calendar>(1);
+ result.add(updatedResult.getLatestDateCovered());
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List next() {
+ List result = null;
+ if(updatedResult.getIDs() != null && idIndex < updatedResult.getIDs().size()){
+ result = new ArrayList(1);
+ result.add(updatedResult.getIDs().get(idIndex));
+ idIndex++;
+ }
+ return result;
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/InsertExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/InsertExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/InsertExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution;
+
+
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.execution.visitors.InsertVisitor;
+import org.teiid.resource.cci.ExecutionContext;
+
+
+public class InsertExecutionImpl extends AbstractUpdateExecution {
+
+ public InsertExecutionImpl(Command command,
+ SalesforceConnection salesforceConnection,
+ RuntimeMetadata metadata, ExecutionContext context) {
+ super(command, salesforceConnection, metadata, context);
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ InsertVisitor visitor = new InsertVisitor(getMetadata());
+ visitor.visit((Insert)command);
+ DataPayload data = new DataPayload();
+ data.setType(visitor.getTableName());
+ data.setMessageElements(visitor.getMessageElements());
+ result = getConnection().create(data);
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParent.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParent.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParent.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,18 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import org.teiid.connector.language.Call;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.cci.ExecutionContext;
+
+
+public interface ProcedureExecutionParent {
+
+ public Call getCommand();
+
+ public ExecutionContext getExecutionContext();
+
+ public RuntimeMetadata getMetadata();
+
+ public SalesforceConnection getConnection();
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParentImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParentImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/ProcedureExecutionParentImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,93 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.util.List;
+
+import org.teiid.connector.language.Call;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ProcedureExecution;
+
+
+public class ProcedureExecutionParentImpl implements ProcedureExecution, ProcedureExecutionParent {
+
+ private Call command;
+ private ExecutionContext executionContext;
+ private RuntimeMetadata metadata;
+ private SalesforceProcedureExecution execution;
+ private SalesforceConnection connection;
+
+ public ProcedureExecutionParentImpl(Call command,
+ SalesforceConnection connection, RuntimeMetadata metadata, ExecutionContext executionContext) {
+ this.setCommand(command);
+ this.setConnection(connection);
+ this.setMetadata(metadata);
+ this.setExecutionContext(executionContext);
+ }
+
+ @Override
+ public List<?> getOutputParameterValues() throws ConnectorException {
+ return execution.getOutputParameterValues();
+ }
+
+ @Override
+ public List<?> next() throws ConnectorException, DataNotAvailableException {
+ return execution.next();
+ }
+
+ @Override
+ public void cancel() throws ConnectorException {
+ execution.cancel();
+ }
+
+ @Override
+ public void close() throws ConnectorException {
+ execution.close();
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ if(getCommand().getProcedureName().endsWith("getUpdated")) {
+ execution = new GetUpdatedExecutionImpl(this);
+ execution.execute(this);
+ }
+ else if(getCommand().getProcedureName().endsWith("getDeleted")) {
+ execution = new GetDeletedExecutionImpl(this);
+ execution.execute(this);
+ }
+ }
+
+ public void setCommand(Call command) {
+ this.command = command;
+ }
+
+ public Call getCommand() {
+ return command;
+ }
+
+ private void setConnection(SalesforceConnection connection) {
+ this.connection = connection;
+ }
+
+ public SalesforceConnection getConnection() {
+ return connection;
+ }
+
+ private void setExecutionContext(ExecutionContext executionContext) {
+ this.executionContext = executionContext;
+ }
+
+ public ExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+
+ private void setMetadata(RuntimeMetadata metadata) {
+ this.metadata = metadata;
+ }
+
+ public RuntimeMetadata getMetadata() {
+ return metadata;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/QueryExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/QueryExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/QueryExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.adapter.salesforce.execution;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+
+import org.teiid.connector.language.AggregateFunction;
+import org.teiid.connector.language.Join;
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.language.TableReference;
+import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.adapter.salesforce.Messages;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.Util;
+import org.teiid.resource.adapter.salesforce.execution.visitors.JoinQueryVisitor;
+import org.teiid.resource.adapter.salesforce.execution.visitors.SelectVisitor;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.w3c.dom.Element;
+
+import com.sforce.soap.partner.QueryResult;
+import com.sforce.soap.partner.sobject.SObject;
+
+public class QueryExecutionImpl extends BasicExecution implements ResultSetExecution {
+
+ private SalesforceConnection connection;
+
+ private RuntimeMetadata metadata;
+
+ private ExecutionContext context;
+
+
+ private SelectVisitor visitor;
+
+ private QueryResult results;
+
+ private List<List<Object>> resultBatch;
+
+ // Identifying values
+ private String connectionIdentifier;
+
+ private String connectorIdentifier;
+
+ private String requestIdentifier;
+
+ private String partIdentifier;
+
+ private String logPreamble;
+
+ private QueryExpression query;
+
+ Map<String, Map<String,Integer>> sObjectToResponseField = new HashMap<String, Map<String,Integer>>();
+
+ private int topResultIndex = 0;
+
+ public QueryExecutionImpl(QueryExpression command, SalesforceConnection connection, RuntimeMetadata metadata, ExecutionContext context) {
+ this.connection = connection;
+ this.metadata = metadata;
+ this.context = context;
+ this.query = command;
+
+ connectionIdentifier = context.getConnectionIdentifier();
+ connectorIdentifier = context.getConnectorIdentifier();
+ requestIdentifier = context.getRequestIdentifier();
+ partIdentifier = context.getPartIdentifier();
+ }
+
+ public void cancel() throws ConnectorException {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, Messages.getString("SalesforceQueryExecutionImpl.cancel"));//$NON-NLS-1$
+ }
+
+ public void close() throws ConnectorException {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, Messages.getString("SalesforceQueryExecutionImpl.close")); //$NON-NLS-1$
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble() + "Incoming Query: " + query.toString()); //$NON-NLS-1$
+ List<TableReference> from = ((Select)query).getFrom();
+ String finalQuery;
+ if(from.get(0) instanceof Join) {
+ visitor = new JoinQueryVisitor(metadata);
+ visitor.visitNode(query);
+ finalQuery = visitor.getQuery().trim();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble() + "Executing Query: " + finalQuery); //$NON-NLS-1$
+
+ results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
+ } else {
+ visitor = new SelectVisitor(metadata);
+ visitor.visitNode(query);
+ if(visitor.canRetrieve()) {
+ results = connection.retrieve(visitor.getRetrieveFieldList(),
+ visitor.getTableName(), visitor.getIdInCriteria());
+ } else {
+ finalQuery = visitor.getQuery().trim();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, getLogPreamble() + "Executing Query: " + finalQuery); //$NON-NLS-1$
+ results = connection.query(finalQuery, this.context.getBatchSize(), visitor.getQueryAll());
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List next() throws ConnectorException, DataNotAvailableException {
+ List<?> result;
+ if (query.getProjectedQuery().getDerivedColumns().get(0)
+ .getExpression() instanceof AggregateFunction) {
+ result = Arrays.asList(results.getSize());
+ results = null;
+
+ } else {
+ result = getRow(results);
+ }
+ return result;
+ }
+
+ private List<Object> getRow(QueryResult result) throws ConnectorException {
+ List<Object> row;
+ if(null == resultBatch) {
+ loadBatch();
+ }
+ if(resultBatch.size() == topResultIndex) {
+ row = null;
+ } else {
+ row = resultBatch.get(topResultIndex);
+ topResultIndex++;
+ if(resultBatch.size() == topResultIndex) {
+ if(!result.isDone()) {
+ loadBatch();
+ }
+ }
+
+ }
+ return row;
+ }
+
+ private void loadBatch() throws ConnectorException {
+ if(null != resultBatch) { // if we have an old batch, then we have to get new results
+ results = connection.queryMore(results.getQueryLocator(), context.getBatchSize());
+ }
+ resultBatch = new ArrayList<List<Object>>();
+
+ for(int resultIndex = 0; resultIndex < results.getSize(); resultIndex++) {
+ SObject sObject = results.getRecords().get(resultIndex);
+ List<Object[]> result = getObjectData(sObject);
+ for(Iterator<Object[]> i = result.iterator(); i.hasNext(); ) {
+ resultBatch.add(Arrays.asList(i.next()));
+ }
+ }
+ }
+
+ private List<Object[]> getObjectData(SObject sObject) throws ConnectorException {
+ List<Object> topFields = sObject.getAny();
+ logAndMapFields(sObject.getType(), topFields);
+ List<Object[]> result = new ArrayList<Object[]>();
+ for(int i = 0; i < topFields.size(); i++) {
+ Element element = (Element) topFields.get(i);
+ QName qName = new QName(element.getNamespaceURI(), element.getLocalName());
+ if(null != qName) {
+ String type = qName.getLocalPart();
+ if(type.equals("sObject")) { //$NON-NLS-1$
+ //SObject parent = (SObject)element.;
+ //result.addAll(getObjectData(parent));
+ } else if(type.equals("QueryResult")) { //$NON-NLS-1$
+ //QueryResult subResult = (QueryResult)element.getValue();
+ //for(int resultIndex = 0; resultIndex < subResult.getSize(); resultIndex++) {
+ // SObject subObject = subResult.getRecords().get(resultIndex);
+ // result.addAll(getObjectData(subObject));
+ //}
+ }
+ }
+ }
+ return extractDataFromFields(sObject, topFields, result);
+
+ }
+
+ private List<Object[]> extractDataFromFields(SObject sObject,
+ List<Object> fields, List<Object[]> result) throws ConnectorException {
+ Map<String,Integer> fieldToIndexMap = sObjectToResponseField.get(sObject.getType());
+ for (int j = 0; j < visitor.getSelectSymbolCount(); j++) {
+ Column element = visitor.getSelectSymbolMetadata(j);
+ AbstractMetadataRecord parent = element.getParent();
+ Table table;
+ if(parent instanceof Table) {
+ table = (Table)parent;
+ } else {
+ parent = parent.getParent();
+ if(parent instanceof Table) {
+ table = (Table)parent;
+ } else {
+ throw new ConnectorException("Could not resolve Table for column " + element.getName()); //$NON-NLS-1$
+ }
+ }
+ if(table.getNameInSource().equals(sObject.getType())) {
+ Integer index = fieldToIndexMap.get(element.getNameInSource());
+ // id gets dropped from the result if it is not the
+ // first field in the querystring. Add it back in.
+ if (null == index) {
+ if (element.getNameInSource().equalsIgnoreCase("id")) { //$NON-NLS-1$
+ setValueInColumn(j, sObject.getId(), result);
+ } else {
+ throw new ConnectorException("SalesforceQueryExecutionImpl.missing.field"+ element.getNameInSource()); //$NON-NLS-1$
+ }
+ } else {
+ Object cell;
+ cell = getCellDatum(element, (Element)fields.get(index));
+ setValueInColumn(j, cell, result);
+ }
+ }
+ }
+ return result;
+ }
+
+ private void setValueInColumn(int columnIndex, Object value, List<Object[]> result) {
+ if(result.isEmpty()) {
+ Object[] row = new Object[visitor.getSelectSymbolCount()];
+ result.add(row);
+ }
+ Iterator<Object[]> iter = result.iterator();
+ while (iter.hasNext()) {
+ Object[] row = iter.next();
+ row[columnIndex] = value;
+ }
+ }
+
+ /**
+ * Load the map of response field names to index.
+ * @param fields
+ * @throws ConnectorException
+ */
+ private void logAndMapFields(String sObjectName,
+ List<Object> fields) throws ConnectorException {
+ if (!sObjectToResponseField.containsKey(sObjectName)) {
+ logFields(sObjectName, fields);
+ Map<String, Integer> responseFieldToIndexMap;
+ responseFieldToIndexMap = new HashMap<String, Integer>();
+ for (int x = 0; x < fields.size(); x++) {
+ Element element = (Element) fields.get(x);
+ responseFieldToIndexMap.put(element.getLocalName(), x);
+ }
+ sObjectToResponseField.put(sObjectName, responseFieldToIndexMap);
+ }
+ }
+
+ private void logFields(String sObjectName, List<Object> fields) throws ConnectorException {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "SalesForce Object Name = " + sObjectName); //$NON-NLS-1$
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "FieldCount = " + fields.size()); //$NON-NLS-1$
+ for(int i = 0; i < fields.size(); i++) {
+ Element element;
+ element = (Element) fields.get(i);
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Field # " + i + " is " + element.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private Object getCellDatum(Column element, Element elem) throws ConnectorException {
+ if(!element.getNameInSource().equals(elem.getLocalName())) {
+ throw new ConnectorException("SalesforceQueryExecutionImpl.column.mismatch1" + element.getNameInSource() + "SalesforceQueryExecutionImpl.column.mismatch2" + elem.getLocalName()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ String value = elem.getTextContent();
+ Object result = null;
+ Class type = element.getJavaType();
+
+ if(type.equals(String.class)) {
+ result = value;
+ }
+ else if (type.equals(Boolean.class)) {
+ result = Boolean.valueOf(value);
+ } else if (type.equals(Double.class)) {
+ if (null != value) {
+ if(value.isEmpty()) {
+ result = null;
+ } else {
+ result = Double.valueOf(value);
+ }
+ }
+ } else if (type.equals(Integer.class)) {
+ if (null != value) {
+ if(value.isEmpty()) {
+ result = null;
+ } else {
+ result = Integer.valueOf(value);
+ }
+ }
+ } else if (type.equals(java.sql.Date.class)) {
+ if (null != value) {
+ if(value.isEmpty()) {
+ result = null;
+ } else {
+ result = java.sql.Date.valueOf(value);
+ }
+ }
+ } else if (type.equals(java.sql.Timestamp.class)) {
+ if (null != value) {
+ if(value.isEmpty()) {
+ result = null;
+ } else try {
+ Date date = Util.getSalesforceDateTimeFormat().parse(value);
+ result = new Timestamp(date.getTime());
+ } catch (ParseException e) {
+ throw new ConnectorException(e, "SalesforceQueryExecutionImpl.datatime.parse" + value); //$NON-NLS-1$
+ }
+ }
+ } else {
+ result = value;
+ }
+ return result;
+ }
+
+
+ private String getLogPreamble() {
+ if (null == logPreamble) {
+ StringBuffer preamble = new StringBuffer();
+ preamble.append(connectorIdentifier);
+ preamble.append('.');
+ preamble.append(connectionIdentifier);
+ preamble.append('.');
+ preamble.append(requestIdentifier);
+ preamble.append('.');
+ preamble.append(partIdentifier);
+ preamble.append(": "); //$NON-NLS-1$
+ logPreamble = preamble.toString();
+ }
+ return logPreamble;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/SalesforceProcedureExecution.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/SalesforceProcedureExecution.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/SalesforceProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,24 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.util.List;
+
+import org.teiid.resource.ConnectorException;
+
+public interface SalesforceProcedureExecution {
+
+ static final int OBJECT = 0;
+ static final int STARTDATE = 1;
+ static final int ENDDATE = 2;
+ static final int LATESTDATECOVERED = 3;
+
+ List<?> getOutputParameterValues();
+
+ List<?> next();
+
+ void cancel();
+
+ void close();
+
+ void execute(ProcedureExecutionParent procedureExecutionParent) throws ConnectorException;
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdateExecutionImpl.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdateExecutionImpl.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdateExecutionImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,84 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.JAXBElement;
+import javax.xml.namespace.QName;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.SetClause;
+import org.teiid.connector.language.Update;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.SalesforceConnection;
+import org.teiid.resource.adapter.salesforce.Util;
+import org.teiid.resource.adapter.salesforce.execution.visitors.UpdateVisitor;
+import org.teiid.resource.cci.ExecutionContext;
+
+
+public class UpdateExecutionImpl extends AbstractUpdateExecution {
+
+ @SuppressWarnings("unchecked")
+ private static final Class stringClazz = new String().getClass();
+
+ public UpdateExecutionImpl(Command command,
+ SalesforceConnection salesforceConnection,
+ RuntimeMetadata metadata, ExecutionContext context) {
+ super(command, salesforceConnection, metadata, context);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public void execute() throws ConnectorException {
+ UpdateVisitor visitor = new UpdateVisitor(getMetadata());
+ visitor.visit((Update)command);
+ String[] Ids = getIDs(((Update)command).getWhere(), visitor);
+
+ if (null != Ids && Ids.length > 0) {
+ List<JAXBElement> elements = new ArrayList<JAXBElement>();
+ for (SetClause clause : ((Update)command).getChanges()) {
+ ColumnReference element = clause.getSymbol();
+ Column column = element.getMetadataObject();
+ String val = ((Literal) clause.getValue()).toString();
+ JAXBElement messageElem = new JAXBElement(new QName(column.getNameInSource()), stringClazz, Util.stripQutes(val));
+ elements.add(messageElem);
+ }
+
+ List<DataPayload> updateDataList = new ArrayList<DataPayload>();
+ for (int i = 0; i < Ids.length; i++) {
+ DataPayload data = new DataPayload();
+ data.setType(visitor.getTableName());
+ data.setID(Ids[i]);
+ data.setMessageElements(elements);
+ updateDataList.add(data);
+ }
+
+ result = getConnection().update(updateDataList);
+ }
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdatedResult.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdatedResult.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/UpdatedResult.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,26 @@
+package org.teiid.resource.adapter.salesforce.execution;
+
+import java.util.Calendar;
+import java.util.List;
+
+public class UpdatedResult {
+
+ private Calendar latestDateCovered;
+ private List<String> IDs;
+
+ public Calendar getLatestDateCovered() {
+ return latestDateCovered;
+ }
+
+ public void setLatestDateCovered(Calendar latestDateCovered) {
+ this.latestDateCovered = latestDateCovered;
+ }
+
+ public List<String> getIDs() {
+ return IDs;
+ }
+
+ public void setIDs(List<String> list) {
+ this.IDs = list;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/CriteriaVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/CriteriaVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/CriteriaVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,455 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.AndOr;
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Function;
+import org.teiid.connector.language.In;
+import org.teiid.connector.language.Like;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.Not;
+import org.teiid.connector.language.Comparison.Operator;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.connector.visitor.framework.HierarchyVisitor;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.Messages;
+import org.teiid.resource.adapter.salesforce.Util;
+
+
+/**
+ * Parses Criteria in support of all of the ExecutionImpl classes.
+ */
+public abstract class CriteriaVisitor extends HierarchyVisitor implements ICriteriaVisitor {
+
+ private static final String RESTRICTEDMULTISELECTPICKLIST = "restrictedmultiselectpicklist";
+ private static final String MULTIPICKLIST = "multipicklist";
+ protected static final String SELECT = "SELECT";
+ protected static final String FROM = "FROM";
+ protected static final String WHERE = "WHERE";
+ protected static final String ORDER_BY = "ORDER BY";
+ protected static final String LIMIT = "LIMIT";
+ protected static final String SPACE = " ";
+ protected static final String EXCLUDES = "EXCLUDES";
+ protected static final String INCLUDES = "includes";
+ protected static final String COMMA = ",";
+ protected static final String SEMI = ";";
+ protected static final String APOS = "'";
+ protected static final String OPEN = "(";
+ protected static final String CLOSE = ")";
+
+ protected RuntimeMetadata metadata;
+ private HashMap<Comparison.Operator, String> comparisonOperators;
+ protected List<String> criteriaList = new ArrayList<String>();
+ protected boolean hasCriteria;
+ protected Map<String, Column> columnElementsByName = new HashMap<String, Column>();
+ protected List<ConnectorException> exceptions = new ArrayList<ConnectorException>();
+ protected Table table;
+ boolean onlyIDCriteria;
+ protected Boolean queryAll = Boolean.FALSE;
+
+ // support for invoking a retrieve when possible.
+ protected In idInCriteria = null;
+
+
+ public CriteriaVisitor( RuntimeMetadata metadata ) {
+ this.metadata = metadata;
+ comparisonOperators = new HashMap<Comparison.Operator, String>();
+ comparisonOperators.put(Operator.EQ, "=");
+ comparisonOperators.put(Operator.GE, ">=");
+ comparisonOperators.put(Operator.GT, ">");
+ comparisonOperators.put(Operator.LE, "<=");
+ comparisonOperators.put(Operator.LT, "<");
+ comparisonOperators.put(Operator.NE, "!=");
+ }
+
+ @Override
+ public void visit( Comparison criteria ) {
+ super.visit(criteria);
+ try {
+ addCompareCriteria(criteriaList, criteria);
+ boolean isAcceptableID = (Operator.EQ == criteria.getOperator() && isIdColumn(criteria.getLeftExpression()));
+ setHasCriteria(true, isAcceptableID);
+ } catch (ConnectorException e) {
+ exceptions.add(e);
+ }
+ }
+
+ @Override
+ public void visit( Like criteria ) {
+ try {
+ if (isIdColumn(criteria.getLeftExpression())) {
+ ConnectorException e = new ConnectorException(Messages.getString("CriteriaVisitor.LIKE.not.supported.on.Id"));
+ exceptions.add(e);
+ }
+ if (isMultiSelectColumn(criteria.getLeftExpression())) {
+ ConnectorException e = new ConnectorException(
+ Messages.getString("CriteriaVisitor.LIKE.not.supported.on.multiselect"));
+ exceptions.add(e);
+ }
+ } catch (ConnectorException e) {
+ exceptions.add(e);
+ }
+ boolean negated = criteria.isNegated();
+ criteria.setNegated(false);
+ criteriaList.add(criteria.toString());
+ if (negated) {
+ addNot();
+ criteria.setNegated(true);
+ }
+ // don't check if it's ID, Id LIKE '123%' still requires a query
+ setHasCriteria(true, false);
+ }
+
+ @Override
+ public void visit(AndOr obj) {
+ List<String> savedCriteria = new LinkedList<String>();
+ savedCriteria.add(OPEN);
+ super.visitNode(obj.getLeftCondition());
+ savedCriteria.addAll(this.criteriaList);
+ this.criteriaList.clear();
+ savedCriteria.add(CLOSE);
+ savedCriteria.add(SPACE);
+ savedCriteria.add(obj.getOperator().toString());
+ savedCriteria.add(SPACE);
+ savedCriteria.add(OPEN);
+ super.visitNode(obj.getRightCondition());
+ savedCriteria.addAll(this.criteriaList);
+ this.criteriaList.clear();
+ this.criteriaList = savedCriteria;
+ this.criteriaList.add(CLOSE);
+ }
+
+ @Override
+ public void visit(Not obj) {
+ super.visit(obj);
+ addNot();
+ }
+
+ private void addNot() {
+ if (!criteriaList.isEmpty()) {
+ criteriaList.add(0, "NOT ("); //$NON-NLS-1$
+ criteriaList.add(CLOSE);
+ }
+ }
+
+ @Override
+ public void visit( In criteria ) {
+ try {
+ Expression lExpr = criteria.getLeftExpression();
+ String columnName = lExpr.toString();
+ if (columnElementsByName.containsKey(columnName)) {
+ Column column = columnElementsByName.get(columnName);
+ if (MULTIPICKLIST.equalsIgnoreCase(column.getNativeType()) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(column.getNativeType())) {
+ appendMultiselectIn(column, criteria);
+ } else {
+ appendCriteria(criteria);
+ }
+ }
+ setHasCriteria(true, isIdColumn(criteria.getLeftExpression()));
+ } catch (ConnectorException e) {
+ exceptions.add(e);
+ }
+ }
+
+ public void parseFunction( Function func ) {
+ String functionName = func.getName();
+ try {
+ if (functionName.equalsIgnoreCase("includes")) {
+ generateMultiSelect(func, INCLUDES);
+ } else if (functionName.equalsIgnoreCase("excludes")) {
+ generateMultiSelect(func, EXCLUDES);
+ }
+ } catch (ConnectorException e) {
+ exceptions.add(e);
+ }
+ }
+
+ private void generateMultiSelect( Function func,
+ String funcName ) throws ConnectorException {
+ List<Expression> expressions = func.getParameters();
+ validateFunction(expressions);
+ Expression columnExpression = expressions.get(0);
+ Column column = ((ColumnReference)columnExpression).getMetadataObject();
+ StringBuffer criterion = new StringBuffer();
+ criterion.append(column.getNameInSource()).append(SPACE).append(funcName);
+ addFunctionParams((Literal)expressions.get(1), criterion);
+ criteriaList.add(criterion.toString());
+ }
+
+ private void appendMultiselectIn( Column column,
+ In criteria ) throws ConnectorException {
+ StringBuffer result = new StringBuffer();
+ result.append(column.getNameInSource()).append(SPACE);
+ if (criteria.isNegated()) {
+ result.append(EXCLUDES).append(SPACE);
+ } else {
+ result.append(INCLUDES).append(SPACE);
+ }
+ result.append('(');
+ List<Expression> rightExpressions = criteria.getRightExpressions();
+ Iterator<Expression> iter = rightExpressions.iterator();
+ boolean first = true;
+ while (iter.hasNext()) {
+ Expression rightExpression = iter.next();
+ if (first) {
+ result.append(rightExpression.toString());
+ first = false;
+ } else {
+ result.append(COMMA).append(rightExpression.toString());
+ }
+
+ }
+ result.append(')');
+ criteriaList.add(result.toString());
+ }
+
+ private void validateFunction( List<Expression> expressions ) throws ConnectorException {
+ if (expressions.size() != 2) {
+ throw new ConnectorException(Messages.getString("CriteriaVisitor.invalid.arg.count"));
+ }
+ if (!(expressions.get(0) instanceof ColumnReference)) {
+ throw new ConnectorException(Messages.getString("CriteriaVisitor.function.not.column.arg"));
+ }
+ if (!(expressions.get(1) instanceof Literal)) {
+ throw new ConnectorException(Messages.getString("CriteriaVisitor.function.not.literal.arg"));
+ }
+ }
+
+ private void addFunctionParams( Literal param,
+ StringBuffer criterion ) {
+ criterion.append(OPEN);
+ boolean first = true;
+ String fullParam = param.toString();
+ String[] params = fullParam.split(",");
+ for (int i = 0; i < params.length; i++) {
+ String token = params[i];
+ if (first) {
+ criterion.append(SPACE).append(Util.addSingleQuotes(token));
+ first = false;
+ } else {
+ criterion.append(COMMA).append(SPACE).append(Util.addSingleQuotes(token));
+ }
+ }
+ criterion.append(CLOSE);
+ }
+
+ protected void addCompareCriteria( List criteriaList,
+ Comparison compCriteria ) throws ConnectorException {
+ Expression lExpr = compCriteria.getLeftExpression();
+ if (lExpr instanceof Function) {
+ parseFunction((Function)lExpr);
+ } else {
+ ColumnReference left = (ColumnReference)lExpr;
+ Column column = left.getMetadataObject();
+ String columnName = column.getNameInSource();
+ StringBuffer queryString = new StringBuffer();
+ queryString.append(column.getParent().getNameInSource());
+ queryString.append('.');
+ queryString.append(columnName).append(SPACE);
+ queryString.append(comparisonOperators.get(compCriteria.getOperator()));
+ queryString.append(' ');
+ Expression rExp = compCriteria.getRightExpression();
+ if(rExp instanceof Literal) {
+ Literal literal = (Literal)rExp;
+ if (column.getJavaType().equals(Boolean.class)) {
+ queryString.append(((Boolean)literal.getValue()).toString());
+ } else if (column.getJavaType().equals(java.sql.Timestamp.class)) {
+ Timestamp datetime = (java.sql.Timestamp)literal.getValue();
+ String value = Util.getSalesforceDateTimeFormat().format(datetime);
+ String zoneValue = Util.getTimeZoneOffsetFormat().format(datetime);
+ queryString.append(value).append(zoneValue.subSequence(0, 3)).append(':').append(zoneValue.subSequence(3, 5));
+ } else if (column.getJavaType().equals(java.sql.Time.class)) {
+ String value = Util.getSalesforceDateTimeFormat().format((java.sql.Time)literal.getValue());
+ queryString.append(value);
+ } else if (column.getJavaType().equals(java.sql.Date.class)) {
+ String value = Util.getSalesforceDateFormat().format((java.sql.Date)literal.getValue());
+ queryString.append(value);
+ } else {
+ queryString.append(compCriteria.getRightExpression().toString());
+ }
+ } else if(rExp instanceof ColumnReference) {
+ ColumnReference right = (ColumnReference)lExpr;
+ column = left.getMetadataObject();
+ columnName = column.getNameInSource();
+ queryString.append(columnName);
+ }
+
+ criteriaList.add(queryString.toString());
+
+ if (columnName.equals("IsDeleted")) {
+ Literal isDeletedLiteral = (Literal)compCriteria.getRightExpression();
+ Boolean isDeleted = (Boolean)isDeletedLiteral.getValue();
+ if (isDeleted) {
+ this.queryAll = isDeleted;
+ }
+ }
+ }
+ }
+
+ private void appendCriteria( In criteria ) throws ConnectorException {
+ StringBuffer queryString = new StringBuffer();
+ Expression leftExp = criteria.getLeftExpression();
+ if(isIdColumn(leftExp)) {
+ idInCriteria = criteria;
+ }
+ queryString.append(getValue(leftExp));
+ queryString.append(' ');
+ if (criteria.isNegated()) {
+ queryString.append("NOT ");
+ }
+ queryString.append("IN");
+ queryString.append('(');
+ Column column = ((ColumnReference)criteria.getLeftExpression()).getMetadataObject();
+ boolean timeColumn = isTimeColumn(column);
+ boolean first = true;
+ Iterator iter = criteria.getRightExpressions().iterator();
+ while (iter.hasNext()) {
+ if (!first) queryString.append(',');
+ if (!timeColumn) queryString.append('\'');
+ queryString.append(getValue((Expression)iter.next()));
+ if (!timeColumn) queryString.append('\'');
+ first = false;
+ }
+ queryString.append(')');
+ criteriaList.add(queryString.toString());
+ }
+
+ private boolean isTimeColumn( Column column ) throws ConnectorException {
+ boolean result = false;
+ if (column.getJavaType().equals(java.sql.Timestamp.class) || column.getJavaType().equals(java.sql.Time.class)
+ || column.getJavaType().equals(java.sql.Date.class)) {
+ result = true;
+ }
+ return result;
+ }
+
+ protected String getValue( Expression expr ) throws ConnectorException {
+ String result;
+ if (expr instanceof ColumnReference) {
+ ColumnReference element = (ColumnReference)expr;
+ Column element2 = element.getMetadataObject();
+ result = element2.getNameInSource();
+ } else if (expr instanceof Literal) {
+ Literal literal = (Literal)expr;
+ result = literal.getValue().toString();
+ } else {
+ throw new RuntimeException("unknown type in SalesforceQueryExecution.getValue(): " + expr.toString());
+ }
+ return result;
+ }
+
+ protected void loadColumnMetadata( NamedTable group ) throws ConnectorException {
+ table = group.getMetadataObject();
+ String supportsQuery = table.getProperties().get("Supports Query");
+ if (!Boolean.valueOf(supportsQuery)) {
+ throw new ConnectorException(table.getNameInSource() + " "
+ + Messages.getString("CriteriaVisitor.query.not.supported"));
+ }
+ List<Column> columnIds = table.getColumns();
+ for (Column element : columnIds) {
+ String name = table.getName() + '.' + element.getNameInSource();
+ columnElementsByName.put(name, element);
+
+ // influences queryAll behavior
+ if (element.getNameInSource().equals("IsDeleted")) {
+ String isDeleted = element.getDefaultValue();
+ if (Boolean.parseBoolean(isDeleted)) {
+ this.queryAll = true;
+ }
+ }
+ }
+ }
+
+ protected boolean isIdColumn( Expression expression ) throws ConnectorException {
+ boolean result = false;
+ if (expression instanceof ColumnReference) {
+ Column element = ((ColumnReference)expression).getMetadataObject();
+ String nameInSource = element.getNameInSource();
+ if (nameInSource.equalsIgnoreCase("id")) {
+ result = true;
+ }
+ }
+ return result;
+ }
+
+ protected boolean isMultiSelectColumn( Expression expression ) throws ConnectorException {
+ boolean result = false;
+ if (expression instanceof ColumnReference) {
+ Column element = ((ColumnReference)expression).getMetadataObject();
+ String nativeType = element.getNativeType();
+ if (MULTIPICKLIST.equalsIgnoreCase(nativeType) || RESTRICTEDMULTISELECTPICKLIST.equalsIgnoreCase(nativeType)) {
+ result = true;
+ }
+ }
+ return result;
+ }
+
+ public boolean hasCriteria() {
+ return hasCriteria;
+ }
+
+ public void setHasCriteria( boolean hasCriteria,
+ boolean isIdCriteria ) {
+ if (isIdCriteria) {
+ if (hasCriteria()) {
+ this.onlyIDCriteria = false;
+ } else {
+ this.onlyIDCriteria = true;
+ }
+ } else if (this.onlyIDCriteria) {
+ this.onlyIDCriteria = false;
+ }
+ this.hasCriteria = hasCriteria;
+ }
+
+ public boolean hasOnlyIDCriteria() {
+ return this.onlyIDCriteria;
+ }
+
+ public String getTableName() throws ConnectorException {
+ return table.getNameInSource();
+ }
+
+ protected void addCriteriaString(StringBuffer result) {
+ if(hasCriteria()) {
+ result.append(WHERE).append(SPACE);
+ for (String string : criteriaList) {
+ result.append(string);
+ }
+ result.append(SPACE);
+ }
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/DeleteVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/DeleteVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/DeleteVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import java.util.Iterator;
+
+import org.teiid.connector.language.Delete;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+
+
+public class DeleteVisitor extends CriteriaVisitor implements IQueryProvidingVisitor {
+
+ public DeleteVisitor(RuntimeMetadata metadata) {
+ super(metadata);
+ }
+
+ @Override
+ public void visit(Delete delete) {
+ super.visit(delete);
+ try {
+ loadColumnMetadata(delete.getTable());
+ } catch (ConnectorException ce) {
+ exceptions.add(ce);
+ }
+ }
+
+ /*
+ * The SOQL SELECT command uses the following syntax: SELECT fieldList FROM
+ * objectType [WHERE The Condition Expression (WHERE Clause)] [ORDER BY]
+ * LIMIT ?
+ */
+
+ public String getQuery() throws ConnectorException {
+ if (!exceptions.isEmpty()) {
+ throw exceptions.get(0);
+ }
+ StringBuffer result = new StringBuffer();
+ result.append(SELECT).append(SPACE);
+ result.append("Id").append(SPACE);
+ result.append(FROM).append(SPACE);
+ result.append(table.getNameInSource()).append(SPACE);
+ addCriteriaString(result);
+ return result.toString();
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/ICriteriaVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/ICriteriaVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/ICriteriaVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,36 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import org.teiid.resource.ConnectorException;
+
+public interface ICriteriaVisitor {
+
+ public boolean hasCriteria();
+
+ public void setHasCriteria(boolean hasCriteria, boolean isIdCriteria);
+
+ public boolean hasOnlyIDCriteria();
+
+ public String getTableName() throws ConnectorException;
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/IQueryProvidingVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/IQueryProvidingVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/IQueryProvidingVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,30 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import org.teiid.resource.ConnectorException;
+
+public interface IQueryProvidingVisitor extends ICriteriaVisitor {
+
+ public String getQuery() throws ConnectorException;
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/InsertVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/InsertVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/InsertVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,101 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.JAXBElement;
+import javax.xml.namespace.QName;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Insert;
+import org.teiid.connector.language.ExpressionValueSource;
+import org.teiid.connector.language.Literal;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+
+
+public class InsertVisitor extends CriteriaVisitor {
+
+ @SuppressWarnings("unchecked")
+ List<JAXBElement> elements = new ArrayList<JAXBElement>();
+
+ private static Class<?> stringClazz = new String().getClass();
+
+ public InsertVisitor(RuntimeMetadata metadata) {
+ super(metadata);
+ }
+
+ @Override
+ public void visit(Insert insert) {
+ super.visit(insert);
+ try {
+ loadColumnMetadata(insert.getTable());
+
+ List<ColumnReference> columns = insert.getColumns();
+ List<Expression> values = ((ExpressionValueSource)insert.getValueSource()).getValues();
+ if(columns.size() != values.size()) {
+ throw new ConnectorException("Error: columns.size and values.size are not the same.");
+ }
+
+ for(int i = 0; i < columns.size(); i++) {
+ ColumnReference element = columns.get(i);
+ Column column = element.getMetadataObject();
+ Object value = values.get(i);
+ String val;
+ if(value instanceof Literal) {
+ Literal literalValue = (Literal)value;
+ val = literalValue.getValue().toString();
+ if(null != val && !val.isEmpty()) {
+ val = this.stripQutes(val);
+ }
+ } else {
+ val = value.toString();
+ }
+ QName qname = new QName(column.getNameInSource());
+ @SuppressWarnings( "unchecked" )
+ JAXBElement jbe = new JAXBElement( qname, stringClazz, val );
+ elements.add(jbe);
+ }
+
+ } catch (ConnectorException ce) {
+ exceptions.add(ce);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<JAXBElement> getMessageElements() {
+ return elements;
+ }
+
+ private String stripQutes(String id) {
+ if((id.startsWith("'") && id.endsWith("'"))) {
+ id = id.substring(1,id.length()-1);
+ } else if ((id.startsWith("\"") && id.endsWith("\""))) {
+ id = id.substring(1,id.length()-1);
+ }
+ return id;
+ }
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/JoinQueryVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/JoinQueryVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/JoinQueryVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,165 @@
+package org.teiid.resource.adapter.salesforce.execution.visitors;
+
+import org.teiid.connector.language.AggregateFunction;
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Comparison;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Join;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.TableReference;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.Util;
+
+
+/**
+ * Salesforce supports joins only on primary key/foreign key relationships. The connector
+ * is supporting these joins through the OUTER JOIN syntax. All RIGHT OUTER JOINS are
+ * rewritten by the query processor as LEFT OUTER JOINS, so that is all this visitor has
+ * to expect.
+ *
+ * Salesforce also requires a different syntax depending upon if you are joining from parent
+ * to child, or from child to parent.
+ * http://www.salesforce.com/us/developer/docs/api/index_Left.htm#StartTopic...
+ *
+ */
+
+public class JoinQueryVisitor extends SelectVisitor {
+
+ private Table leftTableInJoin;
+ private Table rightTableInJoin;
+ private Table childTable;
+
+ public JoinQueryVisitor(RuntimeMetadata metadata) {
+ super(metadata);
+ }
+
+ // Has to be a left outer join
+ @Override
+ public void visit(Join join) {
+ try {
+ TableReference left = join.getLeftItem();
+ if (left instanceof NamedTable) {
+ NamedTable leftGroup = (NamedTable) left;
+ leftTableInJoin = leftGroup.getMetadataObject();
+ loadColumnMetadata(leftGroup);
+ }
+
+ TableReference right = join.getRightItem();
+ if (right instanceof NamedTable) {
+ NamedTable rightGroup = (NamedTable) right;
+ rightTableInJoin = rightGroup.getMetadataObject();
+ loadColumnMetadata((NamedTable) right);
+ }
+ super.visit(join);
+ } catch (ConnectorException ce) {
+ exceptions.add(ce);
+ }
+
+ }
+
+ @Override
+ public void visit(Comparison criteria) {
+
+ // Find the criteria that joins the two tables
+ try {
+ Expression rExp = criteria.getRightExpression();
+ if (rExp instanceof ColumnReference) {
+ Expression lExp = criteria.getLeftExpression();
+ if (isIdColumn(rExp) || isIdColumn(lExp)) {
+
+ Column rColumn = ((ColumnReference) rExp).getMetadataObject();
+ String rTableName = rColumn.getParent().getNameInSource();
+
+ Column lColumn = ((ColumnReference) lExp).getMetadataObject();
+ String lTableName = lColumn.getParent().getNameInSource();
+
+ if (leftTableInJoin.getNameInSource().equals(rTableName)
+ || leftTableInJoin.getNameInSource().equals(lTableName)
+ && rightTableInJoin.getNameInSource().equals(rTableName)
+ || rightTableInJoin.getNameInSource().equals(lTableName)
+ && !rTableName.equals(lTableName)) {
+ // This is the join criteria, the one that is the ID is the parent.
+ Expression fKey = !isIdColumn(lExp) ? lExp : rExp;
+ table = childTable = (Table)((ColumnReference) fKey).getMetadataObject().getParent();
+ } else {
+ // Only add the criteria to the query if it is not the join criteria.
+ // The join criteria is implicit in the salesforce syntax.
+ super.visit(criteria);
+ }
+ }
+ } else {
+ super.visit(criteria);
+ }
+ } catch (ConnectorException e) {
+ exceptions.add(e);
+ }
+ }
+
+ @Override
+ public String getQuery() throws ConnectorException {
+
+ if (isParentToChildJoin()) {
+ return super.getQuery();
+ }
+ if (!exceptions.isEmpty()) {
+ throw exceptions.get(0);
+ }
+ StringBuffer select = new StringBuffer();
+ select.append(SELECT).append(SPACE);
+ addSelectSymbols(leftTableInJoin.getNameInSource(), select);
+ select.append(COMMA).append(SPACE).append(OPEN);
+
+ StringBuffer subselect = new StringBuffer();
+ subselect.append(SELECT).append(SPACE);
+ addSelectSymbols(rightTableInJoin.getNameInSource(), subselect);
+ subselect.append(SPACE);
+ subselect.append(FROM).append(SPACE);
+ subselect.append(rightTableInJoin.getNameInSource()).append('s');
+ subselect.append(CLOSE).append(SPACE);
+ select.append(subselect);
+ select.append(FROM).append(SPACE);
+ select.append(leftTableInJoin.getNameInSource()).append(SPACE);
+ addCriteriaString(select);
+ select.append(limitClause);
+ Util.validateQueryLength(select);
+ return select.toString();
+ }
+
+ public boolean isParentToChildJoin() {
+ return childTable.equals(leftTableInJoin);
+ }
+
+ protected void addSelectSymbols(String tableNameInSource, StringBuffer result) throws ConnectorException {
+ boolean firstTime = true;
+ for (DerivedColumn symbol : selectSymbols) {
+ Expression expression = symbol.getExpression();
+ if (expression instanceof ColumnReference) {
+ Column element = ((ColumnReference) expression).getMetadataObject();
+ String tableName = element.getParent().getNameInSource();
+ if(!isParentToChildJoin() && tableNameInSource.equals(tableName) ||
+ isParentToChildJoin()) {
+ if (!firstTime) {
+ result.append(", ");
+ } else {
+ firstTime = false;
+ }
+ result.append(tableName);
+ result.append('.');
+ result.append(element.getNameInSource());
+ }
+ } else if (expression instanceof AggregateFunction) {
+ if (!firstTime) {
+ result.append(", ");
+ } else {
+ firstTime = false;
+ }
+ result.append("count()"); //$NON-NLS-1$
+ }
+ }
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/SelectVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/SelectVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/SelectVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,235 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.connector.language.AggregateFunction;
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.Expression;
+import org.teiid.connector.language.Limit;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.salesforce.Constants;
+import org.teiid.resource.adapter.salesforce.Messages;
+import org.teiid.resource.adapter.salesforce.Util;
+
+
+public class SelectVisitor extends CriteriaVisitor implements IQueryProvidingVisitor {
+
+ private Map<Integer, Column> selectSymbolIndexToElement = new HashMap<Integer, Column>();
+ private Map<String, Integer> selectSymbolNameToIndex = new HashMap<String, Integer>();
+ private int selectSymbolCount;
+ private int idIndex = -1; // index of the ID select symbol.
+ protected List<DerivedColumn> selectSymbols;
+ protected StringBuffer limitClause = new StringBuffer();
+ private Boolean objectSupportsRetrieve;
+
+ public SelectVisitor(RuntimeMetadata metadata) {
+ super(metadata);
+ }
+
+ public void visit(Select query) {
+ super.visit(query);
+ if (query.isDistinct()) {
+ exceptions.add(new ConnectorException(
+ Messages.getString("SelectVisitor.distinct.not.supported")));
+ }
+ selectSymbols = query.getDerivedColumns();
+ selectSymbolCount = selectSymbols.size();
+ Iterator<DerivedColumn> symbolIter = selectSymbols.iterator();
+ int index = 0;
+ while (symbolIter.hasNext()) {
+ DerivedColumn symbol = symbolIter.next();
+ // get the name in source
+ Expression expression = symbol.getExpression();
+ if (expression instanceof ColumnReference) {
+ Column element = ((ColumnReference) expression).getMetadataObject();
+ selectSymbolIndexToElement.put(index, element);
+ selectSymbolNameToIndex .put(element.getNameInSource(), index);
+ String nameInSource = element.getNameInSource();
+ if (null == nameInSource || nameInSource.length() == 0) {
+ exceptions.add(new ConnectorException(
+ "name in source is null or empty for column "
+ + symbol.toString()));
+ continue;
+ }
+ if (nameInSource.equalsIgnoreCase("id")) {
+ idIndex = index;
+ }
+ }
+ ++index;
+ }
+ }
+
+ @Override
+ public void visit(NamedTable obj) {
+ try {
+ table = obj.getMetadataObject();
+ String supportsQuery = table.getProperties().get(Constants.SUPPORTS_QUERY);
+ objectSupportsRetrieve = Boolean.valueOf(table.getProperties().get(Constants.SUPPORTS_RETRIEVE));
+ if (!Boolean.valueOf(supportsQuery)) {
+ throw new ConnectorException(table.getNameInSource() + " "
+ + Messages.getString("CriteriaVisitor.query.not.supported"));
+ }
+ loadColumnMetadata(obj);
+ } catch (ConnectorException ce) {
+ exceptions.add(ce);
+ }
+ }
+
+ @Override
+ public void visit(Limit obj) {
+ super.visit(obj);
+ limitClause.append(LIMIT).append(SPACE).append(obj.getRowLimit());
+ }
+
+ /*
+ * The SOQL SELECT command uses the following syntax: SELECT fieldList FROM
+ * objectType [WHERE The Condition Expression (WHERE Clause)] [ORDER BY]
+ * LIMIT ?
+ */
+
+ public String getQuery() throws ConnectorException {
+ if (!exceptions.isEmpty()) {
+ throw ((ConnectorException) exceptions.get(0));
+ }
+ StringBuffer result = new StringBuffer();
+ result.append(SELECT).append(SPACE);
+ addSelectSymbols(table.getNameInSource(), result);
+ result.append(SPACE);
+ result.append(FROM).append(SPACE);
+ result.append(table.getNameInSource()).append(SPACE);
+ addCriteriaString(result);
+ //result.append(orderByClause).append(SPACE);
+ result.append(limitClause);
+ Util.validateQueryLength(result);
+ return result.toString();
+ }
+
+ protected void addSelectSymbols(String tableNameInSource, StringBuffer result) throws ConnectorException {
+ boolean firstTime = true;
+ for (DerivedColumn symbol : selectSymbols) {
+ if (!firstTime) {
+ result.append(", ");
+ } else {
+ firstTime = false;
+ }
+ Expression expression = symbol.getExpression();
+ if (expression instanceof ColumnReference) {
+ Column element = ((ColumnReference) expression).getMetadataObject();
+ AbstractMetadataRecord parent = element.getParent();
+ Table table;
+ if(parent instanceof Table) {
+ table = (Table)parent;
+ } else {
+ parent = parent.getParent();
+ if(parent instanceof Table) {
+ table = (Table)parent;
+ } else {
+ throw new ConnectorException("Could not resolve Table for column " + element.getName());
+ }
+ }
+ result.append(table.getNameInSource());
+ result.append('.');
+ result.append(element.getNameInSource());
+ } else if (expression instanceof AggregateFunction) {
+ result.append("count()"); //$NON-NLS-1$
+ }
+ }
+ }
+
+
+ public int getSelectSymbolCount() {
+ return selectSymbolCount;
+ }
+
+ public Column getSelectSymbolMetadata(int index) {
+ return selectSymbolIndexToElement.get(index);
+ }
+
+ public Column getSelectSymbolMetadata(String name) {
+ Column result = null;
+ Integer index = selectSymbolNameToIndex.get(name);
+ if(null != index) {
+ result = selectSymbolIndexToElement.get(index);
+ }
+ return result;
+ }
+
+ /**
+ * Returns the index of the ID column.
+ * @return the index of the ID column, -1 if there is no ID column.
+ */
+ public int getIdIndex() {
+ return idIndex;
+ }
+
+
+ public Boolean getQueryAll() {
+ return queryAll;
+ }
+
+
+ public String getRetrieveFieldList() throws ConnectorException {
+ assertRetrieveValidated();
+ StringBuffer result = new StringBuffer();
+ addSelectSymbols(table.getNameInSource(), result);
+ return result.toString();
+ }
+
+
+ public List<String> getIdInCriteria() throws ConnectorException {
+ assertRetrieveValidated();
+ List<Expression> expressions = this.idInCriteria.getRightExpressions();
+ List<String> result = new ArrayList<String>(expressions.size());
+ for(int i = 0; i < expressions.size(); i++) {
+ result.add(getValue(expressions.get(i)));
+ }
+ return result;
+ }
+
+ private void assertRetrieveValidated() throws AssertionError {
+ if(!hasOnlyIDCriteria()) {
+ throw new AssertionError("Must call hasOnlyIdInCriteria() before this method");
+ }
+ }
+
+ public boolean hasOnlyIdInCriteria() {
+ return hasOnlyIDCriteria() && idInCriteria != null;
+ }
+
+ public boolean canRetrieve() {
+ return objectSupportsRetrieve && hasOnlyIDCriteria();
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/UpdateVisitor.java
===================================================================
--- trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/UpdateVisitor.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/java/org/teiid/resource/adapter/salesforce/execution/visitors/UpdateVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,66 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import org.teiid.connector.language.Update;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+
+
+public class UpdateVisitor extends CriteriaVisitor implements IQueryProvidingVisitor {
+
+ public UpdateVisitor(RuntimeMetadata metadata) {
+ super(metadata);
+ }
+
+ @Override
+ public void visit(Update update) {
+ // don't visit the changes or they will be in the query.
+ visitNode(update.getTable());
+ visitNode(update.getWhere());
+ try {
+ loadColumnMetadata(update.getTable());
+ } catch (ConnectorException ce) {
+ exceptions.add(ce);
+ }
+ }
+
+ /*
+ * The SOQL SELECT command uses the following syntax: SELECT fieldList FROM
+ * objectType [WHERE The Condition Expression (WHERE Clause)] [ORDER BY]
+ * LIMIT ?
+ */
+
+ public String getQuery() throws ConnectorException {
+ if (!exceptions.isEmpty()) {
+ throw ((ConnectorException) exceptions.get(0));
+ }
+ StringBuffer result = new StringBuffer();
+ result.append(SELECT).append(SPACE);
+ result.append("Id").append(SPACE);
+ result.append(FROM).append(SPACE);
+ result.append(table.getNameInSource()).append(SPACE);
+ addCriteriaString(result);
+ return result.toString();
+ }
+
+}
Added: trunk/connectors/translator-salesforce/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-salesforce/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.salesforce.SalesForceExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/translator-salesforce/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/salesforce/i18n.properties
===================================================================
--- trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/salesforce/i18n.properties (rev 0)
+++ trunk/connectors/translator-salesforce/src/main/resources/org/teiid/resource/adapter/salesforce/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.
+#
+SalesforceConnection.update.not.supported=Update Execution is not supported.
+SalesforceConnection.procedures.not.supported=Procedure Execution is not supported.
+SalesforceConnection.invalid.execution.mode=Execution mode not supported.
+SalesforceConnection.bad.IN.value=Exception parsing the IN Criteria Limit value.
+SalesforceConnection.bad.ping.value=Exception parsing the Data Source Test Connect Interval value.
+
+SalesforceSourceConnectionFactory.Invalid.username.password.pair=Invalid credential configuration. The Username and Password binding properties must both be empty or both have values.
+
+SalesforceQueryExecutionImpl.cancel=SynchQueryExecution.cancel() called
+SalesforceQueryExecutionImpl.close=SynchQueryExecution.close() called
+SalesforceQueryExecutionImpl.missing.field=No field in result for SelectSymbol
+SalesforceQueryExecutionImpl.column.mismatch1=Error: Column mismatch, expected
+SalesforceQueryExecutionImpl.column.mismatch2= received
+SalesforceQueryExecutionImpl.datatime.parse=Error parsing date_time: Value =
+SalesforceQueryExecutionImpl.reduced.batch.size=Reduced batch size to 2000
+
+SelectVisitor.distinct.not.supported=Distinct is not supported by the connector.
+
+CriteriaVisitor.query.not.supported= does not support the query statement.
+CriteriaVisitor.invalid.arg.count=The includes and excludes functions require two parameters.
+CriteriaVisitor.function.not.column.arg=The first parameter of the includes and excludes functions must be a column name.
+CriteriaVisitor.function.not.literal.arg=The second parameter of the includes and excludes functions must be a literal value.
+CriteriaVisitor.IN.not.supported.on.col=The IN criteria is not supported on multi-select columns:
+CriteriaVisitor.LIKE.not.supported.on.Id=LIKE criteria are not allowed on columns of native type Id
+CriteriaVisitor.LIKE.not.supported.on.multiselect=LIKE criteria are not allowed on columns of native type Multi-Select Picklist
+
+Util.query.exceeds.max.length=Queries cannot exceed 10,000 characters
\ No newline at end of file
Added: trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/visitors/TestVisitors.java
===================================================================
--- trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/visitors/TestVisitors.java (rev 0)
+++ trunk/connectors/translator-salesforce/src/test/java/org/teiid/resource/adapter/salesforce/execution/visitors/TestVisitors.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,166 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.execution.visitors;
+
+import static org.junit.Assert.*;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.MetadataStore;
+import org.teiid.connector.metadata.runtime.Schema;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.connector.metadata.runtime.Column.SearchType;
+import org.teiid.metadata.CompositeMetadataStore;
+import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.adapter.salesforce.execution.visitors.JoinQueryVisitor;
+import org.teiid.resource.adapter.salesforce.execution.visitors.SelectVisitor;
+
+import com.metamatrix.cdk.api.TranslationUtility;
+import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.query.metadata.QueryMetadataInterface;
+import com.metamatrix.query.unittest.RealMetadataFactory;
+
+public class TestVisitors {
+
+ public static QueryMetadataInterface exampleSalesforce() {
+ MetadataStore store = new MetadataStore();
+ // Create models
+ Schema salesforceModel = RealMetadataFactory.createPhysicalModel("SalesforceModel", store); //$NON-NLS-1$
+
+ // Create Account group
+ Table accounTable = RealMetadataFactory.createPhysicalGroup("Account", salesforceModel); //$NON-NLS-1$
+ accounTable.setNameInSource("Account"); //$NON-NLS-1$
+ accounTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+ // Create Account Columns
+ String[] acctNames = new String[] {
+ "ID", "Name", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+ String[] acctTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+ };
+
+ List<Column> acctCols = RealMetadataFactory.createElements(accounTable, acctNames, acctTypes);
+ acctCols.get(2).setNativeType("multipicklist"); //$NON-NLS-1$
+ acctCols.get(2).setSearchType(SearchType.Like_Only);
+ // Set name in source on each column
+ String[] accountNameInSource = new String[] {
+ "id", "AccountName", "Stuff", "Industry" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = acctCols.get(i);
+ obj.setNameInSource(accountNameInSource[i]);
+ }
+
+ // Create Contact group
+ Table contactTable = RealMetadataFactory.createPhysicalGroup("Contact", salesforceModel); //$NON-NLS-1$
+ contactTable.setNameInSource("Contact"); //$NON-NLS-1$
+ contactTable.setProperty("Supports Query", Boolean.TRUE.toString()); //$NON-NLS-1$
+ // Create Contact Columns
+ String[] elemNames = new String[] {
+ "ContactID", "Name", "AccountId" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ String[] elemTypes = new String[] {
+ DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING
+ };
+
+ List<Column> contactCols = RealMetadataFactory.createElements(contactTable, elemNames, elemTypes);
+ // Set name in source on each column
+ String[] contactNameInSource = new String[] {
+ "id", "ContactName", "accountid" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ };
+ for(int i=0; i<2; i++) {
+ Column obj = contactCols.get(i);
+ obj.setNameInSource(contactNameInSource[i]);
+ }
+ return new TransformationMetadata(null, new CompositeMetadataStore(store), null, null);
+ }
+
+ private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());
+
+ @Test public void testOr() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Name = 'foo' or Stuff = 'bar'"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName = 'foo') OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testNot() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where not (Name = 'foo' and Stuff = 'bar')"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (Account.AccountName != 'foo') OR (Account.Stuff != 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testCountStart() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select count(*) from Account"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT count() FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testNotLike() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Name not like '%foo' or Stuff = 'bar'"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE (NOT (Account.AccountName LIKE '%foo')) OR (Account.Stuff = 'bar')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+
+ @Test public void testIN() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("select * from Account where Industry IN (1,2,3)"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertFalse(visitor.hasOnlyIDCriteria());
+ assertEquals("SELECT Account.id, Account.AccountName, Account.Stuff, Account.Industry FROM Account WHERE Industry IN('1','2','3')", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+
+ }
+
+ @Test public void testOnlyIDsIN() throws Exception {
+ // this can resolve to a better performing retrieve call
+ Select command = (Select)translationUtility.parseCommand("select * from Account where ID IN (1,2,3)"); //$NON-NLS-1$
+ SelectVisitor visitor = new SelectVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertTrue(visitor.hasOnlyIdInCriteria());
+ assertEquals("Account", visitor.getTableName());
+ assertEquals("Account.id, Account.AccountName, Account.Stuff, Account.Industry", visitor.getRetrieveFieldList());
+ assertEquals(Arrays.asList(new String[]{"1", "2", "3"}), visitor.getIdInCriteria());
+ }
+
+ @Test public void testJoin() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contact.Name FROM Contact LEFT OUTER JOIN Account ON Account.Id = Contact.AccountId"); //$NON-NLS-1$
+ SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.AccountName, Contact.ContactName FROM Contact", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+ @Test public void testJoin2() throws Exception {
+ Select command = (Select)translationUtility.parseCommand("SELECT Account.Name, Contact.Name FROM Account LEFT OUTER JOIN Contact ON Account.Id = Contact.AccountId"); //$NON-NLS-1$
+ SelectVisitor visitor = new JoinQueryVisitor(translationUtility.createRuntimeMetadata());
+ visitor.visit(command);
+ assertEquals("SELECT Account.AccountName, (SELECT Contact.ContactName FROM Contacts) FROM Account", visitor.getQuery().toString().trim()); //$NON-NLS-1$
+ }
+
+}
Property changes on: trunk/connectors/translator-text
___________________________________________________________________
Name: svn:ignore
+ target
.project
.settings
.classpath
Added: trunk/connectors/translator-text/pom.xml
===================================================================
--- trunk/connectors/translator-text/pom.xml (rev 0)
+++ trunk/connectors/translator-text/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-text</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Text Translator</name>
+ <description>This translator converts the text file data into relational tables</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-connector-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>
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/StringToDateTranslator.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/StringToDateTranslator.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/StringToDateTranslator.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,231 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
+
+/**
+ * <p>This is a helper class for TextTranslators that can be used to translate
+ * any String that is a representation of a date to a java.util.Date object.
+ * This class is created by passing it a properties object that contains at least
+ * one property. The value of this property is a String that can be a delimited list of
+ * date format Strings. Date format Strings can be any format String that a
+ * java.text.SimpleDateFormat can be created with. There is also an optional
+ * property that defines the delimiter for the list of Date format Strings.
+ * If this property is not specified then the entire String value of the DateFormatStrings
+ * property will be used as the only format that this class can translate.</p>
+ *
+ * <p>After this class is created it can the be used to translate Strings into
+ * java.util.Date object using the translateStringToDate(String) method.</p>
+ */
+public class StringToDateTranslator {
+
+ TextExecutionFactory config;
+
+ /**
+ * The SimpleDateFormat objects that are used to translate dates for this
+ * connector.
+ */
+ private List simpleDateFormats;
+
+ /**
+ * The List of date format Strings that define the patterns of the Strings
+ * that this translator can translate.
+ */
+ private List dateFormatStrings;
+
+ /**
+ * This boolean determines whether this instance has any DateFormatters
+ * to translate Strings with. It is cached for performance reasons.
+ */
+ private boolean hasFormatters=false;
+
+ /**
+ * <p>This class is created by passing it a properties object that contains at least
+ * one property. The value of this property is a String that can be a delimited list of
+ * date format Strings. Date format Strings can be any format String that a
+ * java.text.SimpleDateFormat can be created with. There is also an optional
+ * property that defines the delimiter for the list of Date format Strings.
+ * If this property is not specified then the entire String value of the DateFormatStrings
+ * property will be used as the only format that this class can translate.</p>
+ *
+ * <p>Note that the order of the list of date format strings is important
+ * because the translator attempts to translate the String passed to it in the
+ * order of the date format Strings in the delimited property value.</p>
+ *
+ * <p>After this class is created it can the be used to translate Strings into
+ * java.util.Date object using the translateStringToDate(String) method.</p>
+ *
+ * <pre>
+ * The properties that are required in construction of this class are as
+ * follows:
+ *
+ * PropertyName: TextPropertyNames.DATE_RESULT_FORMATS
+ * PropertyValue: Delimited list of date format Strings: ie MM/dd/yy' 'hh:mm:ss
+ *
+ * PropertyName: TextPropertyNames.DATE_RESULT_FORMATS_DELIMITER
+ * PropertyValue: Delimiter for value of TextPropertyNames.DATE_RESULT_FORMATS
+ * </pre>
+ */
+ public StringToDateTranslator(TextExecutionFactory config) {
+ this.config = config;
+
+ String dateFormats = config.getDateResultFormats();
+ String dateFormatsDelimiter = config.getDateResultFormatsDelimiter();
+
+ if (!(dateFormatsDelimiter == null || dateFormatsDelimiter.trim().length() == 0)) {
+ if (!(dateFormats == null || dateFormats.trim().length() == 0)) {
+ createSimpleDateFormats(dateFormats, dateFormatsDelimiter);
+ }
+ } else if (!(dateFormats == null || dateFormats.trim().length() == 0)) {
+ createSimpleDateFormat(dateFormats);
+ }
+
+ if (simpleDateFormats != null && simpleDateFormats.size() > 0) {
+ hasFormatters = true;
+ }
+ }
+
+ /**
+ * This method is used to translate String representations of dates into
+ * java.util.Date objects using a set of formats passed into this class at
+ * creation time. Has formatters should always be called on this class
+ * prior to the use of this method to determine whether or not there are any
+ * formatters this class can use to translate the String value passed in.
+ * If there are no formatters and this method is called, it will throw
+ * a parse Exception.
+ *
+ * @param string the String to be parsed into a java.util.Date
+ * @return the java.util.Date representation of the passed in String
+ * @throws ParseException if the String passed in could not be parsed
+ */
+ public java.util.Date translateStringToDate(String string) throws ParseException{
+ List parseExceptionList = new ArrayList();
+ Iterator iterator = simpleDateFormats.iterator();
+
+ while (iterator.hasNext()) {
+ SimpleDateFormat formatter = (SimpleDateFormat)iterator.next();
+ try {
+ java.util.Date date = formatter.parse(string);
+ return date;
+ }catch(ParseException e) {
+ parseExceptionList.add(e);
+ // Do nothing here will try again with the next formatter
+ }
+ }
+
+ // if we have reached this point without returning a Date, we
+ // have been unsuccessful in parsing: throw an exception
+
+ // This should always be the case, but just for safety:
+ if (dateFormatStrings.size() == parseExceptionList.size()) {
+ StringBuffer message = new StringBuffer();
+ int counter = 0;
+ Object[] params = new Object[] { string };
+ message.append(TextPlugin.Util.getString("StringToDateTranslator.Attempts_to_parse_String__{0}_to_a_java.util.Date_failed_for_the_following_reasons___1", params)); //$NON-NLS-1$
+
+ if (!hasFormatters()) {
+ message.append(TextPlugin.Util.getString("StringToDateTranslator.There_is_no_format_Strings_found_in_this_formatter_object._n_2", params)); //$NON-NLS-1$
+ }
+
+ Iterator exceptionsIterator = parseExceptionList.iterator();
+ Iterator formatStringsIterator = dateFormatStrings.iterator();
+ while (exceptionsIterator.hasNext()) {
+ String format = (String)formatStringsIterator.next();
+ String exceptionMessage = ((ParseException)exceptionsIterator.next()).getMessage();
+ Object[] params2 = new Object[] { ""+counter, format, exceptionMessage }; //$NON-NLS-1$
+ message.append(TextPlugin.Util.getString("StringToDateTranslator.Parse_Attempt__{0}_using_format__{1}_failed_for_the_following_reason__{2}_4", params2)); //$NON-NLS-1$
+ counter++;
+ }
+
+ throw new ParseException(message.toString(),0);
+ }
+ Object params3 = new Object[] { string, dateFormatStrings };
+ throw new ParseException(TextPlugin.Util.getString("StringToDateTranslator.Failed_to_convert_String__{0}_to_a_Date_using_one_of_the_following_format_Strings_that_are_specified_in_the_properties_for_this_Connector__{1}_1", params3), 0); //$NON-NLS-1$
+ }
+
+ /**
+ * This method is used to check the status of this translator object.
+ * It will return true if this translator has any 'formatters' to do parsing
+ * of Strings in the translateStringToDate() method. This method should
+ * always be called prior to using the translateStringToDate() method.
+ * If there are no formatters for the instance of this class, all calls to
+ * the translateStringToDate() method will throw a ParseException.
+ *
+ * @return true if this class has formatters to parse Strings to Dates
+ */
+ public boolean hasFormatters() {
+ return hasFormatters;
+ }
+
+ /**
+ * This method is a helper method that will instantiate the formatters that
+ * this object uses to translate Strings into Dates.
+ *
+ * @param dateFormats the delimited String of date format templates to
+ * be used to create the date formatters for this object.
+ * @param dateFormatsDelimiter the delimiter used to delimit the dateFormats
+ * String that is also passed into this method.
+ */
+ private void createSimpleDateFormats(String dateFormats, String dateFormatsDelimiter) {
+ simpleDateFormats = new ArrayList();
+ dateFormatStrings = new ArrayList();
+ StringTokenizer tokenizer = new StringTokenizer(dateFormats, dateFormatsDelimiter);
+
+ while (tokenizer.hasMoreTokens()) {
+ String token = tokenizer.nextToken();
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Creating simple Date format for formatting String: " +token); //$NON-NLS-1$
+
+ dateFormatStrings.add(token);
+ SimpleDateFormat formatter = new SimpleDateFormat(token.trim());
+ simpleDateFormats.add(formatter);
+ }
+ }
+
+ /**
+ * This method is as helper method that will create a single date formatter
+ * from the date format template String that is passed into it.
+ *
+ * @param dateFormats the String that is the template for translating
+ * Strings into java.util.Date objects
+ */
+ private void createSimpleDateFormat(String dateFormats) {
+ simpleDateFormats = new ArrayList();
+ dateFormatStrings = new ArrayList();
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Creating simple Date format for formatting String: " +dateFormats); //$NON-NLS-1$
+
+ SimpleDateFormat formatter = new SimpleDateFormat(dateFormats);
+ dateFormatStrings.add(dateFormats);
+ simpleDateFormats.add(formatter);
+ }
+
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextCapabilities.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextCapabilities.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,31 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+
+public class TextCapabilities extends BasicConnectorCapabilities {
+
+ static TextCapabilities INSTANCE = new TextCapabilities();
+
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextConnection.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextConnection.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextConnection.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,35 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import java.util.Map;
+import java.util.Properties;
+
+import javax.resource.cci.Connection;
+
+import org.teiid.resource.ConnectorException;
+
+public interface TextConnection extends Connection {
+ Map<String, Properties> getMetadataProperties();
+ String getNextLine(String tableName)throws ConnectorException;
+ String getHeaderLine(String tableName)throws ConnectorException;
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextDescriptorPropertyNames.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextDescriptorPropertyNames.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextDescriptorPropertyNames.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,44 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+/**
+ * Property names used in the text descriptor file.
+ */
+public class TextDescriptorPropertyNames {
+ public static final String LOCATION = "LOCATION"; //$NON-NLS-1$
+ public static final String FILE_LOCATION = "FILE"; //$NON-NLS-1$
+ public static final String URL_LOCATION = "URL"; //$NON-NLS-1$
+ public static final String DELIMITER = "DELIMITER"; //$NON-NLS-1$
+ public static final String QUALIFIER = "QUALIFIER"; //$NON-NLS-1$
+ public static final String HEADER_LINES = "SKIPHEADERLINES"; //$NON-NLS-1$
+ public static final String COLUMNS = "COLUMNS"; //$NON-NLS-1$
+ public static final String TYPES = "TYPES"; //$NON-NLS-1$
+
+ /**
+ * If HEADER_LINES is non-zero this property defines which row of HEADER_LINES
+ * can be used as the header row. The value is 1-based and must be < HEADER_LINES.
+ * @since 5.0.3
+ */
+ public static final String HEADER_ROW = "HEADERLINE"; //$NON-NLS-1$
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextExecutionFactory.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextExecutionFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.resource.adapter.text;
+
+import java.util.Map;
+import java.util.Properties;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.ConnectionFactory;
+
+import org.teiid.connector.language.QueryExpression;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.MetadataFactory;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.MetadataProvider;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TranslatorProperty;
+import org.teiid.resource.cci.TypeFacility;
+
+
+/**
+ * Implementation of text connector.
+ */
+public class TextExecutionFactory extends BasicExecutionFactory implements MetadataProvider{
+
+ private boolean enforceColumnCount = false;
+ private String dateResultFormatsDelimiter;
+ private String dateResultFormats;
+
+ @Override
+ public void start() throws ConnectorException {
+ super.start();
+ }
+
+ @TranslatorProperty(name="EnforceColumnCount", display="Enforce Column Count",description="This forces the number of columns in text file to match what was modeled", defaultValue="false")
+ public boolean isEnforceColumnCount() {
+ return enforceColumnCount;
+ }
+
+ public void setEnforceColumnCount(Boolean enforceColumnCount) {
+ this.enforceColumnCount = enforceColumnCount.booleanValue();
+ }
+
+ @TranslatorProperty(name="DateResultFormatsDelimiter", display="Date Result Formats Delimiter", advanced=true)
+ public String getDateResultFormatsDelimiter() {
+ return dateResultFormatsDelimiter;
+ }
+
+ public void setDateResultFormatsDelimiter(String dateResultFormatsDelimiter) {
+ this.dateResultFormatsDelimiter = dateResultFormatsDelimiter;
+ }
+
+ @TranslatorProperty(name="DateResultFormats", display="Date Result Formats",advanced=true)
+ public String getDateResultFormats() {
+ return dateResultFormats;
+ }
+
+ public void setDateResultFormats(String dateResultFormats) {
+ this.dateResultFormats = dateResultFormats;
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws ConnectorException {
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+
+ return new TextSynchExecution(this, (Select)command, (TextConnection)cf.getConnection());
+ } catch (ResourceException e) {
+ throw new ConnectorException(e);
+ }
+ }
+
+ @Override
+ public void getConnectorMetadata(MetadataFactory metadataFactory, Object connectionFactory) throws ConnectorException {
+ TextConnection conn;
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+ conn = (TextConnection)cf.getConnection();
+ } catch (ResourceException e) {
+ throw new ConnectorException(e);
+ }
+
+ for (Map.Entry<String, Properties> entry : conn.getMetadataProperties().entrySet()) {
+ Properties p = entry.getValue();
+ String columns = p.getProperty(TextDescriptorPropertyNames.COLUMNS);
+ if (columns == null) {
+ continue;
+ }
+ String types = p.getProperty(TextDescriptorPropertyNames.TYPES);
+ String[] columnNames = columns.trim().split(","); //$NON-NLS-1$
+ String[] typeNames = null;
+ if (types != null) {
+ typeNames = types.trim().split(","); //$NON-NLS-1$
+ if (typeNames.length != columnNames.length) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextConnector.column_mismatch", entry.getKey())); //$NON-NLS-1$
+ }
+ }
+ Table table = metadataFactory.addTable(entry.getKey().substring(entry.getKey().indexOf('.') + 1));
+ for (int i = 0; i < columnNames.length; i++) {
+ String type = typeNames == null?TypeFacility.RUNTIME_NAMES.STRING:typeNames[i].trim().toLowerCase();
+ Column column = metadataFactory.addColumn(columnNames[i].trim(), type, table);
+ column.setNameInSource(String.valueOf(i));
+ column.setNativeType(TypeFacility.RUNTIME_NAMES.STRING);
+ }
+ }
+ }
+
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextPlugin.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextPlugin.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextPlugin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,33 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import java.util.ResourceBundle;
+import com.metamatrix.core.BundleUtil;
+
+public class TextPlugin {
+
+ public static final String PLUGIN_ID = "org.teiid.resource.adapter.text" ; //$NON-NLS-1$
+
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+}
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextSynchExecution.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextSynchExecution.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextSynchExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,555 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.resource.ResourceException;
+
+import org.teiid.connector.language.ColumnReference;
+import org.teiid.connector.language.Command;
+import org.teiid.connector.language.DerivedColumn;
+import org.teiid.connector.language.NamedTable;
+import org.teiid.connector.language.Select;
+import org.teiid.connector.metadata.runtime.Column;
+import org.teiid.connector.metadata.runtime.Table;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.TypeFacility;
+
+import com.metamatrix.core.util.StringUtil;
+
+/**
+ * The essential part that executes the query. It keeps all the execution
+ * states.
+ */
+public class TextSynchExecution extends BasicExecution implements ResultSetExecution {
+ // Command to be executed
+ private Select cmd;
+
+ private TextExecutionFactory config;
+
+ // Translator for String to Data translation
+ private StringToDateTranslator stringToDateTranslator;
+
+ // List of column widths specified
+ private List colWidths = new ArrayList();
+
+ // the number of modeled columsn should match the
+ // number of colums parsed from the file
+ private int numModeledColumns = 0;
+
+ // If a header row is to be used, this is where the
+ // column names will be saved
+ private List headerRow = null;
+
+ //whether this execution is canceled
+ private volatile boolean canceled;
+
+ private int rowsProduced = 0;
+
+ private int[] cols;
+
+ private TextConnection connection;
+
+ /**
+ * Constructor.
+ * @param cmd
+ * @param txtConn
+ */
+ public TextSynchExecution(TextExecutionFactory config, Select query, TextConnection connection) {
+ this.config = config;
+ this.cmd = query;
+ this.connection = connection;
+
+ if(this.config.getDateResultFormats() != null) {
+ stringToDateTranslator = new StringToDateTranslator(this.config);
+ }
+ }
+
+ @Override
+ public void execute() throws ConnectorException {
+ //translate request
+ translateRequest(cmd);
+
+ cols = getSelectCols(cmd.getDerivedColumns());
+ }
+
+ @Override
+ public List next() throws ConnectorException, DataNotAvailableException {
+ if (canceled) {
+ throw new ConnectorException("Execution cancelled"); //$NON-NLS-1$
+ }
+ Select query = cmd;
+ NamedTable group = (NamedTable)query.getFrom().get(0);
+ String tableName = group.getMetadataObject().getFullName().toUpperCase();
+ Properties groupProps = this.connection.getMetadataProperties().get(tableName);
+
+ Class[] types = query.getColumnTypes();
+
+ String location = groupProps.getProperty(TextDescriptorPropertyNames.LOCATION);
+ String delimiter = groupProps.getProperty(TextDescriptorPropertyNames.DELIMITER);
+ String qualifier = groupProps.getProperty(TextDescriptorPropertyNames.QUALIFIER);
+
+ try {
+ while (true) {
+ String line = this.connection.getNextLine(tableName);
+ // Hit the end of file or the file is empty then
+ if(line == null) {
+ return null;
+ }
+
+ // Get record from file for one row
+ List record = getRecord(line, delimiter, qualifier, colWidths);
+
+ ++rowsProduced;
+ // Save selected columns into query results
+
+ if (this.config.isEnforceColumnCount() && record.size() != numModeledColumns) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Input_column_cnt_incorrect", new Object[] { new Integer(numModeledColumns), new Integer(record.size()) })); //$NON-NLS-1$
+ }
+
+ return getRow(record, cols, types);
+ }
+ } catch(ConnectorException ce) {
+ throw ce;
+ } catch(Throwable e) {
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Error_reading_text_file", new Object[] { location, e.getMessage() })); //$NON-NLS-1$
+ }
+ }
+
+
+ public void close() {
+ try {
+ this.connection.close();
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "TextSynchExecution is successfully closed.");//$NON-NLS-1$
+ } catch (ResourceException e) {
+ }
+ }
+
+ public void cancel() {
+ canceled = true;
+ }
+
+ /**
+ * Translate command.
+ * @param request ICommand as request
+ * @return Object translated request
+ * @throws ConnectorException if error occurs
+ */
+ protected Object translateRequest(Command request) throws ConnectorException {
+ if (request == null) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Request_is_null")); //$NON-NLS-1$
+ }
+
+ if (cmd == null) {
+ Object[] params = new Object[] { cmd };
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Error_translating_request", params)); //$NON-NLS-1$
+ }
+
+ // Get the columns widths for all the elements in the group.
+ Select query = (Select) request;
+
+ /* Defect 13371
+ * Can't use the select columns to get the columns widths because we may not be selecting all the columns. Instead,
+ * we need to get all the child elements of the group being queried, and get the columns widths of each one of them.
+ */
+ NamedTable group = (NamedTable)query.getFrom().get(0);
+ try {
+ /* We need to create the reader queue before we
+ * attempt to create the request as we may need
+ * column names from the header row.
+ */
+ String headerLine = this.connection.getHeaderLine(group.getMetadataObject().getFullName().toUpperCase());
+ if (headerLine != null) {
+ String tableName = group.getMetadataObject().getFullName().toUpperCase();
+ Properties groupProps = this.connection.getMetadataProperties().get(tableName);
+ String delimiter = groupProps.getProperty(TextDescriptorPropertyNames.DELIMITER);
+ String qualifier = groupProps.getProperty(TextDescriptorPropertyNames.QUALIFIER);
+ this.headerRow = getRecord(headerLine, delimiter, qualifier, colWidths);
+ }
+
+ List<Column> elements = group.getMetadataObject().getColumns();
+ numModeledColumns = elements.size();
+ int[] colWidthArray = new int[elements.size()];
+ for (int i = 0; i < colWidthArray.length; i++) {
+ Column element = elements.get(i);
+ colWidthArray[getColumn(element)] = element.getLength();
+ }
+ for (int i = 0; i < colWidthArray.length; i++) {
+ colWidths.add(new Integer(colWidthArray[i]));
+ }
+
+
+ } catch (ConnectorException e) {
+ Object[] params = new Object[] { query, e.getMessage() };
+ throw new ConnectorException(e, TextPlugin.Util.getString("TextSynchExecution.Cannot_be_translated_by_the_TextTranslator.", params)); //$NON-NLS-1$
+ }
+
+ return request;
+ }
+
+ /**
+ * Convert selected column names to columns.
+ * @param vars List of DataNodeIDs
+ * @return Column numbers corresponding to vars
+ */
+ private int[] getSelectCols(List vars) throws ConnectorException{
+ int[] cols = new int[vars.size()];
+ for(int i=0; i<vars.size(); i++) {
+ cols[i] = getColumn((DerivedColumn)vars.get(i));
+ }
+ return cols;
+ }
+
+ /**
+ * Get column number in Source by ISelectSymbol
+ *
+ * An Element is created from the symbol and this method
+ * invokes getColumn(Element).
+ *
+ * @param symbol Identifier to look up the column
+ * @return int The column corresponding to that id
+ * @throws ConnectorException
+ */
+ private int getColumn(DerivedColumn symbol) throws ConnectorException{
+ return this.getColumn(getElementFromSymbol(symbol));
+ }
+
+ /**
+ * Helper method for getting runtime {@link org.teiid.connector.metadata.runtime.Element} from a
+ * {@link org.teiid.connector.language.DerivedColumn}.
+ * @param symbol Input ISelectSymbol
+ * @return Element returned metadata runtime Element
+ */
+ private Column getElementFromSymbol(DerivedColumn symbol) {
+ ColumnReference expr = (ColumnReference) symbol.getExpression();
+ return expr.getMetadataObject();
+ }
+
+ /**
+ * Get column number in Source by Element
+ *
+ * An attempt is made to parse an int from the Name In Source
+ * for the Element. If this fails it is assumed that
+ * Name In Source is blank or contains an identifier
+ * name. If blank, the Element.getMetadataID().getName()
+ * is used otherwise, Name In Source is used.
+ * @param elem
+ * @return int
+ * @throws ConnectorException
+ */
+ private int getColumn(Column elem) throws ConnectorException{
+ String colStr = elem.getNameInSource();
+ try {
+ // If Name In Source is numeric, it is a column number
+ return Integer.parseInt(colStr);
+ } catch(NumberFormatException e) {
+ // Name In Source was not numeric, so look for a column with a heading matching Name In Source
+ if ( colStr == null ) {
+ colStr = elem.getName();
+ }
+ if ( headerRow != null ) {
+ for ( int i = 0; i < headerRow.size(); i++ ) {
+ if ( colStr.compareToIgnoreCase((String)headerRow.get(i) )==0) return i;
+ }
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Column_not_found_in_header_row", new Object[] {colStr, elem.getFullName() } )); //$NON-NLS-1$
+ }
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Invalid_column_number", new Object[] {colStr, elem.getFullName() } ) ); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Open the file, read it, and parse it into memory.
+ * @param line the line is being read
+ * @param delimiter
+ * @param qualifier
+ * @param colWidths List of column widths
+ * @return List of column values inside the line
+ * @throws Exception
+ */
+ private List getRecord(String line, String delimiter, String qualifier, List colWidths) throws ConnectorException {
+ if(delimiter != null) {
+ return parseDelimitedLine(line, delimiter, qualifier);
+ }
+ return parseFixedWidthLine(line, colWidths);
+ }
+
+ /**
+ * @param line line's length will not be 0
+ * @return List of parsed columns
+ */
+ private List parseDelimitedLine(String line, String delimiter, String qualifier) throws ConnectorException {
+ // the case with no qualifier
+ if (qualifier == null || qualifier.trim().length()==0) {
+ // parse on delimiters
+ List strs = new ArrayList();
+
+ int index = -1;
+ while(true) {
+ int newIndex = line.indexOf(delimiter, index);
+ if(newIndex >= 0) {
+ if(index >= 0) {
+ // middle column
+ addUnqualifiedColumnToList(strs, line.substring(index, newIndex));
+ } else {
+ // first column
+ addUnqualifiedColumnToList(strs, line.substring(0, newIndex));
+ }
+ index = newIndex+1;
+ } else if(index >= 0) {
+ // end of line
+ addUnqualifiedColumnToList(strs, line.substring(index));
+ break;
+ } else {
+ // only one column
+ addUnqualifiedColumnToList(strs, line);
+ break;
+ }
+ }
+ return strs;
+
+ }
+ // the case with qualifier
+
+ char delimChar = delimiter.charAt(0);
+ char qualChar = qualifier.charAt(0);
+ char spaceChar = " ".charAt(0); //$NON-NLS-1$
+
+ List columns = new ArrayList();
+ int charIndex = 0;
+ int totalChars = line.length();
+
+ while(charIndex < totalChars) {
+ // Read character
+ char c = line.charAt(charIndex);
+
+ if(c == delimChar) {
+ addUnqualifiedColumnToList(columns, null);
+ charIndex++; // past delimiter
+
+ } else if(c == qualChar) {
+ int endQualIndex = charIndex;
+ while(true) {
+ endQualIndex = line.indexOf(qualChar, endQualIndex+1);
+ if(endQualIndex < 0) {
+ Object[] params = new Object[] { ""+(columns.size()+1), line }; //$NON-NLS-1$
+ // changed to Connectorexception so that the exception is thrown to the user
+ // and becomes known a problem, rather than just
+ // keeping it internally to the server
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Text_has_no_ending_qualifier", params)); //$NON-NLS-1$
+ }
+ // skipping escaped qualifier charachters
+ if(line.length() > endQualIndex+1) {
+ if(line.charAt(endQualIndex+1) == qualChar) {
+ endQualIndex = endQualIndex+1;
+ continue;
+ }
+ }
+ // quoted column
+ columns.add(line.substring(charIndex+1, endQualIndex));
+ charIndex = endQualIndex+1; // past quoted column
+
+ // Check for extra characters between quote and delimiter
+ if(charIndex < totalChars && line.charAt(charIndex) != delimChar) {
+ Object[] params = new Object[] { ""+(columns.size()+1), line }; //$NON-NLS-1$
+ String msg = TextPlugin.Util.getString("TextSynchExecution.Text_file_must_have_delimiter", params);//$NON-NLS-1$
+ // changed to Connectorexception so that the exception is thrown to the user
+ // and becomes known a problem, rather than just
+ // keeping it internally to the server
+ throw new ConnectorException(msg);
+
+ }
+
+ charIndex++; // past delimiter
+ break;
+ }
+
+ // skip any space between the delimiter
+ // and the qualifier
+ } else if(c == spaceChar) {
+ charIndex++;
+
+ } else {
+ int endColIndex = line.indexOf(delimChar, charIndex);
+ if(endColIndex < 0) {
+ // last unquoted column
+ addUnqualifiedColumnToList(columns, line.substring(charIndex));
+
+ // We know the line is done so we should exit the loop here.
+ // If we didn't exit the loop and just advanced the charIndex,
+ // we would trip the "line ends in <delim>" case below, which
+ // is not valid as we have not ended in a delimiter
+ break;
+ }
+ // middle unquoted column
+ addUnqualifiedColumnToList(columns, line.substring(charIndex, endColIndex));
+ charIndex = endColIndex+1;
+ }
+
+ // line ends in <delimiter>
+ if(charIndex == totalChars) {
+ addUnqualifiedColumnToList(columns, null);
+ }
+
+ }
+
+ return columns;
+ }
+
+ /**
+ * Add column value, if null or length is 0, then add null.
+ * @param
+ * @param
+ */
+ private static void addUnqualifiedColumnToList(List list, String col) {
+ if(col == null || col.length() == 0) {
+ list.add(null);
+ } else {
+ list.add(col);
+ }
+ }
+
+ /**
+ *
+ * @param line
+ * @param colWidths
+ * @return List
+ * @throws ConnectorException
+ */
+ private List parseFixedWidthLine(String line, List colWidths) throws ConnectorException {
+ int length = line.length();
+ List fields = new ArrayList(colWidths.size());
+ Iterator iter = colWidths.iterator();
+ int current = 0;
+ while(iter.hasNext()) {
+ try {
+ int width = ((Integer)iter.next()).intValue();
+ if(width <= 0) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Column_length_must_be_positive")); //$NON-NLS-1$
+ }
+
+ int end = current + width;
+ if(end > length) {
+ end = length;
+ }
+
+ String colValue = line.substring(current, end).trim();
+ if(colValue.length() == 0) {
+ fields.add(null);
+ } else {
+ fields.add(colValue);
+ }
+ current += width;
+ } catch(Exception e) {
+ // ignore and fill column with null
+ fields.add(null);
+ }
+ }
+
+ return fields;
+ }
+
+ /**
+ * Save selected columns from record into results.
+ * @param batch batch to contain the record
+ * @param record the record of one row
+ * @param columns Columns to save in results
+ * @param types Class of all columns' types
+ */
+ private List getRow(List record, int[] columns, Class[] types) throws ConnectorException {
+ List newRecord = new ArrayList(columns.length);
+ for(int i=0; i<columns.length; i++) {
+ int column = columns[i];
+ String value = (String) record.get(column);
+ Class type = types[i];
+ newRecord.add(convertString(value, type));
+ }
+ return newRecord;
+ }
+
+ /**
+ * Convert String to Object of correct type.
+ * @param value Input Value
+ * @param type Input type
+ * @return Object translated Object from String
+ */
+ private Object convertString(String value, Class type) throws ConnectorException {
+ if (value==null) {
+ return null;
+ }
+
+ if (type == TypeFacility.RUNTIME_TYPES.STRING) {
+ return value;
+ }
+
+ if (java.util.Date.class.isAssignableFrom(type)) {
+ //check defaults first
+ try {
+ return Timestamp.valueOf(value);
+ } catch (IllegalArgumentException e) {
+
+ }
+ try {
+ return Date.valueOf(value);
+ } catch (IllegalArgumentException e) {
+
+ }
+ try {
+ return Time.valueOf(value);
+ } catch (IllegalArgumentException e) {
+
+ }
+ //check for overrides
+ if (stringToDateTranslator!=null && stringToDateTranslator.hasFormatters()) {
+ try {
+ return new Timestamp(stringToDateTranslator.translateStringToDate(value).getTime());
+ }catch(ParseException ex) {
+ throw new ConnectorException(TextPlugin.Util.getString("TextSynchExecution.Unable_translate_String_to_Date", new Object[] { ex.getMessage() })); //$NON-NLS-1$
+ }
+ }
+ }
+ return value;
+ }
+
+}
+
Added: trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextUtil.java
===================================================================
--- trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextUtil.java (rev 0)
+++ trunk/connectors/translator-text/src/main/java/org/teiid/resource/adapter/text/TextUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.text;
+
+import java.io.File;
+
+import com.metamatrix.core.util.FileUtils;
+
+
+/**
+ * @since 4.3
+ */
+public class TextUtil {
+
+ public static boolean usesWildCard(String location) {
+ if (location == null) return false;
+
+ File datafile = new File(location);
+ String fname = datafile.getName();
+
+ // determine if the wild card is used to indicate all files
+ // of the specified extension
+ if (fname.indexOf("*") >= 0) { //$NON-NLS-1$
+ return true;
+ }
+ return false;
+ }
+ public static File[] getFiles(String location) {
+ if (location == null) return null;
+
+ File datafile = new File(location);
+ String fname = datafile.getName();
+
+ // determine if the wild card is used to indicate all files
+ // of the specified extension
+ if (fname.indexOf("*") >= 0) { //$NON-NLS-1$
+
+ File parentDir = datafile.getParentFile();
+ String ext = FileUtils.getExtension(fname);
+ return FileUtils.findAllFilesInDirectoryHavingExtension(parentDir.getAbsolutePath(), "." + ext); //$NON-NLS-1$
+ }
+ return null;
+
+ }
+}
Added: trunk/connectors/translator-text/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-text/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-text/src/main/resources/META-INF/jboss-beans.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.resource.adapter.text.TextExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Added: trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/text/i18n.properties
===================================================================
--- trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/text/i18n.properties (rev 0)
+++ trunk/connectors/translator-text/src/main/resources/org/teiid/resource/adapter/text/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,71 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+StringToDateTranslator.Attempts_to_parse_String__{0}_to_a_java.util.Date_failed_for_the_following_reasons___1=Attempts to parse String: {0} to a java.util.Date failed for the following reasons:
+StringToDateTranslator.There_is_no_format_Strings_found_in_this_formatter_object._n_2=There is no format Strings found in this formatter object.\n
+StringToDateTranslator.Parse_Attempt__{0}_using_format__{1}_failed_for_the_following_reason__{2}_4=Parse Attempt: {0} using format: {1} failed for the following reason: {2}
+StringToDateTranslator.Failed_to_convert_String__{0}_to_a_Date_using_one_of_the_following_format_Strings_that_are_specified_in_the_properties_for_this_Connector__{1}_1=Failed to convert String: {0} to a Date using one of the following format Strings that are specified in the properties for this Connector: {1}
+TextConnection.Descriptor_file_name_is_not_specified._2=Descriptor file name is not specified.
+TextConnection.Error_trying_to_establish_connection_5=Error trying to establish connection
+TextConnection.Error_while_reading_text_file__{0}_1=Error while reading text file: {0}
+TextConnection.Text_file_name_is_not_specified_for_the_group___{0}_2=Text file name is not specified for the group : {0}
+TextConnection.The_value_for_the_property_should_be_an_integer._{0}_3=The value for the property should be an integer. {0}
+TextConnection.The_property_{0}_for_the_group_{1}_is_invalid._4=The property {0} for the group {1} is invalid.
+TextConnection.Error_parsing_property_string_{0}_5=Error parsing property string {0}
+TextConnection.Error_parsing_property_string_{0}__{1}_6=Error parsing property string {0}: {1}
+TextConnection.fileDoesNotExistForGroup=Data file not found at this location: {0}, for group {1}
+TextConnection.Data_file_{0}_found_but_does_not_have_Read_permissions_8=Data file {0} found but does not have Read permissions
+TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_9=Descriptor file does not exist at this location: {0}
+TextConnection.Descriptor_file_{0}_found_but_does_not_have_Read_permissions_10=Descriptor file {0} found but does not have Read permissions
+TextConnection.Couldn__t_find_the_file_of_name_{0}_11=Couldn''t find the file of name {0}
+TextConnection.Descriptor_file_does_not_exist_at_this_location__{0}_12=Descriptor file does not exist at this location: {0}
+TextSynchExecution.Request_is_null=The Request is null.
+TextSynchExecution.No_element_in_Select=There are no element in the Select clause.
+TextSynchExecution.Not_of_type_Map=Response submitted for the request is not of type Map as expected.
+TextSynchExecution.Error_reading_text_file=Error while reading text file: {0}: {1}
+TextSynchExecution.Error_translating_request=Error translating request: Command not supported. {0}
+TextSynchExecution.Cannot_be_translated_by_the_TextTranslator.=''{0}'' cannot be translated by the TextTranslator. {1}
+TextSynchExecution.Error_obtain_properties_for_group=Error trying to obtain connector metadata properties for {0}. Group properties are not specified in the descriptor file.
+TextSynchExecution.Unable_get_Reader=Unable to get the Reader for group {0}, exception: {1}
+TextSynchExecution.Unable_get_Reader_for_group=Unable to get the Reader for group {0}. Source file undefined - check log for errors.
+TextSynchExecution.Cant_read_column_number=Cannot read column number from name in source for element. {0}
+TextSynchExecution.Invalid_column_number=Column {0} not found for element {1} and no header row is defined. If a header row cannot be defined, element {1} must define a numeric column number for its name in source property.
+TextSynchExecution.Column_not_found_in_header_row=Column {0} not found for element {1}. Verify column name \"{0}\" is defined in the header row of the text file and that the header row number is correctly defined in the descriptor file.
+TextSynchExecution.Can_read_column_number=Cannot read column number from name in source for element. {0}
+TextSynchExecution.Text_has_no_ending_qualifier=Text file has no ending qualifier in column {0}: [{1}]
+TextSynchExecution.Text_file_must_have_delimiter=Text file must have delimiter after ending qualifier in column {0}: [{1}]
+TextSynchExecution.Column_length_must_be_positive=Error trying to query the text file, column length must be a positive value.
+TextSynchExecution.Got_unknown_type_of_criteria=Got unknown type of criteria: {0}
+TextSynchExecution.Functions_not_supported._14=The criteria: {0} could not be applied to the results. Functions not supported.
+TextSynchExecution.Values_of_different_types=The following criteria cannot be executed because values are of different types: {0}
+TextSynchExecution.Unknown_compare_criteria_type=Unknown compare criteria type: {0}
+TextSynchExecution.Joins_and_Functions_not_supported._18=The criteria: {0} could not be translated by the TextConnectorTranslator. Joins and Functions not supported.
+TextSynchExecution.The_expression_cannot_be_used_as_criteria=The expression: {0} cannot be used as a criteria value in a query against a text file.
+TextSynchExecution.Functions_in_criteria_not_supported._20=The criteria: {0} cannot be translated by the TextConnectorTranslator. Functions in criteria not supported.
+TextSynchExecution.Functions_in_set_criteria_not_supported._21=The criteria: {0} cannot be translated by the TextConnectorTranslator. Functions in set criteria not supported.
+TextSynchExecution.Unable_translate_String_to_Date=Unable to translate String to Date using the format specified. {0}
+TextSynchExecution.Unable_get_Tranform=Unable to get the Tranform from String to {0}
+TextSynchExecution.Unable_to_transform_value=Unable to transform value {0} to Object of type {1}
+TextSynchExecution.Input_column_cnt_incorrect=Expected input file to have {0} columns based on model, but found {1}. This could be caused by misplaced quotes, causing multiple columns to be treated as one.
+TextSynchExecution.Text_has_no_determined_ending_qualifier=Text file has no matching ending qualifier in row {0}
+TextSynchExecution.Property_contains_an_invalid_value_Using_value=Property {0} contains an invalid value of {1}. Using value {2}.
+TextConnector.column_mismatch=Specified types and columns do not match for text table {0}
\ No newline at end of file
Added: trunk/connectors/translator-text/src/test/resources/EmpData.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/EmpData.txt (rev 0)
+++ trunk/connectors/translator-text/src/test/resources/EmpData.txt 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,51 @@
+LastName,FirstName,MiddleName,EmpId,Department,AnnualSalary,Title,HomePhone,Manager,Street,City,State,Zip
+Kisselburg,Abbiegale,Tikvica ,9000059,G,64000,MGMT WannaBe,670-270-7947,9000073,123 State St.,New York,NY,10001
+Glore,Diodie,Vojvoda ,9000060,G,71000,Associate,480-650-9750,9000073,127 State St.,Los Angeles,CA,10005
+Dawson,Pinckney,Ostoja ,9000061,G,71000,Associate,110-400-3600,9000073,135 State St.,Detroit,MI,10013
+Waldrip,Trixie,Curic ,9000062,G,57000,Newbie,820-210-7045,9000073,136 State St.,Albany,NY,10014
+Kitchen,Zilpha,Buic ,9000063,G,60000,MGMT WannaBe,660-390-3785,9000073,138 State St.,Trenton,NJ,10016
+Wakeman,Gerard,Vlahovic ,9000064,G,78000,Newbie,700-190-5880,9000073,130 State St.,Jefferson City,MO,10008
+Rafferty,Dock,Korda ,9000065,G,70000,Newbie,400-190-6192,9000073,128 State St.,Sacramento,CA,10006
+Kersavage,Zelda,Mjesecevic ,9000066,G,56000,MGMT WannaBe,802-930-1482,9000073,137 State St.,Montpelier,VT,10015
+Zummer,Gerda,Milan ,9000067,G,69000,Newbie,920-100-9701,9000073,131 State St.,Bangor,ME,10009
+Davies,Allwyne,Radic ,9000068,G,61000,Associate,470-820-6096,9000073,126 State St.,Montgomery,AL,10004
+Deanford,Abe,Skrabalo ,9000069,G,67000,Associate,907-660-8233,9000073,124 State St.,Juneau,AK,10002
+Garcia,Orsal,Ucovic ,9000070,ML,79000,CFO,480-490-7710,9000075,150 State St.,Phoenix,AZ,10028
+Zook,Orson,Bendevis ,9000071,G,71000,Newbie,350-260-8654,9000073,133 State St.,Boston,MA,10011
+Rainier,Adelaid,Marinovic ,9000072,G,67000,Newbie,316-550-3499,9000073,125 State St.,Topeka,KS,10003
+Nealon,General,,9000073,G,77000,COO,203-420-3113,9000075,129 State St.,Hartford,CT,10007
+Garahana,Jarrod,Cvjetkovic ,9000074,G,66000,Associate,620-430-1782,9000073,132 State St.,New York,NY,10010
+Neely,Petronella,Goravica ,9000075,G,80000,CEO,230-320-6330,,134 State St.,Los Angeles,CA,10012
+Gamble,Johney,Kordic ,9000123,TM,74000,Associate,330-200-8319,9000132,162 State St.,Detroit,MI,10040
+Gertanovich,Orthell,Tvrdisa ,9000124,TM,63000,Associate,600-410-3667,9000132,165 State St.,Albany,NY,10043
+Kenyon,Jim,Radovanovic ,9000125,TM,80000,MGMT WannaBe,800-510-7741,9000132,161 State St.,Trenton,NJ,10039
+Gerber,Tristan,Rogec ,9000126,TM,57000,Associate,120-990-7278,9000132,169 State St.,Jefferson City,MO,10047
+Gibb,Jaromy,Kristic ,9000127,TM,69000,Associate,270-390-9549,9000132,160 State St.,Sacramento,CA,10038
+Rader,Allissa,Radicevic ,9000128,TM,59000,Newbie,750-420-2128,9000132,157 State St.,Montpelier,VT,10035
+Kammerer,Dilbert,Capor ,9000129,TM,70000,Associate,700-280-3808,9000132,159 State St.,Bangor,ME,10037
+Knippers,Tuesday,Balic ,9000130,TM,68000,MGMT WannaBe,960-140-1045,9000132,170 State St.,Montgomery,AL,10048
+Zumwalt,Patrycia,Srezovic ,9000131,TM,72000,Newbie,210-400-7920,9000132,167 State St.,Juneau,AK,10045
+Needham,Katlyn,Metkovic ,9000132,TM,76000,Goon,380-210-1611,9000070,163 State St.,Phoenix,AZ,10041
+Keefer,Almedia,,9000133,TM,61000,MGMT WannaBe,850-640-3038,9000132,158 State St.,Boston,MA,10036
+Rampton,Orman,Cavelis ,9000134,TM,76000,Newbie,950-930-1038,9000132,164 State St.,Topeka,KS,10042
+Krepps,Paul,Skobelj ,9000135,TM,64000,MGMT WannaBe,430-500-8830,9000132,168 State St.,Hartford,CT,10046
+Deans,Zeno,Jozovic ,9000136,TM,79000,Associate,830-190-9156,9000132,172 State St.,New York,NY,10050
+Zarafonetis,Parazetti,Roncevic ,9000137,TM,73000,Newbie,710-890-2886,9000132,166 State St.,Los Angeles,CA,10044
+Davis,Tyler,Vukic ,9000138,TM,80000,Associate,540-420-5160,9000132,171 State St.,Detroit,MI,10049
+Randolph,Orwin,Rasica ,9010233,ML,44000,Newbie,200-870-4749,9000070,151 State St.,Albany,NY,10029
+Ramsey,Orran,Slade ,9010234,ML,42000,Newbie,500-830-2947,9000070,149 State St.,Trenton,NJ,10027
+Wagonlander,Blondeena,Djano ,9010235,ML,41000,Newbie,780-760-9188,9000070,141 State St.,Jefferson City,MO,10019
+Wadsworth,Alice,Hasan ,9010236,ML,40000,Newbie,230-360-1247,9000070,140 State St.,Sacramento,CA,10018
+Nolen,Parnell,Buconic ,9010237,ML,47000,Newbie,620-300-7125,9000070,152 State St.,Montpelier,VT,10030
+Glidewell,Xoe,Bagovic ,9010238,ML,45000,Associate,850-850-5647,9000070,156 State St.,Bangor,ME,10034
+Zutter,Adam,Hendic ,9010239,ML,48000,Newbie,890-300-9999,9000070,139 State St.,Montgomery,AL,10017
+Gale,Turwayne,Dalmatin ,9010240,ML,36000,Associate,600-290-9758,9000070,154 State St.,Juneau,AK,10032
+Krikwood,Javin,Vidak ,9010241,ML,42000,MGMT WannaBe,380-280-5100,9000070,146 State St.,Phoenix,AZ,10024
+Giggs,Philbert,Vidak ,9010242,ML,52000,Associate,620-270-6404,9000070,153 State St.,Boston,MA,10031
+Danford,Garnett,Brigovic ,9010243,ML,39000,Associate,880-160-7833,9000070,145 State St.,Topeka,KS,10023
+Nash,Xavier,Semes ,9010244,ML,53000,MGMT WannaBe,800-550-5917,9000070,155 State St.,Hartford,CT,10033
+Kasparek,Gallard,Jelic ,9010245,ML,47000,Associate,590-460-5850,9000070,144 State St.,New York,NY,10022
+Kernodle,Dextor,Bupic ,9010246,ML,55000,MGMT WannaBe,440-750-1427,9000070,142 State St.,Los Angeles,CA,10020
+Neighbors,Karron,Stuk ,9010247,ML,40000,Newbie,430-790-9550,9000070,147 State St.,Detroit,MI,10025
+Gilbertson,Doil,Radic ,9010248,ML,51000,Associate,870-510-5367,9000070,143 State St.,Albany,NY,10021
+Neilsen,Katheleen,,9010249,ML,36000,Newbie,550-200-5470,9000070,148 State St.,Trenton,NJ,10026
Added: trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt (rev 0)
+++ trunk/connectors/translator-text/src/test/resources/EmployeeTestDataSalary.txt 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,4 @@
+Employees.EmpTable.location = src/test/resources/EmpData.txt
+Employees.EmpTable.qualifier = "
+Employees.EmpTable.delimiter = ,
+Employees.EmpTable.skipHeaderLines = 1
Added: trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt (rev 0)
+++ trunk/connectors/translator-text/src/test/resources/libraryDelimited.txt 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,2 @@
+"1", "2003-03-25", "Blind"
+"2","1998-04-29", "Antipop"
\ No newline at end of file
Added: trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt
===================================================================
--- trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt (rev 0)
+++ trunk/connectors/translator-text/src/test/resources/testDescriptorDelimited.txt 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,6 @@
+text.library.location = src/test/resources/libraryDelimited.txt
+text.library.qualifier = "
+text.library.delimiter = ,
+text.library2.location = src/test/resources/libraryDelimited2.txt
+text.library2.qualifier = "
+text.library2.delimiter = ,
Modified: trunk/engine/src/main/java/com/metamatrix/common/buffer/TupleBuffer.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/buffer/TupleBuffer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/buffer/TupleBuffer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,10 +31,11 @@
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.Streamable;
import com.metamatrix.core.util.Assertion;
Modified: trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -43,6 +43,9 @@
import javax.xml.transform.Source;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BatchManager;
@@ -52,8 +55,6 @@
import com.metamatrix.common.buffer.TupleBatch;
import com.metamatrix.common.buffer.TupleBuffer;
import com.metamatrix.common.buffer.BatchManager.ManagedBatch;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.InputStreamFactory;
import com.metamatrix.common.types.SQLXMLImpl;
Modified: trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/FileStorageManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,11 +31,12 @@
import java.util.Map;
import java.util.TreeMap;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.common.buffer.FileStore;
import com.metamatrix.common.buffer.StorageManager;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.execution.QueryExecPlugin;
@@ -223,8 +224,8 @@
File createFile(String name, int fileNumber) throws MetaMatrixComponentException {
try {
File storageFile = File.createTempFile(FILE_PREFIX + name + "_" + String.valueOf(fileNumber) + "_", null, this.dirFile); //$NON-NLS-1$ //$NON-NLS-2$
- if (LogManager.isMessageToBeRecorded(com.metamatrix.common.log.LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
- LogManager.logDetail(com.metamatrix.common.log.LogConstants.CTX_BUFFER_MGR, "Created temporary storage area file " + storageFile.getAbsoluteFile()); //$NON-NLS-1$
+ if (LogManager.isMessageToBeRecorded(org.teiid.logging.LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
+ LogManager.logDetail(org.teiid.logging.LogConstants.CTX_BUFFER_MGR, "Created temporary storage area file " + storageFile.getAbsoluteFile()); //$NON-NLS-1$
}
return storageFile;
} catch(IOException e) {
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/JavaLogWriter.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/JavaLogWriter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/JavaLogWriter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,75 +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 com.metamatrix.common.log;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Write to Java logging
- */
-public class JavaLogWriter implements LogListener {
-
- @Override
- public boolean isEnabled(String context, int msgLevel) {
- Logger logger = Logger.getLogger(context);
-
- Level javaLevel = convertLevel(msgLevel);
- return logger.isLoggable(javaLevel);
- }
-
- public void log(int level, String context, Object msg) {
- Logger logger = Logger.getLogger(context);
-
- Level javaLevel = convertLevel(level);
- logger.log(javaLevel, msg.toString());
- }
-
- public void log(int level, String context, Throwable t, Object msg) {
- Logger logger = Logger.getLogger(context);
-
- Level javaLevel = convertLevel(level);
- logger.log(javaLevel, msg.toString(), t);
- }
-
- public Level convertLevel(int level) {
- switch (level) {
- case MessageLevel.CRITICAL:
- case MessageLevel.ERROR:
- return Level.SEVERE;
- case MessageLevel.WARNING:
- return Level.WARNING;
- case MessageLevel.INFO:
- return Level.FINE;
- case MessageLevel.DETAIL:
- return Level.FINER;
- case MessageLevel.TRACE:
- return Level.FINEST;
- }
- return Level.ALL;
- }
-
- public void shutdown() {
- }
-
-}
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/LogConstants.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/LogConstants.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/LogConstants.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,44 +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 com.metamatrix.common.log;
-
-
-public interface LogConstants {
- // add the new contexts to the Log4JUtil.java class, for configuration purpose
- public static final String CTX_SECURITY = "org.teiid.SECURITY"; //$NON-NLS-1$
- public static final String CTX_TRANSPORT = "org.teiid.TRANSPORT"; //$NON-NLS-1$
- public static final String CTX_QUERY_PLANNER = "org.teiid.PLANNER"; //$NON-NLS-1$
- public static final String CTX_DQP = "org.teiid.PROCESSOR"; //$NON-NLS-1$
- public static final String CTX_CONNECTOR = "org.teiid.CONNECTOR"; //$NON-NLS-1$
- public static final String CTX_BUFFER_MGR = "org.teiid.BUFFER_MGR"; //$NON-NLS-1$
- public static final String CTX_TXN_LOG = "org.teiid.TXN_LOG"; //$NON-NLS-1$
- public static final String CTX_COMMANDLOGGING = "org.teiid.COMMAND_LOG"; //$NON-NLS-1$
- public static final String CTX_AUDITLOGGING = "org.teiid.AUDIT_LOG"; //$NON-NLS-1$
- public static final String CTX_ADMIN_API = "org.teiid.ADMIN_API"; //$NON-NLS-1$
- public static final String CTX_RUNTIME = "org.teiid.RUNTIME"; //$NON-NLS-1$
- // Query contexts
- public static final String CTX_FUNCTION_TREE = CTX_QUERY_PLANNER + ".FUNCTION_TREE"; //$NON-NLS-1$
- public static final String CTX_QUERY_RESOLVER = CTX_QUERY_PLANNER + ".RESOLVER"; //$NON-NLS-1$
- public static final String CTX_XML_PLANNER = CTX_QUERY_PLANNER + ".XML_PLANNER"; //$NON-NLS-1$
- public static final String CTX_XML_PLAN = CTX_DQP + ".XML_PLAN"; //$NON-NLS-1$
-}
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/LogListener.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/LogListener.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/LogListener.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,51 +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 com.metamatrix.common.log;
-
-
-/**
- * LogListener
- */
-public interface LogListener {
-
- /**
- * Is the logging for the given context at the specified message level enabled.
- * @param context
- * @param msgLevel
- * @return
- */
- boolean isEnabled(String context, int msgLevel);
-
- void log(int level, String context, Object msg);
-
- void log(int level, String context, Throwable t, Object msg);
-
- /**
- * Shut down this listener, requesting it clean up and release any resources it
- * may have acquired during its use. The listener is free to ignore this
- * request if it is not responsible for managing the resources it uses or if
- * there are no resources.
- */
- void shutdown();
-
-}
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/LogManager.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/LogManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/LogManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,399 +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 com.metamatrix.common.log;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-
-
-/**
- * This class represents the interface to a single logging framework
- * that is easily accessible by any component. Using the LogManager, a component
- * can quickly submit a log message, and can rely upon the LogManager to determine
- * (a) whether that message is to be recorded or discarded; and (b) where
- * to send any recorded messages. Thus, the component's code that submits
- * messages does not have to be modified to alter the logging behavior of the
- * application.
- * <p>
- * By default, all context(s) are logged by the LogManager. The messages that
- * the LogManager actually records and sends to the destinations
- * can be controlled using two different and orthogonal parameters.
- * The first is a message <i>level</i> that filters messages based upon detail,
- * and the second is a message <i>context</i> that filters messages based upon
- * origin. The LogManager tracks only those context(s) that should NOT be
- * logged. Only if a message (which also is defined with these two parameters)
- * passes both filters will it be sent to the destinations.
- * <p>
- * Each message is submitted with one of the following levels (determined
- * by the particular method used to submit the message), sorted from the
- * least detailed to the greatest:
- * <li><b>Critical</b>: This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.</li>
- * <li><b>Error</b>: Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.</li>
- * <li><b>Warning</b>: Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.</li>
- * <li><b>Information</b>: This level of logging is the usually
- * the normal level. All interesting periodic events should be logged at this
- * level so someone looking through the log can see the amount and kind of
- * processing happening in the system.</li>
- * <li><b>Detail</b>: Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.</li>
- * <li><b>Trace</b>: A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.</li>
- * <p>
- * The context for a message is any application-specified String. Again, only
- * those message contexts that match those in the LogManager's configuration will
- * be sent to the destinations.
- *
- */
-public final class LogManager {
-
- public static class LoggingProxy implements InvocationHandler {
- private final Object instance;
- private final String loggingContext;
- private final int level;
-
- public LoggingProxy(Object instance, String loggingContext, int level) {
- this.instance = instance;
- this.loggingContext = loggingContext;
- this.level = level;
- }
-
- public Object invoke(Object proxy,
- Method method,
- Object[] args) throws Throwable {
- boolean log = LogManager.isMessageToBeRecorded(loggingContext, level);
- if (log) {
- StringBuffer message = new StringBuffer();
- message.append("before "); //$NON-NLS-1$
- message.append(method.getName());
- message.append(":"); //$NON-NLS-1$
- message.append(instance);
- message.append("("); //$NON-NLS-1$
- if (args != null) {
- for (int i = 0; i < args.length; i++) {
- if (args[i] != null) {
- message.append(args[i]);
- } else {
- message.append("null"); //$NON-NLS-1$
- }
- if (i != args.length - 1) {
- message.append(","); //$NON-NLS-1$
- }
- }
- }
- message.append(")"); //$NON-NLS-1$
- LogManager.log(level, loggingContext, message.toString());
- }
- try {
- Object result = method.invoke(instance, args);
- if (log) {
- LogManager.log(level, loggingContext,
- "after " + method.getName()+ " : "+result); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return result;
- } catch (InvocationTargetException e) {
- throw e.getTargetException();
- }
- }
- }
-
- static LogListener logListener = new JavaLogWriter(); // either injected or manually set using the set methods
-
- /**
- * Send a critical message to the log. This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logCritical(String context, String message) {
- logMessage(MessageLevel.CRITICAL, context, message);
- }
-
- /**
- * Send a critical message to the log. This level of message is generally
- * used to record an event or error that must be recorded (if any logging
- * is used). If it is used to record an error, it generally means that the
- * system encountered a critical error which affects the integrity, accuracy,
- * reliability and/or capability of the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logCritical(String context, Throwable e, String message) {
- log(MessageLevel.CRITICAL,context,e,message);
- }
-
- /**
- * Send an error message to the log. Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logError(String context, String message) {
- logMessage(MessageLevel.ERROR, context,message);
- }
-
- /**
- * Send an error message to the log. Error messages are generally used
- * to record unexpected problems, or errors that are not critical in nature
- * and from which the system can automatically recover.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logError(String context, Throwable e, String message) {
- log(MessageLevel.ERROR,context,e,message);
- }
-
- /**
- * Send a warning message to the log. Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logWarning(String context, String message) {
- logMessage(MessageLevel.WARNING, context,message);
- }
-
- /**
- * Send a warning message to the log. Warning messages generally described
- * expected errors from which the system should recover. However, this level
- * is used to record the fact that such an error or event did occur.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logWarning(String context, Throwable e, String message) {
- log(MessageLevel.WARNING,context,e,message);
- }
-
- /**
- * Send a information message to the log. This level of logging is the usually
- * the normal level. All interesting periodic events should be logged at this
- * level so someone looking through the log can see the amount and kind of
- * processing happening in the system.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the log message; the message is
- * not logged if this parameter is null
- */
- public static void logInfo(String context, String message) {
- logMessage(MessageLevel.INFO, context,message);
- }
-
- /**
- * Send a detail message to the log. Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param msgParts the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void logDetail(String context, Object ... msgParts) {
- logMessage(MessageLevel.DETAIL, context, msgParts);
- }
-
- /**
- * Send a detail message to the log. Such messages are moderately detailed,
- * and help to debug typical problems in the system. Generally, these
- * messages are not so detailed that the big picture gets lost.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the log message (may be null)
- */
- public static void logDetail(String context, Throwable e, Object ... message) {
- log(MessageLevel.DETAIL,context,e,message);
- }
-
- /**
- * Send a trace message to the log. A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param msgParts the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void logTrace(String context, Object ... msgParts) {
- logMessage(MessageLevel.TRACE, context, msgParts);
- }
-
- /**
- * Send a trace message to the log. A trace message is the most detailed
- * logging level, used to trace system execution for really nasty problems.
- * At this level, logging will be so verbose that the system performance
- * may be affected.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param msgParts the individual parts of the log message (may be null)
- */
- public static void logTrace(String context, Throwable e, Object ... msgParts) {
- logMessage(MessageLevel.TRACE,context,e,msgParts);
- }
-
- /**
- * Send a message of the specified level to the log.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param msgLevel
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param message the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void log(int msgLevel, String context, Object message) {
- logMessage(msgLevel, context, message);
- }
-
- /**
- * Send a message of the specified level to the log.
- * <p>
- * Only if the log manager is configured to send such messages to the
- * destination will the message be recorded.
- * @param context the context for this log message (for example, the component
- * that is generating this message).
- * @param e the exception that is to be logged; the message is
- * not logged if this parameter is null
- * @param message the individual parts of the log message; the message is
- * not logged if this parameter is null
- */
- public static void log(int msgLevel, String context, Throwable e, Object message) {
- if (!isMessageToBeRecorded(context, msgLevel)) {
- return;
- }
- logListener.log(msgLevel, context, e, message);
- }
-
- public static void setLogListener(LogListener listener) {
- logListener.shutdown();
- if (listener != null) {
- logListener = listener;
- }
- else {
- logListener = new JavaLogWriter();
- }
- }
-
- /**
- * Utility method to identify whether a log message with the specified
- * context and level will be recorded in the LogManager's destinations.
- * @param context
- * @param msgLevel
- * @return true if the message would be recorded if sent to the LogManager,
- * or false if it would be discarded by the LogManager.
- */
- public static boolean isMessageToBeRecorded(String context, int msgLevel) {
- if (logListener != null) {
- return logListener.isEnabled(context, msgLevel);
- }
- return true;
- }
-
- private static void logMessage(int level, String context, Object ... msgParts) {
- if (msgParts == null || msgParts.length == 0 || !isMessageToBeRecorded(context, level)) {
- return;
- }
- logListener.log(level, context, new LogMessage(msgParts));
- }
-
-
- /**
- * Create a logging proxy, that logs at entry and exit points of the method calls on the provided interfaces.
- */
- public static Object createLoggingProxy(final String loggingContext,
- final Object instance,
- final Class<?>[] interfaces,
- final int level) {
- return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new LoggingProxy(instance, loggingContext, level));
- }
-}
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/LogMessage.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/LogMessage.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/LogMessage.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,62 +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 com.metamatrix.common.log;
-
-import java.io.Serializable;
-
-
-public class LogMessage implements Serializable{
-
- private Object[] msgParts;
-
- public LogMessage(Object[] msgParts) {
- this.msgParts = msgParts;
- }
-
- public Object[] getMessageParts() {
- return this.msgParts;
- }
-
- public String getText() {
- StringBuffer text = null;
- if(msgParts != null) {
- text = new StringBuffer();
- for(int i=0; i<msgParts.length; i++) {
- if (i>0) text.append(" "); //$NON-NLS-1$
- Object omsg = msgParts[i];
- if ( omsg != null ) {
- text.append(omsg.toString());
- }
- }
- }
-
- if (text == null) {
- return "NULL"; //$NON-NLS-1$
- }
- return text.toString();
- }
-
- public String toString() {
- return getText();
- }
-}
Deleted: trunk/engine/src/main/java/com/metamatrix/common/log/MessageLevel.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/log/MessageLevel.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/common/log/MessageLevel.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,230 +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 com.metamatrix.common.log;
-
-import java.util.*;
-
-/**
- * Constants that define the level of the messages that are to be recorded
- * by the LogManager.
- */
-public final class MessageLevel {
-
- /**
- * Message level value that specifies that no messages are to be recorded.
- */
- public static final int NONE = 0;
-
- /**
- * Message level value that specifies that critical messages are to be recorded.
- */
- public static final int CRITICAL = 1;
-
- /**
- * Message level value that specifies that error messages and critical
- * messages are to be recorded.
- */
- public static final int ERROR = 2;
-
- /**
- * Message level value that specifies that warning, error and critical
- * messages are to be recorded.
- */
- public static final int WARNING = 3;
-
- /**
- * Message level value that specifies that information, warning, error and critical
- * messages are to be recorded.
- */
- public static final int INFO = 4;
-
- /**
- * Message level value that specifies that detailed, information, warning, error and critical
- * messages are to be recorded.
- */
- public static final int DETAIL = 5;
-
- /**
- * Message level value that specifies that all messages are to be recorded.
- */
- public static final int TRACE = 6;
-
-
- /**
- * The default message level is WARNING.
- */
- public static final int DEFAULT_MESSAGE_LEVEL = WARNING;
-
- private static final int MINIMUM = NONE;
- private static final int MAXIMUM = TRACE;
-
- /**
- * Constants that define the types of the messages that are to be recorded
- * by the LogManager.
- */
- public static class Labels {
- public static final String CRITICAL = "CRITICAL"; //$NON-NLS-1$
- public static final String ERROR = "ERROR"; //$NON-NLS-1$
- public static final String WARNING = "WARNING"; //$NON-NLS-1$
- public static final String INFO = "INFO"; //$NON-NLS-1$
- public static final String DETAIL = "DETAIL"; //$NON-NLS-1$
- public static final String TRACE = "TRACE"; //$NON-NLS-1$
- public static final String NONE = "NONE"; //$NON-NLS-1$
- static final String UNKNOWN = "UNKNOWN"; //$NON-NLS-1$
- }
-
- /**
- * Constants that define the types of the messages that are to be recorded
- * by the LogManager.
- */
- public static class DisplayNames {
- public static final String CRITICAL = "Critical"; //$NON-NLS-1$
- public static final String ERROR = "Error"; //$NON-NLS-1$
- public static final String WARNING = "Warning"; //$NON-NLS-1$
- public static final String INFO = "Information"; //$NON-NLS-1$
- public static final String DETAIL = "Detail"; //$NON-NLS-1$
- public static final String TRACE = "Trace"; //$NON-NLS-1$
- public static final String NONE = "None"; //$NON-NLS-1$
- }
-
- private static Map LABEL_TO_LEVEL_MAP = new HashMap();
- private static Map DISPLAY_TO_LEVEL_MAP = new HashMap();
- private static List LABELS = new ArrayList(MAXIMUM - MINIMUM + 1);
- private static List DISPLAYS = new ArrayList(MAXIMUM - MINIMUM + 1);
-
- static {
- LABEL_TO_LEVEL_MAP.put(Labels.CRITICAL, new Integer(CRITICAL) );
- LABEL_TO_LEVEL_MAP.put(Labels.ERROR, new Integer(ERROR) );
- LABEL_TO_LEVEL_MAP.put(Labels.WARNING, new Integer(WARNING) );
- LABEL_TO_LEVEL_MAP.put(Labels.INFO, new Integer(INFO) );
- LABEL_TO_LEVEL_MAP.put(Labels.DETAIL, new Integer(DETAIL) );
- LABEL_TO_LEVEL_MAP.put(Labels.TRACE, new Integer(TRACE) );
- LABEL_TO_LEVEL_MAP.put(Labels.NONE, new Integer(NONE) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.CRITICAL, new Integer(CRITICAL) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.ERROR, new Integer(ERROR) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.WARNING, new Integer(WARNING) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.INFO, new Integer(INFO) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.DETAIL, new Integer(DETAIL) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.TRACE, new Integer(TRACE) );
- DISPLAY_TO_LEVEL_MAP.put(DisplayNames.NONE, new Integer(NONE) );
-
- // Do in the correct order so that the indexes match the levels
- LABELS.add(Labels.NONE);
- LABELS.add(Labels.CRITICAL);
- LABELS.add(Labels.ERROR);
- LABELS.add(Labels.WARNING);
- LABELS.add(Labels.INFO);
- LABELS.add(Labels.DETAIL);
- LABELS.add(Labels.TRACE);
- DISPLAYS.add(DisplayNames.NONE);
- DISPLAYS.add(DisplayNames.CRITICAL);
- DISPLAYS.add(DisplayNames.ERROR);
- DISPLAYS.add(DisplayNames.WARNING);
- DISPLAYS.add(DisplayNames.INFO);
- DISPLAYS.add(DisplayNames.DETAIL);
- DISPLAYS.add(DisplayNames.TRACE);
- }
-
- /**
- * Utility method to set the level of messages that are recorded for this VM.
- * @param newMessageLevel the new level; must be either
- * <code>MessageLevel.NONE</code>,
- * <code>MessageLevel.CRITICAL</code>,
- * <code>MessageLevel.ERROR</code>,
- * <code>MessageLevel.WARNING</code>,
- * <code>MessageLevel.INFO</code>,
- * <code>MessageLevel.DETAIL</code>, or
- * <code>MessageLevel.TRACE.
- * @throws IllegalArgumentException if the level is out of range.
- */
- public static boolean isMessageLevelValid( int newMessageLevel ) {
- return !( newMessageLevel < MessageLevel.NONE || newMessageLevel > MessageLevel.TRACE );
- }
-
- /**
- * Utility method for knowing what is the lower boundary for
- * a valid message level.
- * @return int message level
- * @see #validUpperMessageLevel
- */
- public static int getValidLowerMessageLevel() {
- return MessageLevel.NONE;
- }
-
- /**
- * Utility method for knowing what is the upper boundary for
- * a valid message level.
- * @return int message level
- * @see #validLowerMessageLevel
- */
- public static int getValidUpperMessageLevel() {
- return MessageLevel.TRACE;
- }
-
- public static String getLabelForLevel( int level ) {
- switch ( level ) {
- case MessageLevel.NONE:
- return Labels.NONE;
- case MessageLevel.CRITICAL:
- return Labels.CRITICAL;
- case MessageLevel.ERROR:
- return Labels.ERROR;
- case MessageLevel.WARNING:
- return Labels.WARNING;
- case MessageLevel.INFO:
- return Labels.INFO;
- case MessageLevel.DETAIL:
- return Labels.DETAIL;
- case MessageLevel.TRACE:
- return Labels.TRACE;
- }
- return Labels.UNKNOWN;
- //throw new IllegalArgumentException("The specified message level \"" + level + "\" is invalid");
- }
-
- public static int getMinimumLevel() {
- return MINIMUM;
- }
-
- public static int getMaximumLevel() {
- return MAXIMUM;
- }
-
- public static Collection getDisplayNames() {
- return DISPLAYS;
- }
-
-
- /**
- * Utility method to get the labels for the levels, starting with the lowest
- * level and ending with the highest level.
- * @return an ordered list of String labels
- */
- public static List getLabels() {
- return LABELS;
- }
-
-
-
-}
-
Modified: trunk/engine/src/main/java/com/metamatrix/query/analysis/AnalysisRecord.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/analysis/AnalysisRecord.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/analysis/AnalysisRecord.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -33,10 +33,10 @@
import org.teiid.client.plan.Annotation;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.sql.LanguageObject;
import com.metamatrix.query.sql.lang.SubqueryContainer;
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/FunctionTree.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/FunctionTree.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/FunctionTree.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -35,8 +35,9 @@
import java.util.Map;
import java.util.Set;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.Assertion;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/capabilities/BasicSourceCapabilities.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/capabilities/BasicSourceCapabilities.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/capabilities/BasicSourceCapabilities.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -41,7 +41,7 @@
}
/**
- * @see com.metamatrix.server.datatier.ConnectorCapabilities#supportsCapability(java.lang.String)
+ * @see org.teiid.resource.cci.server.datatier.ConnectorCapabilities#supportsCapability(java.lang.String)
*/
public boolean supportsCapability(Capability capability) {
Boolean supports = (Boolean) capabilityMap.get(capability);
@@ -49,7 +49,7 @@
}
/**
- * @see com.metamatrix.server.datatier.ConnectorCapabilities#supportsFunction(java.lang.String)
+ * @see org.teiid.resource.cci.server.datatier.ConnectorCapabilities#supportsFunction(java.lang.String)
*/
public boolean supportsFunction(String functionName) {
Boolean supports = (Boolean) functionMap.get(functionName);
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,6 +34,8 @@
import org.teiid.client.plan.Annotation;
import org.teiid.client.plan.Annotation.Priority;
import org.teiid.dqp.internal.process.Request;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -41,8 +43,6 @@
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.query.QueryPlugin;
import com.metamatrix.query.analysis.AnalysisRecord;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CapabilitiesUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CapabilitiesUtil.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CapabilitiesUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,8 +27,8 @@
import java.util.Iterator;
import java.util.List;
-import org.teiid.connector.api.ConnectorCapabilities.SupportedJoinCriteria;
import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.resource.cci.ConnectorCapabilities.SupportedJoinCriteria;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/NewCalculateCostUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,11 +34,12 @@
import java.util.List;
import java.util.Map;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.common.buffer.BufferManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.QueryPlugin;
import com.metamatrix.query.metadata.QueryMetadataInterface;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCopyCriteria.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCopyCriteria.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCopyCriteria.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -32,10 +32,11 @@
import java.util.Map;
import java.util.Set;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.optimizer.capabilities.CapabilitiesFinder;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePlanJoins.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePlanJoins.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePlanJoins.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -33,7 +33,7 @@
import java.util.Map;
import java.util.Set;
-import org.teiid.connector.api.ConnectorCapabilities.SupportedJoinCriteria;
+import org.teiid.resource.cci.ConnectorCapabilities.SupportedJoinCriteria;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleRaiseAccess.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,7 +28,7 @@
import java.util.List;
import java.util.Set;
-import org.teiid.connector.api.ConnectorCapabilities.SupportedJoinCriteria;
+import org.teiid.resource.cci.ConnectorCapabilities.SupportedJoinCriteria;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/XMLPlanner.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/XMLPlanner.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/XMLPlanner.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,11 +27,12 @@
import java.util.Iterator;
import java.util.List;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.execution.QueryExecPlugin;
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/QueryProcessor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/QueryProcessor.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/QueryProcessor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,7 +24,10 @@
import java.util.List;
-import org.teiid.connector.api.DataNotAvailableException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.resource.cci.DataNotAvailableException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixException;
@@ -34,9 +37,6 @@
import com.metamatrix.common.buffer.TupleBatch;
import com.metamatrix.common.buffer.BufferManager.BufferReserveMode;
import com.metamatrix.common.buffer.BufferManager.TupleSourceType;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.execution.QueryExecPlugin;
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/AssignmentInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/AssignmentInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/AssignmentInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,12 +27,12 @@
import java.util.Arrays;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.processor.program.ProgramInstruction;
import com.metamatrix.query.sql.symbol.ElementSymbol;
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ErrorInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ErrorInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ErrorInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,10 +26,10 @@
import org.teiid.client.ProcedureErrorInstructionException;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.processor.program.ProgramInstruction;
import com.metamatrix.query.sql.symbol.Expression;
@@ -76,7 +76,7 @@
public void process(ProcedurePlan env) throws MetaMatrixComponentException,
MetaMatrixProcessingException {
Object value = env.evaluateExpression(expression);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP,
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP,
new Object[] {"Processing RaiseErrorInstruction with the value :", value}); //$NON-NLS-1$
throw new ProcedureErrorInstructionException(ERROR_PREFIX + (value != null ? value.toString() : "")); //$NON-NLS-1$
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ExecDynamicSqlInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -33,12 +33,12 @@
import org.teiid.client.plan.PlanNode;
import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.query.analysis.AnalysisRecord;
@@ -133,7 +133,7 @@
.getString("ExecDynamicSqlInstruction.0")); //$NON-NLS-1$
}
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP,
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP,
new Object[] { "Executing dynamic sql ", value }); //$NON-NLS-1$
Command command = QueryParser.getQueryParser().parseCommand(value.toString());
@@ -230,7 +230,7 @@
for (SetClause setClause : dynamicCommand.getUsing().getClauses()) {
Object assignment = procEnv.evaluateExpression(setClause.getValue());
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP,
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP,
new Object[] { this, " The using variable ", //$NON-NLS-1$
setClause.getSymbol(), " has value :", assignment }); //$NON-NLS-1$
localContext.setValue(setClause.getSymbol(), assignment);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/IfInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/IfInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/IfInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,11 +25,11 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.processor.program.Program;
import com.metamatrix.query.processor.program.ProgramInstruction;
import com.metamatrix.query.sql.lang.Criteria;
@@ -91,13 +91,13 @@
boolean evalValue = procEnv.evaluateCriteria(condition);
if(evalValue) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[]{"IFInstruction: "+ //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, new Object[]{"IFInstruction: "+ //$NON-NLS-1$
" The criteria on the if block evaluated to true, processing the if block"}); //$NON-NLS-1$
//push the "if" Program onto the stack
procEnv.push(ifProgram);
} else if(elseProgram != null) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[]{"IFInstruction: "+ //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, new Object[]{"IFInstruction: "+ //$NON-NLS-1$
" The criteria on the if block evaluated to false, processing the else block"}); //$NON-NLS-1$
//push the "else" Program onto the stack
procEnv.push(elseProgram);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/proc/ProcedurePlan.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -36,6 +36,7 @@
import java.util.Stack;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -45,7 +46,6 @@
import com.metamatrix.common.buffer.IndexedTupleSource;
import com.metamatrix.common.buffer.TupleBatch;
import com.metamatrix.common.buffer.TupleSource;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.metadata.QueryMetadataInterface;
@@ -173,7 +173,7 @@
originalProgram.resetProgramCounter();
programs.clear();
programs.push(originalProgram);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "ProcedurePlan reset"); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "ProcedurePlan reset"); //$NON-NLS-1$
}
public ProcessorDataManager getDataManager() {
@@ -272,23 +272,23 @@
Program program = peek();
inst = program.getCurrentInstruction();
if (inst == null){
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Finished program", program); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Finished program", program); //$NON-NLS-1$
this.pop();
continue;
}
if (inst instanceof RepeatedInstruction) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Executing repeated instruction", inst); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Executing repeated instruction", inst); //$NON-NLS-1$
RepeatedInstruction loop = (RepeatedInstruction)inst;
if (loop.testCondition(this)) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Passed condition, executing program " + loop.getNestedProgram()); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Passed condition, executing program " + loop.getNestedProgram()); //$NON-NLS-1$
inst.process(this);
this.push(loop.getNestedProgram());
continue;
}
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Exiting repeated instruction", inst); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Exiting repeated instruction", inst); //$NON-NLS-1$
loop.postInstruction(this);
} else {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Executing instruction", inst); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Executing instruction", inst); //$NON-NLS-1$
inst.process(this);
}
program.incrementProgramCounter();
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/PlanExecutionNode.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/PlanExecutionNode.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/PlanExecutionNode.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,12 +27,12 @@
import java.util.List;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.TupleBatch;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.processor.ProcessorPlan;
import com.metamatrix.query.sql.util.VariableContext;
import com.metamatrix.query.util.CommandContext;
@@ -141,7 +141,7 @@
try {
plan.close();
} catch (MetaMatrixComponentException e1){
- LogManager.logDetail(com.metamatrix.common.log.LogConstants.CTX_DQP, e1, "Error closing processor"); //$NON-NLS-1$
+ LogManager.logDetail(org.teiid.logging.LogConstants.CTX_DQP, e1, "Error closing processor"); //$NON-NLS-1$
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNode.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNode.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/RelationalNode.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,14 +31,14 @@
import java.util.Map;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.TupleBatch;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.processor.ProcessorDataManager;
@@ -385,7 +385,7 @@
* @param batch Batch being sent
*/
private void recordBatch(TupleBatch batch) {
- if (!this.context.getProcessDebug() || !LogManager.isMessageToBeRecorded(com.metamatrix.common.log.LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+ if (!this.context.getProcessDebug() || !LogManager.isMessageToBeRecorded(org.teiid.logging.LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
return;
}
// Print summary
@@ -401,7 +401,7 @@
for (int row = batch.getBeginRow(); row <= batch.getEndRow(); row++) {
str.append("\t").append(row).append(": ").append(batch.getTuple(row)).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
- LogManager.logDetail(com.metamatrix.common.log.LogConstants.CTX_DQP, str.toString());
+ LogManager.logDetail(org.teiid.logging.LogConstants.CTX_DQP, str.toString());
}
// =========================================================================
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/SortUtility.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/SortUtility.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/SortUtility.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,6 +29,9 @@
import java.util.ListIterator;
import java.util.TreeSet;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
@@ -38,8 +41,6 @@
import com.metamatrix.common.buffer.TupleSource;
import com.metamatrix.common.buffer.BufferManager.BufferReserveMode;
import com.metamatrix.common.buffer.BufferManager.TupleSourceType;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.sql.lang.OrderBy;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
@@ -261,8 +262,8 @@
bufferManager.releaseBuffers(release);
reserved -= release;
try {
- if (LogManager.isMessageToBeRecorded(com.metamatrix.common.log.LogConstants.CTX_DQP, MessageLevel.TRACE)) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, "Merging", maxSortIndex, "sublists out of", activeTupleBuffers.size()); //$NON-NLS-1$ //$NON-NLS-2$
+ if (LogManager.isMessageToBeRecorded(org.teiid.logging.LogConstants.CTX_DQP, MessageLevel.TRACE)) {
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Merging", maxSortIndex, "sublists out of", activeTupleBuffers.size()); //$NON-NLS-1$ //$NON-NLS-2$
}
// initialize the sublists with the min value
for(int i = 0; i<maxSortIndex; i++) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AbortProcessingInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AbortProcessingInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AbortProcessingInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,11 +23,11 @@
package com.metamatrix.query.processor.xml;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.util.ErrorMessageKeys;
@@ -59,7 +59,7 @@
public XMLContext process(XMLProcessorEnvironment env, XMLContext context)
throws BlockedException, MetaMatrixComponentException, MetaMatrixProcessingException{
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, "ABORT processing now."); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, "ABORT processing now."); //$NON-NLS-1$
throw new MetaMatrixComponentException(DEFAULT_MESSAGE);
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddCommentInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddCommentInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddCommentInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,12 +25,12 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
/**
* Adds a comment to an element of the document in progress
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddNodeInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddNodeInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/AddNodeInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,11 +30,11 @@
import java.util.Properties;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.sql.symbol.ElementSymbol;
@@ -97,15 +97,15 @@
if (defaultValue != null){
if(isElement) {
success = doc.addElement(descriptor, defaultValue);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"fixed value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"fixed value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
} else {
success = doc.addAttribute(descriptor, defaultValue);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"fixed value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"fixed value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
if(isElement) {
success = doc.addElement(descriptor, nillableDescriptor);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName()}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName()}); //$NON-NLS-1$
} //else nothing gets outputted for attribute with no content
}
} else {
@@ -115,24 +115,24 @@
if (valueStr != null){
if(isElement) {
success = doc.addElement(descriptor, valueStr);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"value",valueStr}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"value",valueStr}); //$NON-NLS-1$ //$NON-NLS-2$
} else {
success = doc.addAttribute(descriptor, valueStr);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"value",valueStr}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"value",valueStr}); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
if (defaultValue != null){
if(isElement) {
success = doc.addElement(descriptor, defaultValue);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"default value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"default value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
} else {
success = doc.addAttribute(descriptor, defaultValue);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"default value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG attr",descriptor.getName(),"default value",defaultValue}); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
if(isElement) {
success = doc.addElement(descriptor, nillableDescriptor);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"no value"}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"TAG elem",descriptor.getName(),"no value"}); //$NON-NLS-1$ //$NON-NLS-2$
} //else nothing gets outputted for attribute with no content
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndBlockInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndBlockInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndBlockInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,11 +25,11 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
/**
* <p>This instruction closes a result set, which closes and removes the TupleSource
@@ -66,7 +66,7 @@
context.removeResultSet(resultSetName);
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{CLOSE_FINISHED,resultSetName});
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{CLOSE_FINISHED,resultSetName});
env.incrementCurrentProgramCounter();
return context;
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndDocumentInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndDocumentInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/EndDocumentInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,11 +23,11 @@
package com.metamatrix.query.processor.xml;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
/**
* This instruction marks the current document in progress as
@@ -52,7 +52,7 @@
// program stack (don't want to start a new doc in the middle of
// recursive processing)
if (!env.isRecursiveProgramInStack()) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, "ending document"); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, "ending document"); //$NON-NLS-1$
env.getDocumentInProgress().markAsFinished();
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecSqlInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecSqlInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecSqlInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,11 +25,11 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.mapping.xml.ResultSetInfo;
/**
@@ -48,7 +48,7 @@
public XMLContext process(XMLProcessorEnvironment env, XMLContext context)
throws BlockedException, MetaMatrixComponentException, MetaMatrixProcessingException{
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
PlanExecutor executor = context.getResultExecutor(resultSetName);
if (executor == null) {
executor = env.createResultExecutor(resultSetName, info);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecStagingTableInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecStagingTableInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/ExecStagingTableInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,11 +27,11 @@
import java.util.Map;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.mapping.xml.ResultSetInfo;
@@ -61,7 +61,7 @@
throws BlockedException, MetaMatrixComponentException, MetaMatrixProcessingException {
if (!env.isStagingTableLoaded(this.resultSetName)) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
PlanExecutor executor = context.getResultExecutor(resultSetName);
if (executor == null) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/IfInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/IfInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/IfInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,11 +28,11 @@
import java.util.List;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
/**
* <p>This instruction holds a List of Criteria, and for each Criteria there is a
@@ -196,7 +196,7 @@
Program thenProgram = condition.getThenProgram();
env.pushProgram(thenProgram, condition.isProgramRecursive());
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"IF: true condition", condition, "- then program:", thenProgram}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"IF: true condition", condition, "- then program:", thenProgram}); //$NON-NLS-1$ //$NON-NLS-2$
}
return context;
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/InitializeDocumentInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/InitializeDocumentInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/InitializeDocumentInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,11 +25,11 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.mapping.xml.MappingNodeConstants;
import com.metamatrix.query.util.XMLFormatConstants;
@@ -78,7 +78,7 @@
public XMLContext process(XMLProcessorEnvironment env, XMLContext context)
throws BlockedException, MetaMatrixComponentException, MetaMatrixProcessingException{
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, "DOC begin"); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, "DOC begin"); //$NON-NLS-1$
// Only process this instruction if there are no recursive programs in the
// program stack (don't want to start a new doc in the middle of
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveCursorInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveCursorInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveCursorInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,11 +25,11 @@
import static com.metamatrix.query.analysis.AnalysisRecord.*;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
/**
*/
@@ -52,7 +52,7 @@
public XMLContext process(XMLProcessorEnvironment env, XMLContext context)
throws BlockedException, MetaMatrixComponentException, MetaMatrixProcessingException {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"NEXT", resultSetName}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"NEXT", resultSetName}); //$NON-NLS-1$
context.getNextRow(resultSetName);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveDocInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveDocInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/MoveDocInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,12 +23,12 @@
package com.metamatrix.query.processor.xml;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import org.xml.sax.SAXException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.util.ErrorMessageKeys;
@@ -59,7 +59,7 @@
switch(this.direction) {
case UP:
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, "UP in document"); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, "UP in document"); //$NON-NLS-1$
try {
doc.moveToParent();
} catch (SAXException err) {
@@ -67,7 +67,7 @@
}
break;
case DOWN:
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, "LAST child in document"); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, "LAST child in document"); //$NON-NLS-1$
doc.moveToLastChild();
break;
default:
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/RelationalPlanExecutor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/RelationalPlanExecutor.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/RelationalPlanExecutor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,12 +25,13 @@
import java.util.List;
import java.util.Map;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.IndexedTupleSource;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.mapping.xml.ResultSetInfo;
import com.metamatrix.query.processor.BatchIterator;
@@ -153,7 +154,7 @@
*/
public void close() throws MetaMatrixComponentException {
this.internalProcessor.closeProcessing();
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"closed executor", resultInfo.getResultSetName()}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"closed executor", resultInfo.getResultSetName()}); //$NON-NLS-1$
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/SAXDocumentInProgress.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/SAXDocumentInProgress.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/SAXDocumentInProgress.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -33,12 +33,12 @@
import net.sf.saxon.TransformerFactoryImpl;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import org.xml.sax.SAXException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.common.buffer.FileStore;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.query.mapping.xml.MappingNodeConstants;
/**
@@ -154,7 +154,7 @@
return true;
}
} catch (SAXException e) {
- LogManager.logError(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, e, e.getMessage());
+ LogManager.logError(org.teiid.logging.LogConstants.CTX_XML_PLAN, e, e.getMessage());
return false;
}
showState( "addElement(2) - BOT" ); //$NON-NLS-1$
@@ -323,19 +323,19 @@
private void showState( String sOccasion ) {
- if (LogManager.isMessageToBeRecorded(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, MessageLevel.TRACE)) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"\n [showState] State Vars at: " + sOccasion} ); //$NON-NLS-1$
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent: " + currentParent} ); //$NON-NLS-1$
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentObject: " + currentObject} ); //$NON-NLS-1$
+ if (LogManager.isMessageToBeRecorded(org.teiid.logging.LogConstants.CTX_XML_PLAN, MessageLevel.TRACE)) {
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"\n [showState] State Vars at: " + sOccasion} ); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent: " + currentParent} ); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentObject: " + currentObject} ); //$NON-NLS-1$
if ( currentObject != null ) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentObject.getNillableDescriptor(): " + currentObject.getNillableDescriptor()}); //$NON-NLS-1$
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] workingElements: " + currentObject.getChildren()}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentObject.getNillableDescriptor(): " + currentObject.getNillableDescriptor()}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] workingElements: " + currentObject.getChildren()}); //$NON-NLS-1$
}
if ( currentParent != null ) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent.getParent(): " + currentParent.getParent()}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent.getParent(): " + currentParent.getParent()}); //$NON-NLS-1$
} else {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent.getParent(): is NULL "}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"[showState] currentParent.getParent(): is NULL "}); //$NON-NLS-1$
}
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/WhileInstruction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/WhileInstruction.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/WhileInstruction.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,11 +28,11 @@
import java.util.Map;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.sql.symbol.ElementSymbol;
import com.metamatrix.query.sql.util.VariableContext;
@@ -72,7 +72,7 @@
setFirst(context.getVariableContext(), Boolean.TRUE);
}
else {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"WHILE removed finished result set:",resultSetName}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"WHILE removed finished result set:",resultSetName}); //$NON-NLS-1$
//increment the current program counter, so this
//While instruction will not be executed again
@@ -100,7 +100,7 @@
protected void pushProgram(XMLProcessorEnvironment env,
XMLContext context,
List row) throws MetaMatrixComponentException {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"WHILE repeating for result set:",resultSetName,", block program:", blockProgram}); //$NON-NLS-1$ //$NON-NLS-2$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"WHILE repeating for result set:",resultSetName,", block program:", blockProgram}); //$NON-NLS-1$ //$NON-NLS-2$
context.setVariableValues(resultSetName, row);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLPlan.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLPlan.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLPlan.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -43,6 +43,8 @@
import javax.xml.parsers.SAXParserFactory;
import org.teiid.client.plan.PlanNode;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
@@ -58,8 +60,6 @@
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.TupleBatch;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.XMLType;
import com.metamatrix.query.analysis.AnalysisRecord;
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLProcessorEnvironment.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLProcessorEnvironment.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLProcessorEnvironment.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,10 +28,11 @@
import java.util.LinkedList;
import java.util.Set;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.common.buffer.BufferManager;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.query.mapping.xml.ResultSetInfo;
import com.metamatrix.query.processor.ProcessorDataManager;
import com.metamatrix.query.processor.ProcessorPlan;
@@ -70,7 +71,7 @@
}
/**
- * @see ProcessorEnvironment#initialize(XMLPlan)
+ * @see ProcessorEnvironment#start()
*/
public void initialize(CommandContext context, ProcessorDataManager dataMgr, BufferManager bufferMgr) {
this.dataMgr = dataMgr;
@@ -134,8 +135,8 @@
while (this.programStack.size() > 1 &&
programState.programCounter >= programState.program.getProcessorInstructions().size()) {
this.programStack.removeFirst();
- if(LogManager.isMessageToBeRecorded(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, MessageLevel.TRACE)) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"Processor Environment popped program w/ recursion count " + programState.recursionCount, "; " + this.programStack.size(), " programs left."}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ if(LogManager.isMessageToBeRecorded(org.teiid.logging.LogConstants.CTX_XML_PLAN, MessageLevel.TRACE)) {
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"Processor Environment popped program w/ recursion count " + programState.recursionCount, "; " + this.programStack.size(), " programs left."}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
programState = this.programStack.getFirst();
}
@@ -159,10 +160,10 @@
} else {
programState.recursionCount = ProgramState.NOT_RECURSIVE + 1;
}
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"Pushed recursive program w/ recursion count " + programState.recursionCount}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"Pushed recursive program w/ recursion count " + programState.recursionCount}); //$NON-NLS-1$
} else {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_XML_PLAN, new Object[]{"Pushed non-recursive program w/ recursion count " + programState.recursionCount}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"Pushed non-recursive program w/ recursion count " + programState.recursionCount}); //$NON-NLS-1$
}
this.programStack.addFirst(programState);
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/resolver/QueryResolver.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/resolver/QueryResolver.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/resolver/QueryResolver.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,10 +29,11 @@
import java.util.List;
import java.util.Map;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.metadata.TempMetadataAdapter;
@@ -131,7 +132,7 @@
AnalysisRecord analysis, boolean resolveNullLiterals)
throws QueryResolverException, MetaMatrixComponentException {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving command", currentCommand}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving command", currentCommand}); //$NON-NLS-1$
TempMetadataAdapter resolverMetadata = null;
try {
Modified: trunk/engine/src/main/java/com/metamatrix/query/resolver/command/UpdateProcedureResolver.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/resolver/command/UpdateProcedureResolver.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/com/metamatrix/query/resolver/command/UpdateProcedureResolver.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,12 +30,13 @@
import java.util.List;
import java.util.Map;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.UnresolvedSymbolDescription;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.QueryPlugin;
import com.metamatrix.query.analysis.AnalysisRecord;
@@ -170,7 +171,7 @@
private void resolveBlock(CreateUpdateProcedureCommand command, Block block, GroupContext externalGroups,
TempMetadataAdapter metadata, boolean isUpdateProcedure, AnalysisRecord analysis)
throws QueryResolverException, QueryMetadataException, MetaMatrixComponentException {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving block", block}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving block", block}); //$NON-NLS-1$
//create a new variable and metadata context for this block so that discovered metadata is not visible else where
TempMetadataStore store = new TempMetadataStore(new HashMap(metadata.getMetadataStore().getData()));
@@ -188,7 +189,7 @@
private void resolveStatement(CreateUpdateProcedureCommand command, Statement statement, GroupContext externalGroups, GroupSymbol variables, TempMetadataAdapter metadata, boolean isUpdateProcedure, AnalysisRecord analysis)
throws QueryResolverException, QueryMetadataException, MetaMatrixComponentException {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving statement", statement}); //$NON-NLS-1$
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_QUERY_RESOLVER, new Object[]{"Resolving statement", statement}); //$NON-NLS-1$
switch(statement.getType()) {
case Statement.TYPE_IF:
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/cache/DQPContextCache.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/cache/DQPContextCache.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/cache/DQPContextCache.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,12 +23,13 @@
import java.io.Serializable;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.cache.Cache;
import com.metamatrix.cache.CacheConfiguration;
import com.metamatrix.cache.CacheFactory;
import com.metamatrix.cache.CacheConfiguration.Policy;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
public class DQPContextCache implements Serializable{
private static final long serialVersionUID = 6958846566556640186L;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/CapabilitiesConverter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/CapabilitiesConverter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/CapabilitiesConverter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,7 +25,7 @@
import java.util.Iterator;
import java.util.List;
-import org.teiid.connector.api.ConnectorCapabilities;
+import org.teiid.resource.cci.ConnectorCapabilities;
import com.metamatrix.query.optimizer.capabilities.BasicSourceCapabilities;
import com.metamatrix.query.optimizer.capabilities.SourceCapabilities;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,25 +34,24 @@
import javax.naming.InitialContext;
import javax.naming.NamingException;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.basic.WrappedConnection;
import org.teiid.connector.metadata.runtime.Datatype;
import org.teiid.connector.metadata.runtime.MetadataFactory;
import org.teiid.connector.metadata.runtime.MetadataStore;
import org.teiid.dqp.internal.cache.DQPContextCache;
import org.teiid.dqp.internal.datamgr.impl.ConnectorWorkItem.PermitMode;
import org.teiid.dqp.internal.process.AbstractWorkItem;
-import org.teiid.logging.api.CommandLogMessage;
-import org.teiid.logging.api.CommandLogMessage.Event;
+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.resource.ConnectorException;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ExecutionFactory;
+import org.teiid.resource.cci.MetadataProvider;
import com.metamatrix.common.buffer.BlockedException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.dqp.DQPPlugin;
import com.metamatrix.dqp.message.AtomicRequestID;
@@ -64,17 +63,15 @@
import com.metamatrix.query.sql.lang.Command;
/**
- * The <code>ConnectorManager</code> manages a {@link org.teiid.connector.basic.BasicConnector Connector}
+ * The <code>ConnectorManager</code> manages a {@link org.teiid.resource.adapter.BasicExecutionFactory Connector}
* and its associated workers' state.
*/
public class ConnectorManager {
public static final int DEFAULT_MAX_THREADS = 20;
- private String connectorName;
+ private String translatorName;
+ private String connectionName;
- // stateful connector supplied to the cm; does not do the lookup
- private Connector statefulConnector;
-
//services acquired in start
private BufferService bufferService;
@@ -84,29 +81,32 @@
private SourceCapabilities cachedCapabilities;
private int currentConnections;
- private int maxConnections;
+ private int maxConnections = DEFAULT_MAX_THREADS;
private LinkedList<ConnectorWorkItem> queuedRequests = new LinkedList<ConnectorWorkItem>();
private volatile boolean stopped;
- public ConnectorManager(String name) {
- this(name, DEFAULT_MAX_THREADS);
+
+ public ConnectorManager(String translatorName, String connectionName) {
+ this.translatorName = translatorName;
+ this.connectionName = connectionName;
}
-
- public ConnectorManager(String name, int maxThreads) {
- this(name, null, maxThreads);
- }
- public ConnectorManager(String name, Connector connector, int maxThreads) {
- if (name == null) {
- throw new IllegalArgumentException("Connector name can not be null"); //$NON-NLS-1$
+ public String getStausMessage() {
+ StringBuilder sb = new StringBuilder();
+ ExecutionFactory ef = getExecutionFactory();
+ if(ef != null) {
+ if (ef.isSourceRequired()) {
+ Object conn = getConnectionFactory();
+ if (conn == null) {
+ sb.append(DQPPlugin.Util.getString("datasource_not_found", this.connectionName)); //$NON-NLS-1$
+ }
+ }
}
- if (maxThreads <= 0) {
- maxThreads = DEFAULT_MAX_THREADS;
+ else {
+ sb.append(DQPPlugin.Util.getString("translator_not_found", this.translatorName)); //$NON-NLS-1$
}
- this.maxConnections = maxThreads;
- this.connectorName = name;
- this.statefulConnector = connector;
+ return sb.toString();
}
public synchronized void acquireConnectionLock(ConnectorWorkItem item) throws BlockedException {
@@ -123,25 +123,14 @@
throw BlockedException.INSTANCE;
}
}
+
- public String getName() {
- return this.connectorName;
- }
-
public MetadataStore getMetadata(String modelName, Map<String, Datatype> datatypes, Properties importProperties) throws ConnectorException {
-
MetadataFactory factory = new MetadataFactory(modelName, datatypes, importProperties);
-
- WrappedConnection conn = null;
- try {
- checkStatus();
- conn = (WrappedConnection)getConnector().getConnection();
- conn.getConnectorMetadata(factory);
- } finally {
- if (conn != null) {
- conn.close();
- }
- }
+ ExecutionFactory executionFactory = getExecutionFactory();
+ if (executionFactory instanceof MetadataProvider) {
+ ((MetadataProvider)executionFactory).getConnectorMetadata(factory, getConnectionFactory());
+ }
return factory.getMetadataStore();
}
@@ -149,31 +138,14 @@
if (cachedCapabilities != null) {
return cachedCapabilities;
}
- Connection conn = null;
- try {
- checkStatus();
- Connector connector = getConnector();
- ConnectorCapabilities caps = connector.getCapabilities();
- boolean global = true;
- if (caps == null) {
- conn = connector.getConnection();
- caps = conn.getCapabilities();
- global = false;
- }
-
- BasicSourceCapabilities resultCaps = CapabilitiesConverter.convertCapabilities(caps, getName(), connector.getConnectorEnvironment().isXaCapable());
- if (global) {
- resultCaps.setScope(Scope.SCOPE_GLOBAL);
- cachedCapabilities = resultCaps;
- } else {
- resultCaps.setScope(Scope.SCOPE_PER_USER);
- }
- return resultCaps;
- } finally {
- if ( conn != null ) {
- conn.close();
- }
- }
+
+ checkStatus();
+ ExecutionFactory connector = getExecutionFactory();
+ ConnectorCapabilities caps = connector.getCapabilities();
+ BasicSourceCapabilities resultCaps = CapabilitiesConverter.convertCapabilities(caps, this.translatorName, connector.isXaCapable());
+ resultCaps.setScope(Scope.SCOPE_GLOBAL);
+ cachedCapabilities = resultCaps;
+ return resultCaps;
}
public ConnectorWork executeRequest(AtomicRequestMessage message, AbstractWorkItem awi) throws ConnectorException {
@@ -223,7 +195,7 @@
* initialize this <code>ConnectorManager</code>.
*/
public void start() {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, DQPPlugin.Util.getString("ConnectorManagerImpl.Initializing_connector", connectorName)); //$NON-NLS-1$
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, DQPPlugin.Util.getString("ConnectorManagerImpl.Initializing_connector", translatorName)); //$NON-NLS-1$
}
/**
@@ -263,31 +235,43 @@
CommandLogMessage message = null;
if (cmdStatus == Event.NEW) {
- message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, connectorName, qr.getWorkContext().getSessionId(), principal, sqlStr, context);
+ message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, sqlStr, context);
}
else {
- message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, connectorName, qr.getWorkContext().getSessionId(), principal, finalRowCnt, cmdStatus, context);
+ message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), id.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, finalRowCnt, cmdStatus, context);
}
LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
}
/**
- * Get the <code>Connector</code> object managed by this
- * manager.
- * @return the <code>Connector</code>.
+ * Get the <code>Translator</code> object managed by this manager.
+ * @return the <code>ExecutionFactory</code>.
*/
- Connector getConnector() throws ConnectorException {
- try {
- if (this.statefulConnector != null) {
- return this.statefulConnector;
- }
- InitialContext ic = new InitialContext();
- return (Connector)ic.lookup(this.connectorName);
+ protected ExecutionFactory getExecutionFactory() {
+ try {
+ InitialContext ic = new InitialContext();
+ return (ExecutionFactory)ic.lookup(this.translatorName);
} catch (NamingException e) {
- throw new ConnectorException(e, DQPPlugin.Util.getString("ConnectorManager.failed_to_lookup_connector", this.connectorName)); //$NON-NLS-1$
- }
+ }
+ return null;
}
+ /**
+ * Get the ConnectionFactory object required by this manager
+ * @return
+ */
+ protected Object getConnectionFactory() {
+ if (this.connectionName != null) {
+ try {
+ InitialContext ic = new InitialContext();
+ return ic.lookup(this.connectionName);
+ } catch (NamingException e) {
+ }
+ }
+ return null;
+ }
+
+
DQPContextCache getContextCache() {
if (bufferService != null) {
return bufferService.getContextCache();
@@ -297,7 +281,19 @@
private void checkStatus() throws ConnectorException {
if (stopped) {
- throw new ConnectorException(DQPPlugin.Util.getString("ConnectorManager.not_in_valid_state", this.connectorName)); //$NON-NLS-1$
+ throw new ConnectorException(DQPPlugin.Util.getString("ConnectorManager.not_in_valid_state", this.translatorName)); //$NON-NLS-1$
}
}
+
+ public void setMaxConnections(int value) {
+ this.maxConnections = value;
+ }
+
+ public String getTranslatorName() {
+ return this.translatorName;
+ }
+
+ public String getConnectionName() {
+ return this.connectionName;
+ }
}
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWork.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWork.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWork.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,7 @@
package org.teiid.dqp.internal.datamgr.impl;
-import org.teiid.connector.api.ConnectorException;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.dqp.message.AtomicResultsMessage;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,28 +28,26 @@
import java.util.concurrent.atomic.AtomicBoolean;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.Execution;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
import org.teiid.connector.language.Call;
import org.teiid.connector.language.QueryExpression;
import org.teiid.connector.metadata.runtime.RuntimeMetadata;
import org.teiid.dqp.internal.datamgr.language.LanguageBridgeFactory;
import org.teiid.dqp.internal.datamgr.metadata.RuntimeMetadataImpl;
import org.teiid.dqp.internal.process.AbstractWorkItem;
-import org.teiid.logging.api.CommandLogMessage.Event;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.CommandLogMessage.Event;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.Execution;
+import org.teiid.resource.cci.ExecutionFactory;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.UpdateExecution;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.TupleBuffer;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.TransformationException;
import com.metamatrix.core.util.Assertion;
@@ -74,14 +72,13 @@
private AtomicRequestID id;
private ConnectorManager manager;
private AtomicRequestMessage requestMsg;
- private Connector connector;
+ private ExecutionFactory connector;
private QueryMetadataInterface queryMetadata;
private PermitMode permitMode = PermitMode.NOT_ACQUIRED;
private AbstractWorkItem awi;
/* Created on new request */
- private Connection connection;
- private ConnectorEnvironment connectorEnv;
+ private Object connection;
private ExecutionContextImpl securityContext;
private volatile ResultSetExecution execution;
private ProcedureBatchHandler procedureBatchHandler;
@@ -97,7 +94,7 @@
private AtomicBoolean isCancelled = new AtomicBoolean();
- ConnectorWorkItem(AtomicRequestMessage message, AbstractWorkItem awi, ConnectorManager manager) throws ConnectorException {
+ ConnectorWorkItem(AtomicRequestMessage message, AbstractWorkItem awi, ConnectorManager manager) {
this.id = message.getAtomicRequestID();
this.requestMsg = message;
this.manager = manager;
@@ -115,13 +112,12 @@
this.securityContext.setBatchSize(this.requestMsg.getFetchSize());
this.securityContext.setContextCache(manager.getContextCache());
- this.connector = manager.getConnector();
- this.connectorEnv = connector.getConnectorEnvironment();
+ this.connector = manager.getExecutionFactory();
VDBMetaData vdb = requestMsg.getWorkContext().getVDB();
this.queryMetadata = vdb.getAttachment(QueryMetadataInterface.class);
this.queryMetadata = new TempMetadataAdapter(this.queryMetadata, new TempMetadataStore());
- if (requestMsg.isTransactional() && this.connectorEnv.isXaCapable()) {
+ if (requestMsg.isTransactional() && this.connector.isXaCapable()) {
this.securityContext.setTransactional(true);
}
this.awi = awi;
@@ -188,16 +184,11 @@
LogManager.logError(LogConstants.CTX_CONNECTOR, e, e.getMessage());
} finally {
manager.removeState(this.id);
- if (connection != null) {
- try {
- connection.close();
- } catch (ConnectorException e) {
- LogManager.logWarning(LogConstants.CTX_CONNECTOR, e.getMessage());
- }
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed connection"}); //$NON-NLS-1$
- }
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Closed connection"}); //$NON-NLS-1$
}
}
+
+
private ConnectorException handleError(Throwable t) {
if (t instanceof DataNotAvailableException) {
@@ -237,7 +228,7 @@
LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.requestMsg.getAtomicRequestID(), "Processing NEW request:", this.requestMsg.getCommand()}); //$NON-NLS-1$
try {
- this.connection = this.connector.getConnection();
+ this.connection = this.manager.getConnectionFactory();
// Translate the command
Command command = this.requestMsg.getCommand();
@@ -258,7 +249,7 @@
RuntimeMetadata rmd = new RuntimeMetadataImpl(queryMetadata);
// Create the execution based on mode
- final Execution exec = connection.createExecution(this.translatedCommand, this.securityContext, rmd);
+ final Execution exec = connector.createExecution(this.translatedCommand, this.securityContext, rmd, this.connection);
if (this.translatedCommand instanceof Call) {
Assertion.isInstanceOf(this.execution, ProcedureExecution.class, "IProcedure Executions are expected to be ProcedureExecutions"); //$NON-NLS-1$
this.execution = (ProcedureExecution)exec;
@@ -338,13 +329,13 @@
correctTypes(row);
rows.add(row);
// Check for max result rows exceeded
- if(this.connectorEnv.getMaxResultRows() > -1 && this.rowCount >= this.connectorEnv.getMaxResultRows()){
- if (this.rowCount == this.connectorEnv.getMaxResultRows() && !this.connectorEnv.isExceptionOnMaxRows()) {
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Exceeded max, returning", this.connectorEnv.getMaxResultRows()}); //$NON-NLS-1$
+ if(this.connector.getMaxResultRows() > -1 && this.rowCount >= this.connector.getMaxResultRows()){
+ if (this.rowCount == this.connector.getMaxResultRows() && !this.connector.isExceptionOnMaxRows()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.id, "Exceeded max, returning", this.connector.getMaxResultRows()}); //$NON-NLS-1$
this.lastBatch = true;
break;
- } else if (this.rowCount > this.connectorEnv.getMaxResultRows() && this.connectorEnv.isExceptionOnMaxRows()) {
- String msg = DQPPlugin.Util.getString("ConnectorWorker.MaxResultRowsExceed", this.connectorEnv.getMaxResultRows()); //$NON-NLS-1$
+ } else if (this.rowCount > this.connector.getMaxResultRows() && this.connector.isExceptionOnMaxRows()) {
+ String msg = DQPPlugin.Util.getString("ConnectorWorker.MaxResultRowsExceed", this.connector.getMaxResultRows()); //$NON-NLS-1$
throw new ConnectorException(msg);
}
}
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ExecutionContextImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ExecutionContextImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ExecutionContextImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,10 +30,10 @@
import javax.security.auth.Subject;
-import org.teiid.connector.api.CacheScope;
-import org.teiid.connector.api.ExecutionContext;
import org.teiid.dqp.internal.cache.DQPContextCache;
import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.resource.cci.CacheScope;
+import org.teiid.resource.cci.ExecutionContext;
import com.metamatrix.cache.Cache;
import com.metamatrix.common.buffer.BufferManager;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ProcedureBatchHandler.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ProcedureBatchHandler.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ProcedureBatchHandler.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,11 +30,11 @@
import java.util.Collections;
import java.util.List;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ProcedureExecution;
import org.teiid.connector.language.Argument;
import org.teiid.connector.language.Call;
import org.teiid.connector.language.Argument.Direction;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ProcedureExecution;
import com.metamatrix.dqp.DQPPlugin;
@@ -45,7 +45,7 @@
private int resultSetCols = 0;
private List filler;
- public ProcedureBatchHandler(Call proc, ProcedureExecution procExec) throws ConnectorException {
+ public ProcedureBatchHandler(Call proc, ProcedureExecution procExec) {
this.proc = proc;
this.procExec = procExec;
List<Argument> params = proc.getArguments();
Added: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/TranslatorRepository.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/TranslatorRepository.java (rev 0)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/TranslatorRepository.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,60 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.datamgr.impl;
+
+import java.io.Serializable;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.teiid.resource.cci.ExecutionFactory;
+
+
+public class TranslatorRepository implements Serializable{
+
+ private static final long serialVersionUID = -1212280886010974273L;
+ private Map<String, ExecutionFactory> translatorRepo = new ConcurrentHashMap<String, ExecutionFactory>();
+
+ public void addTranslator(String name, ExecutionFactory t) {
+// try {
+// InitialContext ic = new InitialContext();
+// ic.bind(name, t);
+// } catch (NamingException e) {
+// LogManager.logError(LogConstants.CTX_RUNTIME, DQPPlugin.Util.getString("failed_to_bind_translator", name)); //$NON-NLS-1$
+// }
+ this.translatorRepo.put(name, t);
+ }
+
+ public ExecutionFactory getTranslator(String name) {
+ return this.translatorRepo.get(name);
+ }
+
+ public ExecutionFactory removeTranslator(String name) {
+// try {
+// InitialContext ic = new InitialContext();
+// ic.unbind(name);
+// } catch (NamingException e) {
+// LogManager.logError(LogConstants.CTX_RUNTIME, DQPPlugin.Util.getString("failed_to_unbind_translator", name)); //$NON-NLS-1$
+// }
+ return this.translatorRepo.remove(name);
+ }
+}
\ No newline at end of file
Property changes on: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/TranslatorRepository.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/language/LanguageBridgeFactory.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/language/LanguageBridgeFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/language/LanguageBridgeFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,7 +27,6 @@
import java.util.List;
import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.language.AggregateFunction;
import org.teiid.connector.language.AndOr;
import org.teiid.connector.language.Argument;
@@ -62,6 +61,7 @@
import org.teiid.connector.metadata.runtime.Procedure;
import org.teiid.connector.metadata.runtime.ProcedureParameter;
import org.teiid.dqp.internal.datamgr.metadata.RuntimeMetadataImpl;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/metadata/RuntimeMetadataImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/metadata/RuntimeMetadataImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/metadata/RuntimeMetadataImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,8 +24,8 @@
*/
package org.teiid.dqp.internal.datamgr.metadata;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.metadata.runtime.*;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,9 +26,10 @@
import javax.resource.spi.work.WorkEvent;
import javax.resource.spi.work.WorkListener;
-import com.metamatrix.common.log.LogManager;
+import org.teiid.logging.LogManager;
+
/**
* Represents a task that performs work that may take more than one processing pass to complete.
* During processing the WorkItem may receive events asynchronously through the moreWork method.
@@ -118,12 +119,12 @@
if (!ignoreDone) {
throw new IllegalStateException("More work is not valid once DONE"); //$NON-NLS-1$
}
- LogManager.logDetail(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[] {this, "ignoring more work, since the work item is done"}); //$NON-NLS-1$
+ LogManager.logDetail(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, "ignoring more work, since the work item is done"}); //$NON-NLS-1$
}
}
private void logTrace(String msg) {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[] {this, msg, this.threadState});
+ LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, new Object[] {this, msg, this.threadState});
}
protected abstract void process();
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/CachedFinder.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,9 +27,9 @@
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.core.CoreConstants;
@@ -72,9 +72,9 @@
ModelMetaData model = vdb.getModel(modelName);
for (String sourceName:model.getSourceNames()) {
try {
- ConnectorManager mgr = this.connectorRepo.getConnectorManager(model.getSourceJndiName(sourceName));
+ ConnectorManager mgr = this.connectorRepo.getConnectorManager(sourceName);
if (mgr == null) {
- throw new ConnectorException(DQPPlugin.Util.getString("CachedFinder.no_connector_found", model.getSourceJndiName(sourceName), modelName, sourceName)); //$NON-NLS-1$
+ throw new ConnectorException(DQPPlugin.Util.getString("CachedFinder.no_connector_found", sourceName, modelName, sourceName)); //$NON-NLS-1$
}
caps = mgr.getCapabilities();
break;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/CodeTableCache.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/CodeTableCache.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/CodeTableCache.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,9 +29,10 @@
import java.util.Map;
import java.util.Set;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.util.HashCodeUtil;
import com.metamatrix.dqp.DQPPlugin;
import com.metamatrix.query.util.CommandContext;
@@ -234,7 +235,7 @@
// Clear the cacheKeyDone
this.rowCount = 0;
// Log status
- LogManager.logInfo(com.metamatrix.common.log.LogConstants.CTX_DQP, DQPPlugin.Util.getString("CodeTableCache.Cleared_code_tables", removedTables, removedRecords)); //$NON-NLS-1$
+ LogManager.logInfo(org.teiid.logging.LogConstants.CTX_DQP, DQPPlugin.Util.getString("CodeTableCache.Cleared_code_tables", removedTables, removedRecords)); //$NON-NLS-1$
}
/**
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -57,15 +57,15 @@
import org.teiid.client.xa.XidImpl;
import org.teiid.dqp.internal.cache.DQPContextCache;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
-import org.teiid.logging.api.CommandLogMessage;
-import org.teiid.logging.api.CommandLogMessage.Event;
+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 com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BufferManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.types.Streamable;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.Assertion;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,7 +34,6 @@
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.client.RequestMessage;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.language.SQLReservedWords;
import org.teiid.connector.metadata.runtime.AbstractMetadataRecord;
import org.teiid.connector.metadata.runtime.Column;
@@ -51,6 +50,7 @@
import org.teiid.dqp.internal.process.CodeTableCache.CacheKey;
import org.teiid.metadata.CompositeMetadataStore;
import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -339,7 +339,7 @@
// this should not happen, but it did occur when setting up the SystemAdmin models
throw new MetaMatrixComponentException(DQPPlugin.Util.getString("DataTierManager.could_not_obtain_connector_binding", new Object[]{modelName, workItem.getDqpWorkContext().getVdbName(), workItem.getDqpWorkContext().getVdbVersion() })); //$NON-NLS-1$
}
- connectorBindingId = model.getSourceJndiName(bindings.get(0));
+ connectorBindingId = bindings.get(0);
Assertion.isNotNull(connectorBindingId, "could not obtain connector id"); //$NON-NLS-1$
}
aqr.setConnectorName(connectorBindingId);
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,8 +26,8 @@
import java.util.List;
import org.teiid.client.SourceWarning;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.dqp.internal.datamgr.impl.ConnectorWork;
+import org.teiid.resource.ConnectorException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,9 +30,9 @@
import org.teiid.client.lob.LobChunk;
import org.teiid.client.util.ResultsReceiver;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.BlobType;
import com.metamatrix.common.types.ClobType;
import com.metamatrix.common.types.Streamable;
@@ -75,7 +75,7 @@
chunk = stream.getNextChunk();
shouldClose = chunk.isLast();
} catch (MetaMatrixComponentException e) {
- LogManager.logWarning(com.metamatrix.common.log.LogConstants.CTX_DQP, e, DQPPlugin.Util.getString("ProcessWorker.LobError")); //$NON-NLS-1$
+ LogManager.logWarning(org.teiid.logging.LogConstants.CTX_DQP, e, DQPPlugin.Util.getString("ProcessWorker.LobError")); //$NON-NLS-1$
ex = e;
} catch (IOException e) {
ex = e;
@@ -102,7 +102,7 @@
stream.close();
}
} catch (IOException e) {
- LogManager.logWarning(com.metamatrix.common.log.LogConstants.CTX_DQP, e, DQPPlugin.Util.getString("ProcessWorker.LobError")); //$NON-NLS-1$
+ LogManager.logWarning(org.teiid.logging.LogConstants.CTX_DQP, e, DQPPlugin.Util.getString("ProcessWorker.LobError")); //$NON-NLS-1$
}
parent.removeLobStream(streamRequestId);
}
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,6 +28,8 @@
import java.util.List;
import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -36,7 +38,6 @@
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.QueryValidatorException;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.QueryPlugin;
import com.metamatrix.query.eval.Evaluator;
@@ -133,7 +134,7 @@
if (prepPlan == null) {
//if prepared plan does not exist, create one
prepPlan = new PreparedPlan();
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
+ LogManager.logTrace(LogConstants.CTX_DQP, new Object[] { "Query does not exist in cache: ", sqlQuery}); //$NON-NLS-1$
}
ProcessorPlan cachedPlan = prepPlan.getPlan();
@@ -148,7 +149,7 @@
this.prepPlanCache.put(id, this.context.isSessionFunctionEvaluated(), prepPlan);
}
} else {
- LogManager.logTrace(com.metamatrix.common.log.LogConstants.CTX_DQP, new Object[] { "Query exist in cache: ", sqlQuery }); //$NON-NLS-1$
+ 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();
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -37,6 +37,9 @@
import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
import org.teiid.dqp.internal.process.multisource.MultiSourcePlanToProcessConverter;
import org.teiid.dqp.internal.process.validator.AuthorizationValidationVisitor;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
@@ -46,9 +49,6 @@
import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.buffer.BufferManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.core.id.IntegerIDFactory;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -38,9 +38,12 @@
import org.teiid.client.metadata.ParameterInfo;
import org.teiid.client.util.ResultsReceiver;
import org.teiid.client.xa.XATransactionException;
-import org.teiid.connector.api.DataNotAvailableException;
import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
-import org.teiid.logging.api.CommandLogMessage.Event;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.logging.CommandLogMessage.Event;
+import org.teiid.resource.cci.DataNotAvailableException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixException;
@@ -48,9 +51,6 @@
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.TupleBatch;
import com.metamatrix.common.buffer.TupleBuffer;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.MetaMatrixCoreException;
import com.metamatrix.dqp.DQPPlugin;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/StatsCapturingWorkManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/StatsCapturingWorkManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/StatsCapturingWorkManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -43,10 +43,10 @@
import javax.resource.spi.work.WorkRejectedException;
import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.util.NamedThreadFactory;
import com.metamatrix.query.QueryPlugin;
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -94,7 +94,7 @@
// Create a new cloned version of the access node and set it's model name to be the bindingUUID
AccessNode instanceNode = (AccessNode) accessNode.clone();
instanceNode.setID(getID());
- instanceNode.setConnectorBindingId(model.getSourceJndiName(sourceName));
+ instanceNode.setConnectorBindingId(sourceName);
// Modify the command to pull the instance column and evaluate the criteria
Command command = (Command)instanceNode.getCommand().clone();
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/validator/AuthorizationValidationVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -39,14 +39,14 @@
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.dqp.internal.process.DQPWorkContext;
import org.teiid.dqp.internal.process.multisource.MultiSourceElement;
-import org.teiid.logging.api.AuditMessage;
+import org.teiid.logging.AuditMessage;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.dqp.DQPPlugin;
import com.metamatrix.query.function.FunctionLibrary;
import com.metamatrix.query.metadata.TempMetadataID;
Modified: trunk/engine/src/main/resources/com/metamatrix/dqp/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/com/metamatrix/dqp/i18n.properties 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/main/resources/com/metamatrix/dqp/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -515,4 +515,10 @@
TransformationMetadata.Unable_to_determine_fullname_for_element__1=Unable to determine fullname for element
CachedRequestWorkItem.not_available=Cache result is no longer available.
-CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2}
\ No newline at end of file
+CachedFinder.no_connector_found=No connector with jndi-name {0} found for Model {1} with source name {2}
+failed_to_get_connection= Failed to get connection for translator {0}
+failed_to_close_connection=Failed to close the connection for translator {0}
+translator_not_found=Translator {0} not accessible.
+datasource_not_found=Data Source {0} not accessible.
+failed_to_bind_translator=Failed to bind the translator {0} on the jndi tree
+failed_to_unbind_translator=Failed to un-bind the translator {0} from the jndi tree.
\ No newline at end of file
Deleted: trunk/engine/src/test/java/com/metamatrix/common/log/TestLogManager.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/common/log/TestLogManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/common/log/TestLogManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,161 +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 com.metamatrix.common.log;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-
-/**
- * This test case tests the LogManager.
- */
-public class TestLogManager extends TestCase {
-
- String context = "SomeContext"; //$NON-NLS-1$
-
- /**
- * Constructor for TestLogManager.
- * @param name
- */
- public TestLogManager(String name) {
- super(name);
- }
-
- @Override
- protected void setUp() throws Exception {
- ListLogger logger = new ListLogger();
- logger.setLogLevel(context, MessageLevel.DETAIL);
- LogManager.logListener = logger;
- }
-
- // =========================================================================
- // T E S T C A S E S
- // =========================================================================
-
- /*
- * Test for boolean isMessageToBeRecorded(String, int)
- */
- public void testIsMessageToBeRecordedString() {
- assertTrue(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
-
- ListLogger cfg = (ListLogger)LogManager.logListener;
- cfg.setLogLevel(context, MessageLevel.NONE);
- assertFalse(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
- }
-
- /**
- * Test that all msgs logged are equal and output in same order.
- */
- public void testLogMessage() throws Exception {
- ListLogger cfg = (ListLogger)LogManager.logListener;
- cfg.setLogLevel(context, MessageLevel.INFO );
-
- List<String> sentMsgList = new ArrayList<String>();
- sentMsgList.add("A message 1"); //$NON-NLS-1$
- sentMsgList.add("A message 2"); //$NON-NLS-1$
- sentMsgList.add("A message 3"); //$NON-NLS-1$
- sentMsgList.add("A message 4"); //$NON-NLS-1$
- sentMsgList.add("A message 5"); //$NON-NLS-1$
- sentMsgList.add("A message 6"); //$NON-NLS-1$
-
- for (Iterator iter = sentMsgList.iterator(); iter.hasNext();) {
- String msg = (String) iter.next();
- LogManager.logInfo(context, msg);
- }
-
- List recevedMsgList = cfg.getLoggedMessages();
- assertEquals(sentMsgList.size(), recevedMsgList.size());
- assertEquals(sentMsgList, recevedMsgList);
- }
-
- /**
- *
- * A log listener that saves messages (IStatus)s in a
- * List for later comparison.
- */
- class ListLogger implements LogListener {
- private List<String> messages = new ArrayList<String>();
- private Map<String, Integer> contextMap = new HashMap<String, Integer>();
- private int defaultLevel;
-
- public ListLogger() {
- }
-
- /* (non-Javadoc)
- * @see com.metamatrix.core.log.LogListener#logMessage(org.eclipse.core.runtime.IStatus, long, java.lang.String, java.lang.String)
- */
- public void log(int level, String context, Object msg){
- this.messages.add(msg.toString());
- }
-
- public void log(int level, String context, Throwable t, Object msg) {
- this.messages.add(msg.toString());
- }
-
- /* (non-Javadoc)
- * @see com.metamatrix.core.log.LogListener#shutdown()
- */
- public void shutdown() {
- messages.clear();
- messages = null;
-
- }
-
- public int size() {
- return this.messages.size();
- }
-
- public List getLoggedMessages() {
- return this.messages;
- }
-
- public Set<String> getContexts() {
- return this.contextMap.keySet();
- }
-
- public int getLogLevel(String context) {
- Integer level = this.contextMap.get(context);
- if (level != null) {
- return level;
- }
- return defaultLevel;
- }
-
- public void setLogLevel(String context, int logLevel) {
- this.contextMap.put(context, logLevel);
- }
-
- @Override
- public boolean isEnabled(String context, int msgLevel) {
- int level = getLogLevel(context);
- return level >= msgLevel;
- }
- }
-
-}
Modified: trunk/engine/src/test/java/com/metamatrix/dqp/service/AutoGenDataService.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/dqp/service/AutoGenDataService.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/dqp/service/AutoGenDataService.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,12 +28,12 @@
import java.util.Iterator;
import java.util.List;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
import org.teiid.dqp.internal.datamgr.impl.ConnectorWork;
import org.teiid.dqp.internal.datamgr.impl.ConnectorWorkItem;
import org.teiid.dqp.internal.process.AbstractWorkItem;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.dqp.message.AtomicRequestMessage;
@@ -55,7 +55,7 @@
public int dataNotAvailable = -1;
public AutoGenDataService() {
- super("FakeConnector");
+ super("FakeConnector","FakeConnector"); //$NON-NLS-1$ //$NON-NLS-2$
caps = new BasicSourceCapabilities();
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionTree.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionTree.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionTree.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,8 +31,8 @@
import junit.framework.TestCase;
import org.mockito.Mockito;
+import org.teiid.logging.LogManager;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.query.function.metadata.FunctionCategoryConstants;
import com.metamatrix.query.function.metadata.FunctionMethod;
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinOptimization.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinOptimization.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinOptimization.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,7 +28,7 @@
import java.util.List;
import org.junit.Test;
-import org.teiid.connector.api.SourceSystemFunctions;
+import org.teiid.resource.cci.SourceSystemFunctions;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.QueryMetadataException;
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinPushdownRestrictions.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinPushdownRestrictions.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinPushdownRestrictions.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,7 +23,7 @@
package com.metamatrix.query.optimizer;
import org.junit.Test;
-import org.teiid.connector.api.ConnectorCapabilities.SupportedJoinCriteria;
+import org.teiid.resource.cci.ConnectorCapabilities.SupportedJoinCriteria;
import com.metamatrix.query.optimizer.capabilities.BasicSourceCapabilities;
import com.metamatrix.query.optimizer.capabilities.FakeCapabilitiesFinder;
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestSubqueryPushdown.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestSubqueryPushdown.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestSubqueryPushdown.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,7 +25,7 @@
import static com.metamatrix.query.optimizer.TestOptimizer.*;
import org.junit.Test;
-import org.teiid.connector.api.SourceSystemFunctions;
+import org.teiid.resource.cci.SourceSystemFunctions;
import com.metamatrix.query.optimizer.capabilities.BasicSourceCapabilities;
import com.metamatrix.query.optimizer.capabilities.FakeCapabilitiesFinder;
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/FakeDataManager.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/FakeDataManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/FakeDataManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,12 +29,13 @@
import java.util.List;
import java.util.Map;
+import org.teiid.logging.LogManager;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.CriteriaEvaluationException;
import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.TupleSource;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.query.eval.Evaluator;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.metadata.TempMetadataID;
Modified: trunk/engine/src/test/java/com/metamatrix/query/sql/visitor/TestExpressionMappingVisitor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/sql/visitor/TestExpressionMappingVisitor.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/sql/visitor/TestExpressionMappingVisitor.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,8 +31,8 @@
import java.util.Map;
import org.junit.Test;
-import org.teiid.connector.api.SourceSystemFunctions;
import org.teiid.connector.language.SQLReservedWords;
+import org.teiid.resource.cci.SourceSystemFunctions;
import com.metamatrix.query.sql.LanguageObject;
import com.metamatrix.query.sql.lang.CompareCriteria;
Modified: trunk/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/com/metamatrix/query/unittest/FakeMetadataFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -162,7 +162,7 @@
}
model.setVisible(true);
model.setSupportsMultiSourceBindings(false);
- model.addSourceMapping(name, null);
+ model.addSourceMapping(name, name, null);
return model;
}
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeConnector.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -27,25 +27,21 @@
import junit.framework.Assert;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.Execution;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.basic.BasicConnector;
-import org.teiid.connector.basic.BasicConnectorCapabilities;
-import org.teiid.connector.basic.BasicExecution;
import org.teiid.connector.language.Command;
import org.teiid.connector.language.QueryExpression;
import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.Execution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.UpdateExecution;
-
-public class FakeConnector extends BasicConnector {
+public class FakeConnector extends BasicExecutionFactory {
private static final int RESULT_SIZE = 5;
private boolean executeBlocks;
@@ -58,8 +54,6 @@
private int connectionCount;
private int executionCount;
- private ConnectorEnvironment env;
-
public int getConnectionCount() {
return connectionCount;
}
@@ -68,33 +62,25 @@
return executionCount;
}
- public ConnectorEnvironment getConnectorEnvironment() {
- return this.env;
+ @Override
+ public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ executionCount++;
+ return new FakeBlockingExecution(executionContext);
}
+ public ConnectorCapabilities getCapabilities() {
+ return new BasicConnectorCapabilities();
+ }
- public void setConnectorEnvironment(ConnectorEnvironment env) {
- this.env = env;
- }
-
- @Override
- public Connection getConnection() throws ConnectorException {
+ public Object getConnection() {
return new FakeConnection();
}
- private class FakeConnection extends BasicConnection {
-
+ private class FakeConnection {
public FakeConnection() {
connectionCount++;
}
public boolean released = false;
- public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata) throws ConnectorException {
- executionCount++;
- return new FakeBlockingExecution(executionContext);
- }
- public ConnectorCapabilities getCapabilities() {
- return new BasicConnectorCapabilities();
- }
public void close() {
Assert.assertFalse("The connection should not be released more than once", released); //$NON-NLS-1$
released = true;
@@ -192,9 +178,4 @@
public void setClassloader(ClassLoader classloader) {
this.classloader = classloader;
}
-
- @Override
- public ConnectorCapabilities getCapabilities() {
- return null;
- }
}
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeExecutionContextImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeExecutionContextImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeExecutionContextImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,7 +24,7 @@
import java.util.concurrent.atomic.AtomicInteger;
-import org.teiid.connector.api.ExecutionContext;
+import org.teiid.resource.cci.ExecutionContext;
/**
*/
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeProcedureExecution.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeProcedureExecution.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/FakeProcedureExecution.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,10 +26,10 @@
import java.util.Arrays;
import java.util.List;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.basic.BasicExecution;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicExecution;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.ProcedureExecution;
final class FakeProcedureExecution extends BasicExecution implements ProcedureExecution {
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManager.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManager.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManager.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,9 +29,8 @@
import junit.framework.TestCase;
import org.mockito.Mockito;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorEnvironment;
import org.teiid.dqp.internal.process.AbstractWorkItem;
+import org.teiid.resource.cci.ExecutionFactory;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.dqp.message.AtomicRequestID;
@@ -45,14 +44,17 @@
private AtomicRequestMessage request;
private ConnectorManager csm;
- static ConnectorManager getConnectorManager(ConnectorEnvironment env) throws Exception {
+ static ConnectorManager getConnectorManager() throws Exception {
final FakeConnector c = new FakeConnector();
- c.setConnectorEnvironment(env);
- ConnectorManager cm = new ConnectorManager("FakeConnector", 1) { //$NON-NLS-1$
- Connector getConnector() {
+ ConnectorManager cm = new ConnectorManager("FakeConnector","FakeConnector") { //$NON-NLS-1$ //$NON-NLS-2$
+ protected ExecutionFactory getExecutionFactory() {
return c;
}
+ protected Object getConnectionFactory(){
+ return c.getConnection();
+ }
};
+ cm.setMaxConnections(1);
cm.start();
return cm;
}
@@ -68,7 +70,7 @@
protected void setUp() throws Exception {
super.setUp();
request = TestConnectorWorkItem.createNewAtomicRequestMessage(1, 1);
- csm = getConnectorManager(Mockito.mock(ConnectorEnvironment.class));
+ csm = getConnectorManager();
}
void helpAssureOneState() throws Exception {
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorWorkItem.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,7 +22,8 @@
package org.teiid.dqp.internal.datamgr.impl;
-import static junit.framework.Assert.*;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.fail;
import java.util.Arrays;
import java.util.List;
@@ -33,13 +34,12 @@
import org.junit.Test;
import org.mockito.Mockito;
import org.teiid.client.RequestMessage;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ProcedureExecution;
import org.teiid.connector.language.Call;
import org.teiid.dqp.internal.datamgr.language.LanguageBridgeFactory;
import org.teiid.dqp.internal.process.AbstractWorkItem;
import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ProcedureExecution;
import com.metamatrix.dqp.message.AtomicRequestMessage;
import com.metamatrix.dqp.message.AtomicResultsMessage;
@@ -118,7 +118,7 @@
AtomicRequestMessage arm = createNewAtomicRequestMessage(1, 1);
arm.setCommand(command);
ConnectorWorkItem synchConnectorWorkItem = new ConnectorWorkItem(arm, Mockito.mock(AbstractWorkItem.class),
- TestConnectorManager.getConnectorManager(Mockito.mock(ConnectorEnvironment.class)));
+ TestConnectorManager.getConnectorManager());
return synchConnectorWorkItem.execute();
}
@@ -136,9 +136,9 @@
* 3. command must NOT be a SELECT
* 4. Then, set isImmutable to TRUE, we should SUCCEED
*/
- ConnectorEnvironment env = Mockito.mock(ConnectorEnvironment.class);
- Mockito.stub(env.isImmutable()).toReturn(true);
- ConnectorManager cm = TestConnectorManager.getConnectorManager(env);
+ ConnectorManager cm = TestConnectorManager.getConnectorManager();
+ ((FakeConnector)cm.getExecutionFactory()).setImmutable(true);
+
// command must not be a SELECT
Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
@@ -164,9 +164,9 @@
* 3. command must NOT be a SELECT
* 4. Then, set isImmutable to FALSE, and we should FAIL
*/
- ConnectorEnvironment env = Mockito.mock(ConnectorEnvironment.class);
- Mockito.stub(env.isImmutable()).toReturn(false);
- ConnectorManager cm = TestConnectorManager.getConnectorManager(env);
+ ConnectorManager cm = TestConnectorManager.getConnectorManager();
+ ((FakeConnector)cm.getExecutionFactory()).setImmutable(false);
+
// command must not be a SELECT
Command command = helpGetCommand("update bqt1.smalla set stringkey = 1 where stringkey = 2", EXAMPLE_BQT); //$NON-NLS-1$
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestTypeFacilityImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestTypeFacilityImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestTypeFacilityImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,7 +24,7 @@
import java.sql.Clob;
-import org.teiid.connector.basic.TypeFacilityImpl;
+import org.teiid.resource.cci.TypeFacilityImpl;
import junit.framework.TestCase;
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -101,7 +101,7 @@
ModelMetaData m = vdb.getModel(model);
int x = m.getSourceNames().size();
for(int i=x; i<sourceCount; i++, sourceID++) {
- m.addSourceMapping("" + sourceID, null);
+ m.addSourceMapping("" + sourceID, "translator", null); //$NON-NLS-1$ //$NON-NLS-2$
}
}
Modified: trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,9 +22,6 @@
package org.teiid.adminapi.jboss;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
@@ -37,8 +34,6 @@
import java.util.Map;
import java.util.Properties;
import java.util.Set;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
import org.jboss.deployers.spi.management.ManagementView;
import org.jboss.deployers.spi.management.deploy.DeploymentManager;
@@ -62,43 +57,32 @@
import org.teiid.adminapi.AdminException;
import org.teiid.adminapi.AdminObject;
import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.ConnectionFactory;
-import org.teiid.adminapi.Model;
import org.teiid.adminapi.PropertyDefinition;
import org.teiid.adminapi.Request;
import org.teiid.adminapi.Session;
import org.teiid.adminapi.TeiidAdmin;
import org.teiid.adminapi.Transaction;
+import org.teiid.adminapi.Translator;
import org.teiid.adminapi.VDB;
import org.teiid.adminapi.WorkerPoolStatistics;
-import org.teiid.adminapi.impl.ConnectionFactoryMetaData;
-import org.teiid.adminapi.impl.DataPolicyMetadata;
-import org.teiid.adminapi.impl.ModelMetaData;
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.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
import org.teiid.jboss.IntegrationPlugin;
import org.teiid.jboss.deployers.RuntimeEngineDeployer;
public class Admin extends TeiidAdmin {
- private static final String CONNECTOR_PREFIX = "connector-"; //$NON-NLS-1$
- private static final String RAR = ".rar"; //$NON-NLS-1$
+ private static final String TRANSLATOR_PREFIX = "translator-"; //$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 ComponentType CONNECTION_FACTORY_TYPE = new ComponentType("teiid", "connection-factory");//$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.class.getName();
- private static ComponentType NOTXTYPE = new ComponentType("ConnectionFactory", "NoTx");//$NON-NLS-1$ //$NON-NLS-2$
- private static ComponentType TXTYPE = new ComponentType("ConnectionFactory", "Tx");//$NON-NLS-1$ //$NON-NLS-2$
- private static ComponentType DS_LOCAL_TX = new ComponentType("DataSource", "LocalTx");//$NON-NLS-1$ //$NON-NLS-2$
- private static ComponentType DS_XA_TX = new ComponentType("DataSource", "XA");//$NON-NLS-1$ //$NON-NLS-2$
- private static ComponentType DS_NO_TX = new ComponentType("DataSource", "NoTx");//$NON-NLS-1$ //$NON-NLS-2$
- private static ComponentType[] DS_TYPES = {DS_XA_TX,DS_LOCAL_TX,TXTYPE,DS_NO_TX,NOTXTYPE};
+ private static ComponentType TRANSLATOR_TYPE = new ComponentType("teiid", "translator");//$NON-NLS-1$ //$NON-NLS-2$
private ManagementView view;
@@ -158,12 +142,12 @@
// }
@Override
- public Collection<ConnectionFactory> getConnectionFactories() throws AdminException {
- ArrayList<ConnectionFactory> factories = new ArrayList<ConnectionFactory>();
+ public Collection<Translator> getTranslators() throws AdminException {
+ ArrayList<Translator> factories = new ArrayList<Translator>();
try {
- Set<ManagedComponent> mcSet = getView().getComponentsForType(CONNECTION_FACTORY_TYPE);
+ Set<ManagedComponent> mcSet = getView().getComponentsForType(TRANSLATOR_TYPE);
for (ManagedComponent mc:mcSet) {
- factories.add(AdminObjectBuilder.buildAO(mc, ConnectionFactoryMetaData.class));
+ factories.add(AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class));
}
} catch (Exception e) {
throw new AdminComponentException(e);
@@ -172,11 +156,11 @@
}
@Override
- public ConnectionFactory getConnectionFactory(String deployedName) throws AdminException {
+ public Translator getTranslator(String deployedName) throws AdminException {
try {
- ManagedComponent mc = getConnectionFactoryComponent(deployedName);
+ ManagedComponent mc = getView().getComponent(deployedName, TRANSLATOR_TYPE);
if (mc != null) {
- return AdminObjectBuilder.buildAO(mc, ConnectionFactoryMetaData.class);
+ return AdminObjectBuilder.buildAO(mc, TranslatorMetaData.class);
}
return null;
} catch(Exception e) {
@@ -184,19 +168,6 @@
}
}
- private ManagedComponent getConnectionFactoryComponent(String deployedName)
- throws Exception {
- if (deployedName.startsWith("java:")) { //$NON-NLS-1$
- deployedName = deployedName.substring(5);
- }
-
- if (!deployedName.startsWith("teiid-cf/")) { //$NON-NLS-1$
- deployedName = "teiid-cf/"+deployedName; //$NON-NLS-1$
- }
- ManagedComponent mc = view.getComponent(deployedName, CONNECTION_FACTORY_TYPE);
- return mc;
- }
-
private InputStream exportDeployment(String url) throws AdminComponentException {
try {
URL contentURL = new URL(url);
@@ -208,90 +179,59 @@
}
}
- private ManagedComponent getManagedConnectionFactoryComponent(String deployedName) throws AdminProcessingException {
+ @Override
+ public Translator addTranslator(String deploymentName, String typeName, Properties properties) throws AdminException {
try {
- if (deployedName.startsWith("java:")) { //$NON-NLS-1$
- deployedName = deployedName.substring(5);
+ ManagedComponent mc = getView().getComponent(deploymentName, TRANSLATOR_TYPE);
+ if (mc != null) {
+ throw new AdminProcessingException(IntegrationPlugin.Util.getString("translator_exists",deploymentName)); //$NON-NLS-1$;
}
- for (ComponentType type:DS_TYPES) {
- ManagedComponent mc = view.getComponent(deployedName, type);
- if (mc != null) {
- return mc;
+
+ DeploymentTemplateInfo info = getView().getTemplate(typeName);
+ if(info == null) {
+ throw new AdminProcessingException(IntegrationPlugin.Util.getString("translator_template_not_found", typeName)); //$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));
+ }
}
}
+ getView().applyTemplate(deploymentName, info);
+ } catch (NoSuchDeploymentException e) {
+ throw new AdminComponentException(e.getMessage(), e);
} catch(Exception e) {
- throw new AdminProcessingException(e.getMessage(), e);
- }
- return null;
- }
-
-// private ConnectionFactory buildConnectionFactory(ManagedComponent mc) {
-//
-// ConnectionFactoryMetaData connector = new ConnectionFactoryMetaData();
-// connector.setName(mc.getName());
-// connector.setComponentType(mc.getType());
-// connector.setJNDIName(ManagedUtil.getSimpleValue(mc, "jndi-name", String.class)); //$NON-NLS-1$
-// connector.setRARFileName(ManagedUtil.getSimpleValue(mc, "rar-name", String.class)); //$NON-NLS-1$
-//
-// connector.addProperty("deployer-name", mc.getDeployment().getName());//$NON-NLS-1$
-//
-// for (String key:mc.getProperties().keySet()) {
-// ManagedProperty property = mc.getProperty(key);
-// MetaValue value = property.getValue();
-//
-// //TODO: All properties need to be added
-// if (value != null) {
-// if(value.getMetaType().isSimple()) {
-// connector.addProperty(key, ManagedUtil.stringValue(value));
-// }
-// else if (key.equals("config-property")) { //$NON-NLS-1$
-// MapCompositeValueSupport v1 = (MapCompositeValueSupport)value;
-// MapCompositeMetaType metaType = v1.getMetaType();
-// for (String configProperty:metaType.keySet()) {
-// if (!configProperty.endsWith(".type")) { //$NON-NLS-1$
-// connector.addProperty(configProperty, ManagedUtil.stringValue(v1.get(configProperty)));
-// }
-// }
-// }
-// else {
-// //log.info(key+" property is not added to connector properties");
-// }
-// }
-// }
-// return connector;
-// }
-
-
-
- @Override
- public ConnectionFactory addConnectionFactory(String deploymentName, String typeName, Properties properties) throws AdminException {
- if (getManagedConnectionFactoryComponent(deploymentName) != null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("connector_binding_exists",deploymentName)); //$NON-NLS-1$;
- }
- addConnectionfactory(deploymentName, typeName, properties);
- return getConnectionFactory(deploymentName);
+ throw new AdminComponentException(e.getMessage(), e);
+ }
+ return getTranslator(deploymentName);
}
@Override
- public void setConnectionFactoryProperty(String deployedName, String propertyName, String propertyValue) throws AdminException{
+ public void setTranslatorProperty(String deployedName, String propertyName, String propertyValue) throws AdminException{
try {
ManagementView localView = getView();
- ManagedComponent mc = getManagedConnectionFactoryComponent(deployedName);
+ ManagedComponent mc = localView.getComponent(deployedName, TRANSLATOR_TYPE);
if (mc == null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("connector_binding_exists",deployedName)); //$NON-NLS-1$;
+ throw new AdminProcessingException(IntegrationPlugin.Util.getString("translator_does_not_exist",deployedName)); //$NON-NLS-1$;
}
+
if (mc.getProperty(propertyName) != null) {
mc.getProperty(propertyName).setValue(SimpleValueSupport.wrap(propertyValue));
}
else {
- // since this is not in the regular properties list; must be teiid specific property
- // handle this by template properties
- ConnectionFactory cf = getConnectionFactory(deployedName);
- DeploymentTemplateInfo template = localView.getTemplate(cf.getTemplateName());
- if (template instanceof ExtendedPropertyInfo) {
- ExtendedPropertyInfo extendedTemplate = (ExtendedPropertyInfo)template;
- extendedTemplate.updateProperty(propertyName, propertyValue, mc);
- }
+ Map<String, String> configProps = new HashMap<String, String>();
+ configProps.put(propertyName, propertyValue);
+ configProps.put(propertyValue+".type", "java.lang.String"); //$NON-NLS-1$ //$NON-NLS-2$
+ MetaValue metaValue = ManagedUtil.compositeValueMap(configProps);
+ mc.getProperty("translator-property").setValue(metaValue); //$NON-NLS-1$
}
localView.updateComponent(mc);
@@ -302,71 +242,23 @@
}
@Override
- public void deleteConnectionFactory(String deployedName) throws AdminException {
- ManagedComponent mc = getManagedConnectionFactoryComponent(deployedName);
- if (mc != null) {
- ManagedUtil.removeArchive(getDeploymentManager(),mc.getDeployment().getName());
- }
- }
-
- @Override
- public void startConnectionFactory(String deployedName) throws AdminException {
+ public void deleteTranslator(String deployedName) throws AdminException {
try {
- String deploymentName = getDeploymentName(deployedName);
- ManagedUtil.execute(getDeploymentManager().start(deploymentName), IntegrationPlugin.Util.getString("failed_to_start_connector", deployedName)); //$NON-NLS-1$
+ ManagedComponent mc = getView().getComponent(deployedName, TRANSLATOR_TYPE);
+ if (mc != null) {
+ ManagedUtil.removeArchive(getDeploymentManager(),mc.getDeployment().getName());
+ }
} catch (Exception e) {
- ManagedUtil.handleException(e);
+ throw new AdminComponentException(e);
}
}
-
- @Override
- public void stopConnectionFactory(String deployedName) throws AdminException {
- try {
- String deploymentName = getDeploymentName(deployedName);
- ManagedUtil.execute(getDeploymentManager().stop(deploymentName), IntegrationPlugin.Util.getString("failed_to_stop_connector", deployedName)); //$NON-NLS-1$
- } catch (Exception e) {
- ManagedUtil.handleException(e);
- }
- }
-
- private String getDeploymentName(String deployedName) throws AdminProcessingException {
- ManagedComponent mc = getManagedConnectionFactoryComponent(deployedName);
- if (mc == null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("failed_to_find_connector", deployedName)); //$NON-NLS-1$
- }
- String deploymentName = mc.getDeployment().getName();
- if (deploymentName == null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("failed_to_find_connector")); //$NON-NLS-1$
- }
- return deploymentName;
- }
@Override
- public Collection<ConnectionFactory> getConnectionFactoriesInVDB(String vdbName, int vdbVersion) throws AdminException {
- HashMap<String, ConnectionFactory> bindingMap = new HashMap<String, ConnectionFactory>();
- VDBMetaData vdb = (VDBMetaData) getVDB(vdbName, vdbVersion);
- if (vdb != null) {
- for (Model model:vdb.getModels()) {
- if (model.isSource()) {
- for (String sourceName : model.getSourceNames()) {
- ConnectionFactory binding = getConnectionFactory(((ModelMetaData)model).getSourceJndiName(sourceName));
- if (binding != null) {
- bindingMap.put(sourceName, binding);
- }
- }
- }
- }
- }
- return new ArrayList(bindingMap.values());
- }
-
-
- @Override
- public Set<String> getConnectorTemplateNames() throws AdminException{
+ public Set<String> getTranslatorTemplateNames() throws AdminException{
Set<String> names = getView().getTemplateNames();
HashSet<String> matched = new HashSet<String>();
for(String name:names) {
- if (name.startsWith(CONNECTOR_PREFIX)) {
+ if (name.startsWith(TRANSLATOR_PREFIX)) {
matched.add(name);
}
}
@@ -409,7 +301,7 @@
public VDB getVDB(String vdbName, int vdbVersion) throws AdminException{
ManagedComponent mc = getVDBManagedComponent(vdbName, vdbVersion);
if (mc != null) {
- return buildVDB(mc);
+ return AdminObjectBuilder.buildAO(mc, VDBMetaData.class);
}
return null;
}
@@ -436,129 +328,14 @@
Set<VDB> vdbs = new HashSet<VDB>();
Set<ManagedComponent> vdbComponents = getView().getComponentsForType(VDBTYPE);
for (ManagedComponent mc: vdbComponents) {
- vdbs.add(buildVDB(mc));
+ vdbs.add(AdminObjectBuilder.buildAO(mc, VDBMetaData.class));
}
return vdbs;
} catch (Exception e) {
throw new AdminComponentException(e.getMessage(), e);
}
}
-
- private VDBMetaData buildVDB(ManagedComponent mc) {
- VDBMetaData vdb = new VDBMetaData();
- vdb.setName(ManagedUtil.getSimpleValue(mc, "name", String.class));//$NON-NLS-1$
- vdb.setDescription(ManagedUtil.getSimpleValue(mc, "description", String.class));//$NON-NLS-1$
- String status = ManagedUtil.getSimpleValue(mc, "status", String.class);//$NON-NLS-1$
- if (status != null) {
- vdb.setStatus(VDB.Status.valueOf(status));
- }
- vdb.setVersion(ManagedUtil.getSimpleValue(mc, "version", Integer.class));//$NON-NLS-1$
- vdb.setUrl(mc.getDeployment().getName());
- ManagedProperty prop = mc.getProperty("JAXBProperties"); //$NON-NLS-1$
- List<ManagedObject> properties = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(prop.getValue());
- for (ManagedObject managedProperty:properties) {
- vdb.addProperty(ManagedUtil.getSimpleValue(managedProperty, "name", String.class), ManagedUtil.getSimpleValue(managedProperty, "value", String.class)); //$NON-NLS-1$ //$NON-NLS-2$
- }
- // models
- ManagedProperty mp = mc.getProperty("models");//$NON-NLS-1$
- List<ManagedObject> models = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
- for(ManagedObject mo:models) {
- vdb.addModel(buildModel(mo));
- }
-
- // SecurityRoleMappings
- mp = mc.getProperty("dataPolicies");//$NON-NLS-1$
- List<ManagedObject> policies = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(mp.getValue());
- if (policies != null && !policies.isEmpty()) {
- for(ManagedObject mo:policies) {
- vdb.addDataPolicy(buildDataPolicy(mo));
- }
- }
- return vdb;
- }
-
- private DataPolicyMetadata buildDataPolicy(ManagedObject managedPolicy) {
- DataPolicyMetadata policy = new DataPolicyMetadata();
- policy.setName(ManagedUtil.getSimpleValue(managedPolicy, "name", String.class));//$NON-NLS-1$
- policy.setDescription(ManagedUtil.getSimpleValue(managedPolicy, "description", String.class));//$NON-NLS-1$
-
- ManagedProperty mappedRoleNames = managedPolicy.getProperty("mappedRoleNames");//$NON-NLS-1$
- CollectionValueSupport roleCollection = (CollectionValueSupport)mappedRoleNames.getValue();
- if (roleCollection != null) {
- MetaValue[] roleNames = roleCollection.getElements();
- for (MetaValue mv:roleNames) {
- policy.addMappedRoleName((String)((SimpleValueSupport)mv).getValue());
- }
- }
-
- ManagedProperty permissions = managedPolicy.getProperty("permissions");//$NON-NLS-1$
- if (permissions != null) {
- List<ManagedObject> permissionCollection = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(permissions.getValue());
- if (permissionCollection != null) {
- for (ManagedObject mo:permissionCollection) {
- PermissionMetaData permission = new PermissionMetaData();
-
- permission.setResourceName(ManagedUtil.getSimpleValue(mo, "resourceName", String.class));//$NON-NLS-1$
-
- if (ManagedUtil.getSimpleValue(mo, "allowCreate", Boolean.class) != null) { //$NON-NLS-1$
- permission.setAllowCreate(ManagedUtil.getSimpleValue(mo, "allowCreate", Boolean.class)); //$NON-NLS-1$
- }
-
- if (ManagedUtil.getSimpleValue(mo, "allowRead", Boolean.class) != null) { //$NON-NLS-1$
- permission.setAllowRead(ManagedUtil.getSimpleValue(mo, "allowRead", Boolean.class)); //$NON-NLS-1$
- }
-
- if (ManagedUtil.getSimpleValue(mo, "allowUpdate", Boolean.class) != null) { //$NON-NLS-1$
- permission.setAllowUpdate(ManagedUtil.getSimpleValue(mo, "allowUpdate", Boolean.class)); //$NON-NLS-1$
- }
-
- if (ManagedUtil.getSimpleValue(mo, "allowDelete", Boolean.class) != null) { //$NON-NLS-1$
- permission.setAllowDelete(ManagedUtil.getSimpleValue(mo, "allowDelete", Boolean.class)); //$NON-NLS-1$
- }
-
- policy.addPermission(permission);
- }
- }
- }
-
- return policy;
- }
-
- private ModelMetaData buildModel(ManagedObject managedModel) {
- ModelMetaData model = new ModelMetaData();
- model.setName(ManagedUtil.getSimpleValue(managedModel, "name", String.class));//$NON-NLS-1$
- model.setVisible(ManagedUtil.getSimpleValue(managedModel, "visible", Boolean.class));//$NON-NLS-1$
- model.setModelType(ManagedUtil.getSimpleValue(managedModel, "modelType", String.class));//$NON-NLS-1$
-
- ManagedProperty prop = managedModel.getProperty("JAXBProperties"); //$NON-NLS-1$
- List<ManagedObject> properties = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(prop.getValue());
- for (ManagedObject managedProperty:properties) {
- model.addProperty(ManagedUtil.getSimpleValue(managedProperty, "name", String.class), ManagedUtil.getSimpleValue(managedProperty, "value", String.class)); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- 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 name = ManagedUtil.getSimpleValue(mo, "name", String.class);//$NON-NLS-1$
- String jndiName = ManagedUtil.getSimpleValue(mo, "jndiName", String.class);//$NON-NLS-1$
- model.addSourceMapping(name, jndiName);
- }
- }
-
- ManagedProperty validationErrors = managedModel.getProperty("errors");//$NON-NLS-1$
- if (validationErrors != null) {
- List<ManagedObject> errors = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(validationErrors.getValue());
- if (errors != null) {
- for (ManagedObject mo:errors) {
- model.addError(ManagedUtil.getSimpleValue(mo, "severity", String.class), ManagedUtil.getSimpleValue(mo, "value", String.class));//$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- }
- return model;
- }
-
@Override
public Collection<Session> getSessions() throws AdminException {
try {
@@ -627,62 +404,7 @@
}
}
- private String getRarDeployerName(String rarName) throws AdminException{
- try {
- Set<String> rarDeployments = getView().getDeploymentNamesForType("rar");//$NON-NLS-1$
- for (String name: rarDeployments) {
- if (name.endsWith(rarName+"/")) { //$NON-NLS-1$
- return name;
- }
- }
- return null;
- } catch (Exception e) {
- throw new AdminComponentException(e.getMessage(), e);
- }
- }
-
@Override
- public void addConnector(String connectorName, InputStream contents) throws AdminException{
- if (!connectorName.startsWith(CONNECTOR_PREFIX) || !connectorName.endsWith(RAR)) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("bad_connector_type_name")); //$NON-NLS-1$
- }
-
- String deployerName = getRarDeployerName(connectorName);
- if (deployerName != null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("connector_type_exists", connectorName)); //$NON-NLS-1$
- }
-
- ManagedUtil.deployArchive(getDeploymentManager(), connectorName, contents, false);
-
- //also need to add a template for the properties
- try {
- String connectorNameWithoutExt = connectorName.substring(0, connectorName.length()-4);
- File jarFile = Admin.createConnectorTypeTemplate(connectorNameWithoutExt);
- ManagedUtil.deployArchive(getDeploymentManager(), connectorNameWithoutExt+"-template.jar", jarFile.toURI().toURL(), false);//$NON-NLS-1$
- jarFile.delete();
- } catch (IOException e) {
- deleteConnector(connectorName);
- }
- }
-
- @Override
- public void deleteConnector(String connectorName) throws AdminException {
- if (!connectorName.startsWith(CONNECTOR_PREFIX) || !connectorName.endsWith(RAR)) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("bad_connector_type_name")); //$NON-NLS-1$
- }
-
- String deployerName = getRarDeployerName(connectorName);
- if (deployerName == null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("connector_not_found", connectorName)); //$NON-NLS-1$
- }
-
- //also need to delete template for the properties
- String connectorNameWithoutExt = connectorName.substring(0, connectorName.length()-4);
- ManagedUtil.removeArchive(getDeploymentManager(), connectorNameWithoutExt+"-template.jar");//$NON-NLS-1$
- ManagedUtil.removeArchive(getDeploymentManager(), deployerName);
- }
-
- @Override
public Collection<String> getCacheTypes() throws AdminException {
try {
Collection<String> requestList = new ArrayList<String>();
@@ -747,7 +469,7 @@
@Override
- public Collection<PropertyDefinition> getConnectorTemplatePropertyDefinitions(String templateName) throws AdminException {
+ public Collection<PropertyDefinition> getTranslatorTemplatePropertyDefinitions(String templateName) throws AdminException {
try {
DeploymentTemplateInfo info = getView().getTemplate(templateName);
if(info == null) {
@@ -814,87 +536,8 @@
return false;
}
- private void addConnectionfactory(String deploymentName, String typeName, Properties properties) throws AdminException {
- try {
- DeploymentTemplateInfo info = getView().getTemplate(typeName);
- if(info == null) {
- throw new AdminProcessingException(IntegrationPlugin.Util.getString("connector_type_not_found", typeName)); //$NON-NLS-1$
- }
-
-// Map<String, String> configProps = new HashMap<String, String>();
-
- // template properties specific to the template
- Map<String, ManagedProperty> propertyMap = info.getProperties();
-
- // walk through the supplied properties and assign properly to either template
- // of config-properties.
- 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));
- }
- }
-// else {
-// configProps.put(key, properties.getProperty(key));
-// configProps.put(key+".type", "java.lang.String");//$NON-NLS-1$ //$NON-NLS-2$
-// }
- }
-
-// if (configProps.size() > 0) {
-// MetaValue metaValue = ManagedUtil.compositeValueMap(configProps);
-// info.getProperties().get("config-property").setValue(metaValue);//$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);
- }
- }
-
- private static final String connectorTemplate =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+ //$NON-NLS-1$
- "<deployment xmlns=\"urn:jboss:bean-deployer:2.0\">\n" + //$NON-NLS-1$
- "<!-- This is Teiid connector type template - DO NOT DELETE -->\n"+ //$NON-NLS-1$
- "<bean name=\"${name}\" class=\"org.teiid.templates.connector.ConnectorDeploymentTemplate\">\n" + //$NON-NLS-1$
- " <property name=\"info\"><inject bean=\"${name}-templateinfo\"/></property>\n" + //$NON-NLS-1$
- " <property name=\"targetTemplate\"><inject bean=\"NoTxConnectionFactoryTemplate\"/></property>\n" + //$NON-NLS-1$
- "</bean>\n" + //$NON-NLS-1$
- "<bean name=\"${name}-templateinfo\" class=\"org.teiid.templates.connector.ConnectorTemplateInfo\">\n" + //$NON-NLS-1$
- " <constructor factoryMethod=\"createTemplateInfo\">\n" + //$NON-NLS-1$
- " <factory bean=\"DSDeploymentTemplateInfoFactory\"/>\n" + //$NON-NLS-1$
- " <parameter class=\"java.lang.Class\">org.teiid.templates.connector.ConnectorTemplateInfo</parameter>\n" + //$NON-NLS-1$
- " <parameter class=\"java.lang.Class\">org.jboss.resource.metadata.mcf.NoTxConnectionFactoryDeploymentMetaData</parameter>\n" + //$NON-NLS-1$
- " <parameter class=\"java.lang.String\">${name}</parameter>\n" + //$NON-NLS-1$
- " <parameter class=\"java.lang.String\">${name}</parameter>\n"+ //$NON-NLS-1$
- " </constructor>\n" + //$NON-NLS-1$
- " <property name=\"rarName\">${name}.rar</property>" + //$NON-NLS-1$
- "</bean>\n"+ //$NON-NLS-1$
- "</deployment>"; //$NON-NLS-1$
-
- private static File createConnectorTypeTemplate(String name) throws IOException {
- String content = connectorTemplate.replace("${name}", name);//$NON-NLS-1$
-
- File jarFile = File.createTempFile(name, ".jar");//$NON-NLS-1$
- JarOutputStream jo = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)));
-
- JarEntry je = new JarEntry("META-INF/jboss-beans.xml");//$NON-NLS-1$
- jo.putNextEntry(je);
-
- jo.write(content.getBytes());
-
- jo.close();
- return jarFile;
- }
-
-
@Override
- public void assignConnectionFactoryToModel(String vdbName, int vdbVersion, String modelName, String sourceName, String jndiName) throws AdminException {
-
+ 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$
@@ -922,11 +565,19 @@
for (ManagedObject mo:mappings) {
String sName = ManagedUtil.getSimpleValue(mo, "name", String.class);//$NON-NLS-1$
if (sName.equals(sourceName)) {
- ManagedProperty jndiProperty = mo.getProperty("jndiName"); //$NON-NLS-1$
+
+ 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, dsName));
+
+ // set the jndi name for the ds.
+ ManagedProperty jndiProperty = mo.getProperty("connectionJndiName"); //$NON-NLS-1$
if (jndiProperty == null) {
- jndiProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("jndiName")); //$NON-NLS-1$
+ jndiProperty = new WritethroughManagedPropertyImpl(mo, new DefaultFieldsImpl("connectionJndiName")); //$NON-NLS-1$
}
- jndiProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, jndiName));
+ jndiProperty.setValue(ManagedUtil.wrap(SimpleMetaType.STRING, dsName));
}
}
} else {
Deleted: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,195 +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.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import javax.resource.ResourceException;
-
-import org.jboss.deployers.spi.DeploymentException;
-import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
-import org.jboss.deployers.spi.deployer.managed.ManagedObjectCreator;
-import org.jboss.deployers.structure.spi.DeploymentUnit;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.factory.ManagedObjectFactory;
-import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryDeploymentMetaData;
-import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryPropertyMetaData;
-import org.teiid.adminapi.ConnectionFactory;
-import org.teiid.adminapi.impl.ConnectionFactoryMetaData;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.basic.BasicManagedConnectionFactory;
-import org.teiid.deployers.VDBStatusChecker;
-import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
-import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
-import org.teiid.jboss.IntegrationPlugin;
-
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.util.PropertiesUtils;
-import com.metamatrix.core.MetaMatrixCoreException;
-import com.metamatrix.core.util.ReflectionHelper;
-
-/**
- * If the data source's "-ds.xml" file contains couple of extra Teiid Connection Factory properties, this deployer
- * creates a stateful "Connector" and creates the "ConnectorManager" using the "Connector" created. In this case the
- * "Connector" is not the JCA component. No lookup done for the "Connector". This way Teiid can combine the creation of
- * data source and connection factory in one step.
- */
-public class AutoConnectionFactoryDeployer extends AbstractSimpleRealDeployer<AutoConnectionFactoryDeploymentGroup> implements ManagedObjectCreator {
-
- private ConnectorManagerRepository connectorManagerRepository;
- private VDBStatusChecker vdbChecker;
- private ManagedObjectFactory mof;
-
- public AutoConnectionFactoryDeployer() {
- super(AutoConnectionFactoryDeploymentGroup.class);
- setRelativeOrder(3000);
- }
-
- @Override
- public void deploy(DeploymentUnit unit, AutoConnectionFactoryDeploymentGroup group) throws DeploymentException {
- List<ManagedConnectionFactoryDeploymentMetaData> deployments = group.getDeployments();
-
- ConnectionFactoryMetadataGroup cfGroup = new ConnectionFactoryMetadataGroup();
-
- for (ManagedConnectionFactoryDeploymentMetaData data : deployments) {
- String connectorName = "java:"+data.getJndiName(); //$NON-NLS-1$
- ConnectorManager cm = null;
-
- // check if a Teiid connection factory needs to be created for this data source.
- List<ManagedConnectionFactoryPropertyMetaData> props = data.getManagedConnectionFactoryProperties();
-
- String cfClass = getPropertyValue("ConnectionFactoryClass", props); //$NON-NLS-1$
- if (cfClass != null) {
- Properties teiidProps = convertToProperties(props);
-
- // This indicates that a Teiid Connection factory
- Connector connector = buildTeiidConnector(cfClass, teiidProps, connectorName);
- cm = new ConnectorManager(connectorName, connector, data.getMaxSize());
-
- cm.start();
-
- // Add the references to the mgr as loaded.
- this.connectorManagerRepository.addConnectorManager(connectorName, cm);
- cfGroup.addConnectionFactory(ConnectionFactoryDeployer.buildCF(data));
-
- this.vdbChecker.connectorAdded(connectorName);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("connector_started", connectorName)); //$NON-NLS-1$
- }
- }
-
- if (!cfGroup.getConnectionFactories().isEmpty()) {
- unit.addAttachment(ConnectionFactoryMetadataGroup.class, cfGroup);
- }
- }
-
- private String getPropertyValue(String name, List<ManagedConnectionFactoryPropertyMetaData> props) {
- for (ManagedConnectionFactoryPropertyMetaData prop:props) {
- if (prop.getName().equals(name)) {
- return prop.getValue();
- }
- }
- return null;
- }
-
- private Properties convertToProperties(List<ManagedConnectionFactoryPropertyMetaData> props) {
- Properties convertedProps = new Properties();
- for (ManagedConnectionFactoryPropertyMetaData prop:props) {
- convertedProps.setProperty(prop.getName(), prop.getValue());
- }
- return convertedProps;
- }
-
- private Connector buildTeiidConnector(String cfClass, Properties props, String sourceJndiName) throws DeploymentException {
- BasicManagedConnectionFactory cf;
- try {
- Object o = ReflectionHelper.create(cfClass, null, Thread.currentThread().getContextClassLoader());
- if(!(o instanceof ConnectorEnvironment)) {
- throw new DeploymentException(IntegrationPlugin.Util.getString("invalid_class", cfClass));//$NON-NLS-1$
- }
- cf = (BasicManagedConnectionFactory)o;
-
- PropertiesUtils.setBeanProperties(cf, props, null);
- cf.setSourceJNDIName(sourceJndiName);
-
- return (Connector)cf.createConnectionFactory();
-
- } catch (MetaMatrixCoreException e) {
- throw new DeploymentException(e);
- } catch (ResourceException e) {
- throw new DeploymentException(e);
- }
- }
-
- public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
- this.connectorManagerRepository = repo;
- }
-
- /*
- * undeploy covered by the other deployer already.
- @Override
- public void undeploy(DeploymentUnit unit, AutoConnectionFactoryDeploymentGroup group) {
- super.undeploy(unit, group);
- List<ManagedConnectionFactoryDeploymentMetaData> deployments = group.getDeployments();
-
- for (ManagedConnectionFactoryDeploymentMetaData data : deployments) {
- String connectorName = "java:"+data.getJndiName(); //$NON-NLS-1$
- if (this.connectorManagerRepository != null) {
- ConnectorManager cm = this.connectorManagerRepository.removeConnectorManager(connectorName);
- if (cm != null) {
- cm.stop();
- this.vdbChecker.connectorRemoved(connectorName);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("connector_stopped", connectorName)); //$NON-NLS-1$
- }
- }
- }
- }
- */
-
- @Override
- public void build(DeploymentUnit unit, Set<String> attachmentNames, Map<String, ManagedObject> managedObjects)
- throws DeploymentException {
-
- ConnectionFactoryMetadataGroup group = unit.getAttachment(ConnectionFactoryMetadataGroup.class);
- if (group != null) {
- for (ConnectionFactoryMetaData data : group.getConnectionFactories()) {
- ManagedObject mo = this.mof.initManagedObject(data, ConnectionFactory.class, data.getName(), data.getName());
- if (mo == null) {
- throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
- }
- managedObjects.put(mo.getName(), mo);
- }
- }
- }
-
- public void setVDBStatusChecker(VDBStatusChecker vdbChecker) {
- this.vdbChecker = vdbChecker;
- }
-
- public void setManagedObjectFactory(ManagedObjectFactory mof) {
- this.mof = mof;
- }
-}
Deleted: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeploymentGroup.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeploymentGroup.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryDeploymentGroup.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,51 +0,0 @@
-/*
- * 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.
- */
-package org.teiid.jboss.deployers;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElements;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryDeploymentMetaData;
-
-
-(a)XmlAccessorType(XmlAccessType.NONE)
-@XmlRootElement
-public class AutoConnectionFactoryDeploymentGroup implements Serializable {
- private static final long serialVersionUID = -7650097438654698297L;
-
- @XmlElements({@XmlElement(name="local-tx-datasource", type=ManagedConnectionFactoryDeploymentMetaData.class),
- @XmlElement(name="no-tx-datasource", type=ManagedConnectionFactoryDeploymentMetaData.class),
- @XmlElement(name="xa-datasource", type=ManagedConnectionFactoryDeploymentMetaData.class)})
- List<ManagedConnectionFactoryDeploymentMetaData> deployments = new ArrayList<ManagedConnectionFactoryDeploymentMetaData>();
-
- public List<ManagedConnectionFactoryDeploymentMetaData> getDeployments() {
- return Collections.unmodifiableList(deployments);
- }
-}
Deleted: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryParserDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryParserDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/AutoConnectionFactoryParserDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-package org.teiid.jboss.deployers;
-
-import java.io.InputStream;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.sax.SAXSource;
-
-import org.jboss.deployers.vfs.spi.deployer.AbstractVFSParsingDeployer;
-import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
-import org.jboss.util.xml.JBossEntityResolver;
-import org.jboss.virtual.VirtualFile;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-import org.xml.sax.helpers.XMLReaderFactory;
-
-
-public class AutoConnectionFactoryParserDeployer extends AbstractVFSParsingDeployer<AutoConnectionFactoryDeploymentGroup> {
-
- public AutoConnectionFactoryParserDeployer() {
- super(AutoConnectionFactoryDeploymentGroup.class);
- setIncludeDeploymentFile(true);
- setSuffix("-ds.xml"); //$NON-NLS-1$
- }
-
- @Override
- protected AutoConnectionFactoryDeploymentGroup parse(VFSDeploymentUnit unit, VirtualFile file, AutoConnectionFactoryDeploymentGroup root) throws Exception {
- JAXBContext context = JAXBContext.newInstance(new Class[] {AutoConnectionFactoryDeploymentGroup.class});
- Unmarshaller um = context.createUnmarshaller();
- InputStream is = file.openStream();
-
- try{
- InputSource input = new InputSource(is);
- input.setSystemId(file.toURI().toString());
- XMLReader reader = XMLReaderFactory.createXMLReader();
- reader.setEntityResolver(new JBossEntityResolver());
- SAXSource source = new SAXSource(reader, input);
- JAXBElement<AutoConnectionFactoryDeploymentGroup> elem = um.unmarshal(source, AutoConnectionFactoryDeploymentGroup.class);
- AutoConnectionFactoryDeploymentGroup deployment = elem.getValue();
- return deployment;
- }
- finally {
- if (is != null)
- is.close();
- }
- }
-}
Modified: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,44 +22,22 @@
package org.teiid.jboss.deployers;
import java.util.List;
-import java.util.Map;
-import java.util.Set;
import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
-import org.jboss.deployers.spi.deployer.managed.ManagedObjectCreator;
import org.jboss.deployers.structure.spi.DeploymentUnit;
-import org.jboss.managed.api.ManagedObject;
-import org.jboss.managed.api.ManagedProperty;
-import org.jboss.managed.api.factory.ManagedObjectFactory;
-import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.CollectionValue;
-import org.jboss.metatype.api.values.GenericValue;
-import org.jboss.metatype.api.values.MapCompositeValueSupport;
-import org.jboss.metatype.api.values.MetaValue;
import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryDeploymentGroup;
import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryDeploymentMetaData;
-import org.jboss.resource.metadata.mcf.ManagedConnectionFactoryPropertyMetaData;
-import org.teiid.adminapi.ConnectionFactory;
-import org.teiid.adminapi.impl.ConnectionFactoryMetaData;
-import org.teiid.adminapi.jboss.ManagedUtil;
-import org.teiid.connector.api.Connector;
import org.teiid.deployers.VDBStatusChecker;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
-import org.teiid.jboss.IntegrationPlugin;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-
/**
- * This is a deployer that looks for the teiid connection factories deployed with their own "-ds.xml"
- * file, then this class creates a ConnectorManager for it. So, the access to the "Connector" is through look-up
- * in jndi tree for Connector Manager. Connector is JCA component.
+ * This deployer listens to the data source load and unload events and manages the connectionManager status based
+ * on these events.
*/
-public class ConnectionFactoryDeployer extends AbstractSimpleRealDeployer<ManagedConnectionFactoryDeploymentGroup> implements ManagedObjectCreator {
+public class ConnectionFactoryDeployer extends AbstractSimpleRealDeployer<ManagedConnectionFactoryDeploymentGroup> {
- private ManagedObjectFactory mof;
private ConnectorManagerRepository connectorManagerRepository;
private VDBStatusChecker vdbChecker;
@@ -72,135 +50,33 @@
public void deploy(DeploymentUnit unit, ManagedConnectionFactoryDeploymentGroup group) throws DeploymentException {
List<ManagedConnectionFactoryDeploymentMetaData> deployments = group.getDeployments();
- ConnectionFactoryMetadataGroup cfGroup = new ConnectionFactoryMetadataGroup();
-
for (ManagedConnectionFactoryDeploymentMetaData data : deployments) {
- String connectorDefinition = data.getConnectionDefinition();
- String connectorName = "java:"+data.getJndiName(); //$NON-NLS-1$
-
- if (connectorDefinition.equals(Connector.class.getName())) {
- ConnectorManager cm = new ConnectorManager(connectorName, data.getMaxSize());
- // start the connector manager
- cm.start();
-
- // Add the references to the mgr as loaded.
- this.connectorManagerRepository.addConnectorManager(connectorName, cm);
- cfGroup.addConnectionFactory(buildCF(data));
-
- this.vdbChecker.connectorAdded(connectorName);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("connector_started", connectorName)); //$NON-NLS-1$
- }
+ this.vdbChecker.dataSourceAdded(data.getJndiName());
+
+ // set the number of available connections on the cm
+ for (ConnectorManager cm:this.connectorManagerRepository.getConnectorManagers()) {
+ if (cm.getConnectionName().equals(data.getJndiName())) {
+ cm.setMaxConnections(data.getMaxSize());
+ }
+ }
}
-
- if (!cfGroup.getConnectionFactories().isEmpty()) {
- unit.addAttachment(ConnectionFactoryMetadataGroup.class, cfGroup);
- }
}
- public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
- this.connectorManagerRepository = repo;
- }
-
@Override
public void undeploy(DeploymentUnit unit, ManagedConnectionFactoryDeploymentGroup group) {
super.undeploy(unit, group);
List<ManagedConnectionFactoryDeploymentMetaData> deployments = group.getDeployments();
for (ManagedConnectionFactoryDeploymentMetaData data : deployments) {
- String connectorDefinition = data.getConnectionDefinition();
- if (connectorDefinition.equals(Connector.class.getName())) {
- String connectorName = "java:"+data.getJndiName(); //$NON-NLS-1$
- if (this.connectorManagerRepository != null) {
- ConnectorManager cm = this.connectorManagerRepository.removeConnectorManager(connectorName);
- if (cm != null) {
- cm.stop();
- this.vdbChecker.connectorRemoved(connectorName);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("connector_stopped", connectorName)); //$NON-NLS-1$
- }
- }
- }
+ this.vdbChecker.dataSourceRemoved(data.getJndiName());
}
}
- @Override
- public void build(DeploymentUnit unit, Set<String> outputs,Map<String, ManagedObject> managedObjects) throws DeploymentException {
- ConnectionFactoryMetadataGroup group = unit.getAttachment(ConnectionFactoryMetadataGroup.class);
-
- ManagedObject mcfdgMO = managedObjects.get(ManagedConnectionFactoryDeploymentGroup.class.getName());
- if (mcfdgMO != null) {
- ManagedProperty deployments = mcfdgMO.getProperty("deployments"); //$NON-NLS-1$
- if (deployments.getMetaType().isCollection()) {
- if (deployments.getValue() != null) {
- MetaValue[] elements = ((CollectionValue)deployments.getValue()).getElements();
- for (MetaValue element:elements) {
- ManagedObject managed = (ManagedObject) ((GenericValue)element).getValue();
-
- ConnectionFactoryMetaData data = group.getConnectionFactory("teiid-cf/"+managed.getName()); //$NON-NLS-1$
- populateConnectionFactory(data, managed);
- if (data != null) {
- ManagedObject mo = this.mof.initManagedObject(data, ConnectionFactory.class, data.getName(), data.getName());
- if (mo == null) {
- throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
- }
- managedObjects.put(mo.getName(), mo);
- }
- }
- }
- }
- }
+ public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
+ this.connectorManagerRepository = repo;
}
-
-
- public void setManagedObjectFactory(ManagedObjectFactory mof) {
- this.mof = mof;
+ public void setVDBStatusChecker(VDBStatusChecker checker) {
+ this.vdbChecker = checker;
}
-
- public void setVDBStatusChecker(VDBStatusChecker vdbChecker) {
- this.vdbChecker = vdbChecker;
- }
-
- static ConnectionFactoryMetaData buildCF(ManagedConnectionFactoryDeploymentMetaData data) {
- ConnectionFactoryMetaData c = new ConnectionFactoryMetaData();
- // The name is prefixed here because, the Managed objects map overwrites this MO, with the main
- // -ds.xml based MO, since they have same names.
- c.setName("teiid-cf/"+data.getJndiName()); //$NON-NLS-1$
- c.setRARFileName(data.getRarName());
- c.setJNDIName("java:"+data.getJndiName()); //$NON-NLS-1$
-
- List<ManagedConnectionFactoryPropertyMetaData> props = data.getManagedConnectionFactoryProperties();
- for (ManagedConnectionFactoryPropertyMetaData p:props) {
- c.addProperty(p.getName(), p.getValue());
- }
- return c;
- }
-
- private void populateConnectionFactory(ConnectionFactoryMetaData data, ManagedObject managed) {
- Map<String, ManagedProperty> props = managed.getProperties();
-
- for (String key:props.keySet()) {
- ManagedProperty mp = props.get(key);
-
- MetaValue value = mp.getValue();
- if (value != null) {
- MetaType type = value.getMetaType();
- if (type.isSimple()) {
- data.addProperty(mp.getName(), ManagedUtil.stringValue(value));
- }
- else if (type.isComposite()) {
- if (value instanceof MapCompositeValueSupport) {
- MapCompositeValueSupport map = (MapCompositeValueSupport)value;
- if (key.equals("config-property") || key.equals("connection-properties") || key.equals("xa-datasource-properties")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- for (String subKey:map.getMetaType().keySet()) {
- MetaValue subValue = map.get(subKey);
- if (subValue.getMetaType().isSimple()) {
- data.addProperty(subKey, ManagedUtil.stringValue(subValue));
- }
- }
- }
- }
- }
- }
- }
- }
}
Deleted: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryMetadataGroup.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryMetadataGroup.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/ConnectionFactoryMetadataGroup.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,49 +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.util.ArrayList;
-import java.util.List;
-
-import org.teiid.adminapi.impl.ConnectionFactoryMetaData;
-
-public class ConnectionFactoryMetadataGroup {
- private List<ConnectionFactoryMetaData> mgrs = new ArrayList<ConnectionFactoryMetaData>();
-
- public void addConnectionFactory(ConnectionFactoryMetaData cm) {
- this.mgrs.add(cm);
- }
-
- public List<ConnectionFactoryMetaData> getConnectionFactories(){
- return this.mgrs;
- }
-
- public ConnectionFactoryMetaData getConnectionFactory(String name) {
- for(ConnectionFactoryMetaData cf: this.mgrs) {
- if (cf.getName().equals(name)) {
- return cf;
- }
- }
- return null;
- }
-}
Modified: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -60,6 +60,9 @@
import org.teiid.dqp.internal.transaction.TransactionServerImpl;
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.security.SecurityHelper;
import org.teiid.transport.ClientServiceRegistry;
import org.teiid.transport.ClientServiceRegistryImpl;
@@ -69,9 +72,6 @@
import com.metamatrix.api.exception.ComponentNotFoundException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.dqp.service.BufferService;
import com.metamatrix.dqp.service.SessionService;
Modified: trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/VDBMetaDataInstanceClassFactory.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/VDBMetaDataInstanceClassFactory.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/deployers/VDBMetaDataInstanceClassFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -63,8 +63,9 @@
List<ManagedObject> mappings = (List<ManagedObject>)MetaValueFactory.getInstance().unwrap(sourceMappings.getValue());
for (ManagedObject mo:mappings) {
String name = ManagedUtil.getSimpleValue(mo, "name", String.class);//$NON-NLS-1$
- String jndiName = ManagedUtil.getSimpleValue(mo, "jndiName", String.class);//$NON-NLS-1$
- model.addSourceMapping(name, jndiName);
+ String jndiName = ManagedUtil.getSimpleValue(mo, "connectionJndiName", String.class);//$NON-NLS-1$
+ String translatorName = ManagedUtil.getSimpleValue(mo, "translatorName", String.class);//$NON-NLS-1$
+ model.addSourceMapping(name, translatorName, jndiName);
}
}
}
Modified: trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorDeploymentTemplate.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorDeploymentTemplate.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorDeploymentTemplate.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,6 +25,8 @@
import java.util.List;
import java.util.Map;
+import javax.resource.cci.ConnectionFactory;
+
import org.jboss.deployers.spi.management.DeploymentTemplate;
import org.jboss.managed.api.DeploymentTemplateInfo;
import org.jboss.managed.api.ManagedProperty;
@@ -34,7 +36,6 @@
import org.jboss.virtual.VirtualFile;
import org.teiid.adminapi.AdminComponentException;
import org.teiid.adminapi.jboss.ManagedUtil;
-import org.teiid.connector.api.Connector;
import org.teiid.jboss.IntegrationPlugin;
/**
@@ -72,7 +73,7 @@
DeploymentTemplateInfo targetInfo = this.targetTemplate.getInfo();
// override these properties always.
- targetInfo.getProperties().get("connection-definition").setValue(SimpleValueSupport.wrap(Connector.class.getName()));//$NON-NLS-1$
+ targetInfo.getProperties().get("connection-definition").setValue(SimpleValueSupport.wrap(ConnectionFactory.class.getName()));//$NON-NLS-1$
targetInfo.getProperties().get("rar-name").setValue(SimpleValueSupport.wrap(((ConnectorTemplateInfo)getInfo()).getRarName()));//$NON-NLS-1$
Modified: trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorTemplateInfo.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorTemplateInfo.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ConnectorTemplateInfo.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,23 +24,21 @@
import java.util.List;
import java.util.Map;
-import org.jboss.managed.api.Fields;
+import javax.resource.cci.ConnectionFactory;
+
import org.jboss.managed.api.ManagedComponent;
import org.jboss.managed.api.ManagedProperty;
import org.jboss.managed.plugins.BasicDeploymentTemplateInfo;
-import org.jboss.managed.plugins.DefaultFieldsImpl;
-import org.jboss.managed.plugins.ManagedPropertyImpl;
import org.jboss.metatype.api.types.SimpleMetaType;
import org.jboss.metatype.api.values.MapCompositeValueSupport;
import org.jboss.metatype.api.values.SimpleValueSupport;
import org.teiid.adminapi.jboss.ExtendedPropertyInfo;
-import org.teiid.connector.api.Connector;
+import org.teiid.deployers.ManagedPropertyUtil;
/**
* This class some magic in it. First off all through the configuration it extends the
* NoTxConnectionFactoryTemplate. Then using the JMX adds the properties defined inside a connector
- * RAR file's ra.xml dynamically the above template. The RAR file name is supplied in the "description"
- * field of the configuration. Also, it uses the NoTxConnectionFactoryTemplate "applyTemplate" to write
+ * RAR file's ra.xml dynamically the above template. Also, it uses the NoTxConnectionFactoryTemplate "applyTemplate" to write
* the custom properties that have been added thru JMX as "config-property" in the eventual "-ds.xml" file.
*/
public class ConnectorTemplateInfo extends BasicDeploymentTemplateInfo implements ExtendedPropertyInfo {
@@ -48,7 +46,6 @@
private static final long serialVersionUID = 9066758787789280783L;
private String rarName;
static final String TEMPLATE_NAME = "template-name"; //$NON-NLS-1$
- private static final String TEIID_PROPERTY = "teiid-property"; //$NON-NLS-1$
public ConnectorTemplateInfo(String name, String description, Map<String, ManagedProperty> properties) {
@@ -67,7 +64,7 @@
copy.populate();
ManagedProperty mp = copy.getProperties().get("connection-definition");//$NON-NLS-1$
- mp.setValue(SimpleValueSupport.wrap(Connector.class.getName()));
+ mp.setValue(SimpleValueSupport.wrap(ConnectionFactory.class.getName()));
mp = copy.getProperties().get("rar-name");//$NON-NLS-1$
mp.setValue(SimpleValueSupport.wrap(getRarName()));
@@ -91,28 +88,9 @@
}
static ManagedProperty buildTemplateProperty(String name) {
- ManagedProperty mp = buildProperty(TEMPLATE_NAME, SimpleMetaType.STRING, "Template Name", "The Name of the Teiid Connector Template", true, name);//$NON-NLS-1$ //$NON-NLS-2$
- mp.setField(Fields.READ_ONLY, SimpleValueSupport.wrap(true));
- return mp;
+ return ManagedPropertyUtil.createProperty(TEMPLATE_NAME, SimpleMetaType.STRING, "Template Name", "The Name of the Teiid Connector Template", true, true, name);//$NON-NLS-1$ //$NON-NLS-2$
}
-
- static ManagedProperty buildProperty(String name, SimpleMetaType type, String displayName, String description, boolean mandatory, String value) {
- DefaultFieldsImpl fields = new DefaultFieldsImpl(name);
- fields.setDescription(description);
- fields.setField(Fields.MAPPED_NAME,displayName);
- fields.setMetaType(type);
- fields.setField(Fields.MANDATORY, SimpleValueSupport.wrap(mandatory));
- fields.setField(TEIID_PROPERTY, SimpleValueSupport.wrap(true));
- if (value != null) {
- fields.setField(Fields.DEFAULT_VALUE, SimpleValueSupport.wrap(value));
- }
- return new ManagedPropertyImpl(fields);
- }
- static void markAsTeiidProperty(ManagedProperty mp) {
- mp.setField(TEIID_PROPERTY, SimpleValueSupport.wrap(true));
- }
-
@Override
public void updateProperty(String name, String value, ManagedComponent main) {
List<String> connectorNames = RaXmlPropertyConverter.getPropertyNames(getRarName());
Deleted: trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ExtendedPropertyMetadata.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ExtendedPropertyMetadata.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ExtendedPropertyMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.templates.connector;
-
-import java.util.ArrayList;
-
-import com.metamatrix.core.MetaMatrixRuntimeException;
-
-public class ExtendedPropertyMetadata {
- private String displayName;
- private String description;
- private boolean advanced;
- private boolean masked;
- private boolean editable = true;
- private boolean required;
- private ArrayList<String> allowed;
-
-
- public ExtendedPropertyMetadata(String encodedData) {
- encodedData = encodedData.trim();
-
- // if not begins with { then treat as if just a simple description field.
- if (!encodedData.startsWith("{")) {
- this.displayName = encodedData;
- return;
- }
-
- if (!encodedData.endsWith("}")) {
- throw new MetaMatrixRuntimeException("The description field = "+encodedData+" does not end with \"}\"");
- }
- encodedData = encodedData.substring(1, encodedData.length()-1);
-
- int index = 0;
- int start = -1;
- boolean inQuotes = false;
- int inQuotesStart = -1;
- boolean inArray = false;
-
- String propertyName = null;
- ArrayList<String> values = new ArrayList<String>();
- for (char c:encodedData.toCharArray()) {
- if (c == '$' && start == -1) {
- start = index;
- }
- else if (c == '"') {
- inQuotes = !inQuotes;
- if (inQuotes && inQuotesStart == -1) {
- inQuotesStart = index;
- }
- else if (!inQuotes && inQuotesStart != -1) {
- if (inQuotesStart+1 != index) {
- values.add(encodedData.substring(inQuotesStart+1, index));
- }
- else {
- values.add("");
- }
- inQuotesStart = -1;
- }
- }
- else if (c == '[') {
- inArray = true;
- }
- else if (c == ']') {
- inArray = false;
- }
- else if (c == ':' && !inQuotes && !inArray && start != -1) {
- propertyName = encodedData.substring(start, index);
- }
- else if (c == ',' && !inQuotes && !inArray && start != -1) {
- addProperty(propertyName, values);
- propertyName = null;
- values = new ArrayList<String>();
- start = -1;
- }
- index++;
- }
- // add last property
- addProperty(propertyName, values);
- }
-
- private void addProperty(String name, ArrayList<String> values) {
- if (name.equals("$display")) {
- this.displayName = values.get(0);
- }
- else if (name.equals("$description")) {
- this.description = values.get(0);
- }
- else if (name.equals("$advanced")) {
- this.advanced = Boolean.parseBoolean(values.get(0));
- }
- else if (name.equals("$masked")) {
- this.masked = Boolean.parseBoolean(values.get(0));
- }
- else if (name.equals("$editable")) {
- this.editable = Boolean.parseBoolean(values.get(0));
- }
- else if (name.equals("$allowed")) {
- this.allowed = new ArrayList<String>(values);
- }
- else if (name.equals("$required")) {
- this.required = Boolean.parseBoolean(values.get(0));
- }
- }
-
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public String getDisplayName() {
- return displayName;
- }
- public boolean isAdvanced() {
- return advanced;
- }
- public boolean isMasked() {
- return masked;
- }
- public boolean isEditable() {
- return editable;
- }
- public boolean isRequired() {
- return required;
- }
- public ArrayList<String> getAllowed() {
- return allowed;
- }
-}
Modified: trunk/jboss-integration/src/main/java/org/teiid/templates/connector/RaXmlPropertyConverter.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/templates/connector/RaXmlPropertyConverter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/templates/connector/RaXmlPropertyConverter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.Collection;
-import java.util.HashSet;
import java.util.List;
import javax.management.AttributeNotFoundException;
@@ -40,14 +39,14 @@
import org.jboss.managed.plugins.DefaultFieldsImpl;
import org.jboss.managed.plugins.ManagedPropertyImpl;
import org.jboss.metatype.api.types.SimpleMetaType;
-import org.jboss.metatype.api.values.MetaValue;
-import org.jboss.metatype.api.values.SimpleValueSupport;
import org.jboss.resource.metadata.ConfigPropertyMetaData;
import org.jboss.resource.metadata.ConnectionDefinitionMetaData;
import org.jboss.resource.metadata.ConnectorMetaData;
import org.jboss.resource.metadata.DescriptionMetaData;
import org.teiid.adminapi.jboss.ManagedUtil;
-import org.teiid.connector.api.Connector;
+import org.teiid.deployers.ExtendedPropertyMetadata;
+import org.teiid.deployers.ManagedPropertyUtil;
+import org.teiid.resource.cci.ExecutionFactory;
public class RaXmlPropertyConverter {
@@ -80,7 +79,7 @@
MBeanServer server = MBeanServerFactory.findMBeanServer(null).get(0);
ObjectName on = new ObjectName("jboss.jca:service=RARDeployment,name='"+rarName+"'");//$NON-NLS-1$ //$NON-NLS-2$
ConnectorMetaData obj = (ConnectorMetaData)server.getAttribute(on, "MetaData");//$NON-NLS-1$
- ConnectionDefinitionMetaData metadata = obj.getConnectionDefinition(Connector.class.getName());
+ ConnectionDefinitionMetaData metadata = obj.getConnectionDefinition(ExecutionFactory.class.getName());
return metadata.getProperties();
} catch (MalformedObjectNameException e) {
//ignore
@@ -97,41 +96,21 @@
}
private static ManagedProperty createConnectorProperty(ConfigPropertyMetaData metadata) {
- SimpleMetaType metaType = SimpleMetaType.resolve(metadata.getType());
- DefaultFieldsImpl fields = new DefaultFieldsImpl(metadata.getName());
DescriptionMetaData descMetadata = metadata.getDescription();
String description = descMetadata.getDescription();
if (description != null) {
- ExtendedPropertyMetadata extended = new ExtendedPropertyMetadata(description);
- if (extended.getDescription() != null) {
- fields.setDescription(description);
- }
-
- if (extended.getDisplayName() != null) {
- fields.setField(Fields.MAPPED_NAME, extended.getDisplayName());
- }
-
- if (extended.getAllowed() != null) {
- HashSet<MetaValue> values = new HashSet<MetaValue>();
- for (String value:extended.getAllowed()) {
- values.add(ManagedUtil.wrap(SimpleMetaType.STRING, value));
- }
- fields.setField(Fields.LEGAL_VALUES, values);
- }
- fields.setField(Fields.MANDATORY, ManagedUtil.wrap(SimpleMetaType.BOOLEAN_PRIMITIVE, String.valueOf(extended.isRequired())));
- fields.setField(Fields.READ_ONLY, ManagedUtil.wrap(SimpleMetaType.BOOLEAN_PRIMITIVE, String.valueOf(!extended.isEditable())));
- fields.setField("advanced", ManagedUtil.wrap(SimpleMetaType.BOOLEAN_PRIMITIVE, String.valueOf(extended.isAdvanced())));//$NON-NLS-1$
- fields.setField("masked", ManagedUtil.wrap(SimpleMetaType.BOOLEAN_PRIMITIVE, String.valueOf(extended.isMasked())));//$NON-NLS-1$
- fields.setField("teiid-property", SimpleValueSupport.wrap(true)); //$NON-NLS-1$
+ ExtendedPropertyMetadata extended = new ExtendedPropertyMetadata(metadata.getName(), metadata.getType(), description, metadata.getValue());
+ return ManagedPropertyUtil.convert(extended);
}
+ DefaultFieldsImpl fields = new DefaultFieldsImpl(metadata.getName());
+ SimpleMetaType metaType = SimpleMetaType.resolve(metadata.getType());
fields.setMetaType(metaType);
if (metadata.getValue() != null && metadata.getValue().trim().length() > 0) {
fields.setField(Fields.DEFAULT_VALUE, ManagedUtil.wrap(metaType, metadata.getValue()));
}
- ManagedPropertyImpl dsTypeMP = new ManagedPropertyImpl(fields);
- return dsTypeMP;
+ return new ManagedPropertyImpl(fields);
}
}
Modified: trunk/jboss-integration/src/main/java/org/teiid/templates/connector/XaJdbcConnectorTemplateInfo.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/templates/connector/XaJdbcConnectorTemplateInfo.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/java/org/teiid/templates/connector/XaJdbcConnectorTemplateInfo.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -37,6 +37,7 @@
import org.jboss.resource.deployers.management.DsDataSourceTemplateInfo;
import org.teiid.adminapi.jboss.ExtendedPropertyInfo;
import org.teiid.adminapi.jboss.ManagedUtil;
+import org.teiid.deployers.ManagedPropertyUtil;
/**
* This template is specific to XA data source combined with Teiid's JDBC connector.
@@ -89,12 +90,12 @@
addProperty(ConnectorTemplateInfo.buildTemplateProperty(getName()));
- ConnectorTemplateInfo.markAsTeiidProperty(this.getProperties().get("user-name")); //$NON-NLS-1$
- ConnectorTemplateInfo.markAsTeiidProperty(this.getProperties().get("password"));//$NON-NLS-1$
- addProperty(ConnectorTemplateInfo.buildProperty(DATABASE_NAME, SimpleMetaType.STRING,"Database Name","Database Name", false, null));//$NON-NLS-1$ //$NON-NLS-2$
- addProperty(ConnectorTemplateInfo.buildProperty(PORT_NUMBER, SimpleMetaType.INTEGER,"Database Port", "Database Port",false, null));//$NON-NLS-1$ //$NON-NLS-2$
- addProperty(ConnectorTemplateInfo.buildProperty(SERVER_NAME, SimpleMetaType.STRING,"Database Server Name", "Database Server Name", false, null));//$NON-NLS-1$ //$NON-NLS-2$
- addProperty(ConnectorTemplateInfo.buildProperty(ADDITIONAL_DS_PROPS, SimpleMetaType.STRING,"Addtional Data Source Properties", "Addtional Data source properties. (comma separated name value pairs)", false, null));//$NON-NLS-1$ //$NON-NLS-2$
+ ManagedPropertyUtil.markAsTeiidProperty(this.getProperties().get("user-name")); //$NON-NLS-1$
+ ManagedPropertyUtil.markAsTeiidProperty(this.getProperties().get("password"));//$NON-NLS-1$
+ addProperty(ManagedPropertyUtil.createProperty(DATABASE_NAME, SimpleMetaType.STRING,"Database Name","Database Name", false, false, null));//$NON-NLS-1$ //$NON-NLS-2$
+ addProperty(ManagedPropertyUtil.createProperty(PORT_NUMBER, SimpleMetaType.INTEGER,"Database Port", "Database Port",false, false, null));//$NON-NLS-1$ //$NON-NLS-2$
+ addProperty(ManagedPropertyUtil.createProperty(SERVER_NAME, SimpleMetaType.STRING,"Database Server Name", "Database Server Name", false, false, null));//$NON-NLS-1$ //$NON-NLS-2$
+ addProperty(ManagedPropertyUtil.createProperty(ADDITIONAL_DS_PROPS, SimpleMetaType.STRING,"Addtional Data Source Properties", "Addtional Data source properties. (comma separated name value pairs)", false, false, null));//$NON-NLS-1$ //$NON-NLS-2$
}
static ManagedPropertyImpl buildConfigProperty() {
Modified: trunk/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
===================================================================
--- trunk/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,23 +25,16 @@
socket_enabled={0} {1}
engine_stopped=Teiid Engine stopped {0}
admin_connection_closed=Teiid admin connection is already closed.
-connector_binding_exists=Connection factory with name "{0}" already exists.
-failed_to_find_connector=Failed to find connector {0}. Can not start!
-failed_to_start_connector=Failed to start Connection factory = {0}
-failed_to_stop_connector=Failed to start Connection factory = {0}
+translator_exists=Translator with name {0} already exists in the configuration
+translator_does_not_exist=Translator with name {0} does not exist in the configuration
bad_vdb_extension=The extension of the file name must be either ".vdb" for designer vdb or "xxx-vdb.xml" for dynamic VDBs
-bad_connector_type_name=Teiid connector names must start with \"connector-\" and end with ".rar" extension.
-connector_type_exists=Connector with name:"{0}" already exists!
-connector_type_not_found=Connector template "{0}" not found in the configuration.
+translator_template_not_found=Template with name {0} not found for creating a translator
vdb_not_found=VDB with name "{0}" version "{1}" not found in configuration
model_not_found=Model name "{0}" not found in the VDB with name "{1}" version "{2}"
policy_not_found=Policy name "{0}" not found in the VDB with name "{1}" version "{2}"
connectionfactory_not_found=Connection factory {0} not found in the configuration.
datasource_not_found=Datasource {0} not found in the configuration.
-connector_not_found=Connector {0} not found in the configuration.
sourcename_not_found=No source name {0} found in the model: {1}.{2}.{3}
-connector_started= Teiid connector {0} started
-connector_stopped=Teiid connector {0} stopped
no_operation=No operation found with given name = {0}
failed_to_remove=Failed to remove the deployment
Deleted: trunk/jboss-integration/src/test/java/org/teiid/templates/connector/TestExtendedPropertyMetadata.java
===================================================================
--- trunk/jboss-integration/src/test/java/org/teiid/templates/connector/TestExtendedPropertyMetadata.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/jboss-integration/src/test/java/org/teiid/templates/connector/TestExtendedPropertyMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.templates.connector;
-
-import java.util.ArrayList;
-
-import junit.framework.Assert;
-
-import org.junit.Test;
-
-public class TestExtendedPropertyMetadata {
-
- @Test
- public void testDefault() {
- ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("some-name");
-
- Assert.assertEquals("some-name", metadata.getDisplayName());
- Assert.assertEquals(null, metadata.getDescription());
- Assert.assertEquals(false, metadata.isAdvanced());
- Assert.assertEquals(false, metadata.isRequired());
- Assert.assertEquals(false, metadata.isMasked());
- Assert.assertEquals(true , metadata.isEditable());
- }
-
- @Test
- public void testFormatted() {
- ArrayList<String> allowed = new ArrayList<String>();
- allowed.add("get");
- allowed.add("post");
-
- ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("{$display:\"Is Immutable\",$description:\"True if the source never changes.\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}");
-
- Assert.assertEquals("Is Immutable", metadata.getDisplayName());
- Assert.assertEquals("True if the source never changes.", metadata.getDescription());
- Assert.assertEquals(true, metadata.isAdvanced());
- Assert.assertEquals(true, metadata.isRequired());
- Assert.assertEquals(false, metadata.isMasked());
- Assert.assertEquals(true , metadata.isEditable());
- Assert.assertEquals(allowed , metadata.getAllowed());
- }
-
- @Test
- public void testFormattedExtraCommasAndColons() {
- ArrayList<String> allowed = new ArrayList<String>();
- allowed.add("get");
- allowed.add("post");
-
- ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("{$display:\"Is Immu:table\",$description:\"True if the, source never changes.\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}");
-
- Assert.assertEquals("Is Immu:table", metadata.getDisplayName());
- Assert.assertEquals("True if the, source never changes.", metadata.getDescription());
- Assert.assertEquals(true, metadata.isAdvanced());
- Assert.assertEquals(true, metadata.isRequired());
- Assert.assertEquals(false, metadata.isMasked());
- Assert.assertEquals(true , metadata.isEditable());
- Assert.assertEquals(allowed , metadata.getAllowed());
- }
-
- @Test
- public void testBlankProperties() {
- ArrayList<String> allowed = new ArrayList<String>();
- allowed.add("get");
- allowed.add("post");
-
- ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("{$display:\"Is Immutable\",$description:\"\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}");
-
- Assert.assertEquals("Is Immutable", metadata.getDisplayName());
- Assert.assertEquals("", metadata.getDescription());
- Assert.assertEquals(true, metadata.isAdvanced());
- Assert.assertEquals(true, metadata.isRequired());
- Assert.assertEquals(false, metadata.isMasked());
- Assert.assertEquals(true , metadata.isEditable());
- Assert.assertEquals(allowed , metadata.getAllowed());
- }
-}
Modified: trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java
===================================================================
--- trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -22,23 +22,23 @@
package com.metamatrix.cdk.api;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.Connector;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.Execution;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.api.UpdateExecution;
import org.teiid.connector.language.BatchedUpdates;
import org.teiid.connector.language.Command;
import org.teiid.connector.metadata.runtime.RuntimeMetadata;
import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.DataNotAvailableException;
+import org.teiid.resource.cci.Execution;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ExecutionFactory;
+import org.teiid.resource.cci.ResultSetExecution;
+import org.teiid.resource.cci.UpdateExecution;
/**
* A simple test environment to execute commands on a connector.
@@ -47,63 +47,71 @@
*/
public class ConnectorHost {
- private Connector connector;
+ private ExecutionFactory connector;
private TranslationUtility util;
private ExecutionContext executionContext;
- public ConnectorHost(Connector connector, ConnectorEnvironment connectorEnvironment, String vdbFileName) throws ConnectorException {
- initialize(connector, connectorEnvironment, new TranslationUtility(VDBMetadataFactory.getVDBMetadata(vdbFileName)));
+ public ConnectorHost(ExecutionFactory connector, String vdbFileName) throws ConnectorException {
+ initialize(connector, new TranslationUtility(VDBMetadataFactory.getVDBMetadata(vdbFileName)));
}
- public ConnectorHost(Connector connector, ConnectorEnvironment connectorEnvironment, TranslationUtility util) throws ConnectorException{
- initialize(connector, connectorEnvironment, util);
+ public ConnectorHost(ExecutionFactory connector, TranslationUtility util) throws ConnectorException{
+ initialize(connector, util);
}
- private void initialize(Connector connector, final ConnectorEnvironment env, TranslationUtility util) throws ConnectorException {
+ private void initialize(ExecutionFactory connector, TranslationUtility util) throws ConnectorException {
this.connector = connector;
this.util = util;
- this.connector.initialize(env);
+ this.connector.start();
}
public void setExecutionContext(ExecutionContext context) {
this.executionContext = context;
}
- public List executeCommand(String query) throws ConnectorException {
+ public List executeCommand(String query, Object connection) throws ConnectorException {
- Connection connection = null;
try {
- connection = getConnection();
Command command = getCommand(query);
RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
return executeCommand(connection, command, runtimeMetadata);
} finally {
if (connection != null) {
- connection.close();
+ close(connection);
}
}
}
- public List executeCommand(Command command) throws ConnectorException {
-
- Connection connection = null;
+ public List executeCommand(Command command, Object connection) throws ConnectorException {
try {
- connection = getConnection();
RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
-
return executeCommand(connection, command, runtimeMetadata);
} finally {
if (connection != null) {
- connection.close();
+ close(connection);
}
}
}
- private List executeCommand(Connection connection, Command command, RuntimeMetadata runtimeMetadata)
+ private void close(Object connection) {
+ try {
+ Method m = connection.getClass().getMethod("close"); //$NON-NLS-1$
+ if (m != null) {
+ m.invoke(connection);
+ }
+ } catch (SecurityException e) {
+ } catch (IllegalArgumentException e) {
+ } catch (NoSuchMethodException e) {
+ } catch (IllegalAccessException e) {
+ } catch (InvocationTargetException e) {
+ }
+ }
+
+ private List executeCommand(Object connection, Command command, RuntimeMetadata runtimeMetadata)
throws ConnectorException {
- Execution exec = connection.createExecution(command, this.executionContext, runtimeMetadata);
+ Execution exec = connector.createExecution(command, this.executionContext, runtimeMetadata, connection);
exec.execute();
List results = readResultsFromExecution(exec);
exec.close();
@@ -111,11 +119,8 @@
return results;
}
- public int[] executeBatchedUpdates(String[] updates) throws ConnectorException {
-
- Connection connection = null;
+ public int[] executeBatchedUpdates(String[] updates, Object connection) throws ConnectorException {
try {
- connection = getConnection();
RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
Command[] commands = new Command[updates.length];
for (int i = 0; i < updates.length; i++) {
@@ -125,12 +130,12 @@
return executeBatchedUpdates(connection, commands, runtimeMetadata);
} finally {
if (connection != null) {
- connection.close();
+ close(connection);
}
}
}
- public int[] executeBatchedUpdates(Connection connection, Command[] commands, RuntimeMetadata runtimeMetadata) throws ConnectorException {
+ public int[] executeBatchedUpdates(Object connection, Command[] commands, RuntimeMetadata runtimeMetadata) throws ConnectorException {
List<List> result = executeCommand(connection, new BatchedUpdates(Arrays.asList(commands)), runtimeMetadata);
int[] counts = new int[result.size()];
for (int i = 0; i < counts.length; i++) {
@@ -175,10 +180,4 @@
public Command getCommand(String query) {
return util.parseCommand(query);
}
-
- private Connection getConnection() throws ConnectorException {
- Connection connection = connector.getConnection();
- return connection;
- }
-
}
Deleted: trunk/metadata/src/test/java/com/metamatrix/cdk/api/SysLogger.java
===================================================================
--- trunk/metadata/src/test/java/com/metamatrix/cdk/api/SysLogger.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/metadata/src/test/java/com/metamatrix/cdk/api/SysLogger.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -1,150 +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 com.metamatrix.cdk.api;
-
-import java.util.Date;
-
-import org.teiid.connector.api.ConnectorLogger;
-
-
-/**
- * ConnectorLogger that prints output to System.out.
- */
-public class SysLogger implements ConnectorLogger {
-
- public static final int OFF = 0;
- public static final int ERROR = 1;
- public static final int WARNING = 2;
- public static final int INFO = 3;
- public static final int DETAIL = 4;
- public static final int TRACE = 5;
-
- private int logLevel = INFO;
-
- public SysLogger() {
-
- }
-
- public SysLogger(boolean shouldLog) {
- if (shouldLog) {
- this.logLevel = TRACE;
- } else {
- this.logLevel = OFF;
- }
- }
-
- protected void log(int level, String message, Throwable error) {
- if (level <= this.logLevel) {
- System.out.println(getCurrentTimestampString() + " " + message); //$NON-NLS-1$
- if(error != null) {
- error.printStackTrace(System.out);
- }
- }
- }
-
- public int getLevel() {
- return this.logLevel;
- }
-
- public void setLevel(int level) {
- this.logLevel = level;
- }
-
- protected Date getCurrentTimestamp() {
- return new Date();
- }
-
- protected String getCurrentTimestampString() {
- return getCurrentTimestamp().toString();
- }
-
- public void logError(String message) {
- log(ERROR, message, null);
- }
-
- public void logError(String message, Throwable error) {
- log(ERROR, message, error);
- }
-
- public void logWarning(String message) {
- log(WARNING, message, null);
- }
-
- public void logInfo(String message) {
- log(INFO, message, null);
- }
-
- public void logDetail(String message) {
- log(DETAIL, message, null);
- }
-
- public void logTrace(String message) {
- log(TRACE, message, null);
- }
-
- @Override
- public boolean isDetailEnabled() {
- return DETAIL <= this.logLevel;
- }
-
- @Override
- public boolean isErrorEnabled() {
- return ERROR <= this.logLevel;
- }
-
- @Override
- public boolean isInfoEnabled() {
- return INFO <= this.logLevel;
- }
-
- @Override
- public boolean isTraceEnabled() {
- return TRACE <= this.logLevel;
- }
-
- @Override
- public boolean isWarningEnabled() {
- return WARNING <= this.logLevel;
- }
-
- @Override
- public void logDetail(String message, Throwable error) {
- log(DETAIL, message, error);
- }
-
- @Override
- public void logInfo(String message, Throwable error) {
- log(INFO, message, error);
- }
-
- @Override
- public void logTrace(String message, Throwable error) {
- log(TRACE, message, error);
- }
-
- @Override
- public void logWarning(String message, Throwable error) {
- log(WARNING, message, error);
- }
-
-}
Modified: trunk/runtime/pom.xml
===================================================================
--- trunk/runtime/pom.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -88,5 +88,10 @@
<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
Modified: trunk/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/deployers/DynamicVDBDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -29,9 +29,9 @@
import org.teiid.adminapi.Model;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.CoreConstants;
public class DynamicVDBDeployer extends AbstractVFSParsingDeployer<VDBMetaData> {
@@ -54,7 +54,7 @@
system.setName(CoreConstants.SYSTEM_MODEL);
system.setVisible(true);
system.setModelType(Model.Type.PHYSICAL);
- system.addSourceMapping(CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL);
+ system.addSourceMapping(CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL);
system.setSupportsMultiSourceBindings(false);
vdb.addModel(system);
Copied: trunk/runtime/src/main/java/org/teiid/deployers/ExtendedPropertyMetadata.java (from rev 2076, trunk/jboss-integration/src/main/java/org/teiid/templates/connector/ExtendedPropertyMetadata.java)
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/ExtendedPropertyMetadata.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/deployers/ExtendedPropertyMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,167 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.util.ArrayList;
+
+import com.metamatrix.core.MetaMatrixRuntimeException;
+
+/**
+ * This is used with ra.xml properties file to extend the metadata on the properties.
+ */
+public class ExtendedPropertyMetadata {
+ private String displayName;
+ private String description;
+ private boolean advanced;
+ private boolean masked;
+ private boolean editable = true;
+ private boolean required;
+ private ArrayList<String> allowed;
+ private String name;
+ private String type;
+ private String defaultValue;
+
+
+ public ExtendedPropertyMetadata(String name, String type, String encodedData, String defaultValue) {
+ this.name = name;
+ this.type = type;
+ this.defaultValue = defaultValue;
+
+ encodedData = encodedData.trim();
+
+ // if not begins with { then treat as if just a simple description field.
+ if (!encodedData.startsWith("{")) { //$NON-NLS-1$
+ this.displayName = encodedData;
+ return;
+ }
+
+ if (!encodedData.endsWith("}")) { //$NON-NLS-1$
+ throw new MetaMatrixRuntimeException("The description field = "+encodedData+" does not end with \"}\""); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ encodedData = encodedData.substring(1, encodedData.length()-1);
+
+ int index = 0;
+ int start = -1;
+ boolean inQuotes = false;
+ int inQuotesStart = -1;
+ boolean inArray = false;
+
+ String propertyName = null;
+ ArrayList<String> values = new ArrayList<String>();
+ for (char c:encodedData.toCharArray()) {
+ if (c == '$' && start == -1) {
+ start = index;
+ }
+ else if (c == '"') {
+ inQuotes = !inQuotes;
+ if (inQuotes && inQuotesStart == -1) {
+ inQuotesStart = index;
+ }
+ else if (!inQuotes && inQuotesStart != -1) {
+ if (inQuotesStart+1 != index) {
+ values.add(encodedData.substring(inQuotesStart+1, index));
+ }
+ else {
+ values.add(""); //$NON-NLS-1$
+ }
+ inQuotesStart = -1;
+ }
+ }
+ else if (c == '[') {
+ inArray = true;
+ }
+ else if (c == ']') {
+ inArray = false;
+ }
+ else if (c == ':' && !inQuotes && !inArray && start != -1) {
+ propertyName = encodedData.substring(start, index);
+ }
+ else if (c == ',' && !inQuotes && !inArray && start != -1) {
+ addProperty(propertyName, values);
+ propertyName = null;
+ values = new ArrayList<String>();
+ start = -1;
+ }
+ index++;
+ }
+ // add last property
+ addProperty(propertyName, values);
+ }
+
+ private void addProperty(String name, ArrayList<String> values) {
+ if (name.equals("$display")) { //$NON-NLS-1$
+ this.displayName = values.get(0);
+ }
+ else if (name.equals("$description")) { //$NON-NLS-1$
+ this.description = values.get(0);
+ }
+ else if (name.equals("$advanced")) { //$NON-NLS-1$
+ this.advanced = Boolean.parseBoolean(values.get(0));
+ }
+ else if (name.equals("$masked")) { //$NON-NLS-1$
+ this.masked = Boolean.parseBoolean(values.get(0));
+ }
+ else if (name.equals("$editable")) { //$NON-NLS-1$
+ this.editable = Boolean.parseBoolean(values.get(0));
+ }
+ else if (name.equals("$allowed")) { //$NON-NLS-1$
+ this.allowed = new ArrayList<String>(values);
+ }
+ else if (name.equals("$required")) { //$NON-NLS-1$
+ this.required = Boolean.parseBoolean(values.get(0));
+ }
+ }
+
+ public String name() {
+ return this.name;
+ }
+ public String description() {
+ return description;
+ }
+ public String display() {
+ return displayName;
+ }
+ public boolean advanced() {
+ return advanced;
+ }
+ public boolean masked() {
+ return masked;
+ }
+ public boolean readOnly() {
+ return editable;
+ }
+ public boolean required() {
+ return required;
+ }
+ public String[] allowed() {
+ if (allowed != null) {
+ return allowed.toArray(new String[allowed.size()]);
+ }
+ return new String[] {};
+ }
+ public String type() {
+ return this.type;
+ }
+ public String defaultValue() {
+ return this.defaultValue;
+ }
+}
Added: trunk/runtime/src/main/java/org/teiid/deployers/ManagedPropertyUtil.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/ManagedPropertyUtil.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/deployers/ManagedPropertyUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,89 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.deployers;
+
+import java.util.HashSet;
+
+import org.jboss.managed.api.Fields;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.DefaultFieldsImpl;
+import org.jboss.managed.plugins.ManagedPropertyImpl;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.teiid.resource.cci.TranslatorProperty;
+
+public class ManagedPropertyUtil {
+ private static final String TEIID_PROPERTY = "teiid-property"; //$NON-NLS-1$
+
+ public static ManagedProperty convert(TranslatorProperty prop) {
+ return createProperty(prop.name(), SimpleMetaType.resolve(prop.type().getName()),
+ prop.display(), prop.description(), prop.required(), prop.readOnly(), prop.defaultValue(),
+ prop.advanced(), prop.masked(), prop.allowed());
+ }
+
+ public static ManagedProperty convert(ExtendedPropertyMetadata prop) {
+ return createProperty(prop.name(), SimpleMetaType.resolve(prop.type()),
+ prop.display(), prop.description(), prop.required(), prop.readOnly(), prop.defaultValue(),
+ prop.advanced(), prop.masked(), prop.allowed());
+ }
+
+ public static ManagedProperty createProperty(String name,
+ SimpleMetaType type, String displayName, String description,
+ boolean mandatory, boolean readOnly, String defaultValue) {
+
+ DefaultFieldsImpl fields = new DefaultFieldsImpl(name);
+ fields.setDescription(description);
+ fields.setField(Fields.MAPPED_NAME,displayName);
+ fields.setMetaType(type);
+ fields.setField(Fields.MANDATORY, SimpleValueSupport.wrap(mandatory));
+ fields.setField(Fields.READ_ONLY, SimpleValueSupport.wrap(readOnly));
+ fields.setField(TEIID_PROPERTY, SimpleValueSupport.wrap(true));
+
+ if (defaultValue != null) {
+ fields.setField(Fields.DEFAULT_VALUE, SimpleValueSupport.wrap(defaultValue));
+ }
+ return new ManagedPropertyImpl(fields);
+ }
+
+ public static ManagedProperty createProperty(String name,
+ SimpleMetaType type, String displayName, String description,
+ boolean mandatory, boolean readOnly, String defaultValue, boolean advanced,
+ boolean masked, String[] allowed) {
+
+ ManagedProperty mp = createProperty(name, type, displayName, description, mandatory, readOnly, defaultValue);
+ mp.setField("advanced", SimpleValueSupport.wrap(advanced));//$NON-NLS-1$
+ mp.setField("masked", SimpleValueSupport.wrap(masked));//$NON-NLS-1$
+ if (allowed != null) {
+ HashSet<MetaValue> values = new HashSet<MetaValue>();
+ for (String value:allowed) {
+ values.add(SimpleValueSupport.wrap(value));
+ }
+ mp.setField(Fields.LEGAL_VALUES, values);
+ }
+ return mp;
+ }
+
+ public static void markAsTeiidProperty(ManagedProperty mp) {
+ mp.setField(TEIID_PROPERTY, SimpleValueSupport.wrap(true));
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/deployers/ManagedPropertyUtil.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/deployers/ObjectSerializer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,10 +30,10 @@
import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
import org.jboss.logging.Logger;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.runtime.RuntimePlugin;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.util.FileUtils;
public class ObjectSerializer {
Added: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/TranslatorDeployer.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/deployers/TranslatorDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,151 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+import javax.resource.ResourceException;
+
+import org.jboss.deployers.spi.DeploymentException;
+import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
+import org.jboss.deployers.structure.spi.DeploymentUnit;
+import org.jboss.managed.api.annotation.ManagementProperty;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+import org.teiid.dqp.internal.datamgr.impl.TranslatorRepository;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.cci.ExecutionFactory;
+import org.teiid.resource.cci.TranslatorProperty;
+import org.teiid.runtime.RuntimePlugin;
+
+import com.metamatrix.core.MetaMatrixCoreException;
+import com.metamatrix.core.util.ReflectionHelper;
+
+/**
+ * Deployer for the Translator
+ */
+public class TranslatorDeployer extends AbstractSimpleRealDeployer<TranslatorMetaData> {
+
+ private TranslatorRepository translatorRepository;
+ private VDBStatusChecker vdbChecker;
+
+ public TranslatorDeployer() {
+ super(TranslatorMetaData.class);
+ }
+
+ @Override
+ public void deploy(DeploymentUnit unit, TranslatorMetaData data) throws DeploymentException {
+
+ String translatorName = data.getName();
+
+ String executionFactoryClass = data.getExecutionFactoryClass();
+ if (executionFactoryClass != null) {
+ ExecutionFactory connector = buildTranslator(executionFactoryClass, data);
+ this.translatorRepository.addTranslator(translatorName, connector);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("translator_started", translatorName)); //$NON-NLS-1$
+ this.vdbChecker.translatorAdded(translatorName);
+ }
+ }
+
+ @Override
+ public void undeploy(DeploymentUnit unit, TranslatorMetaData data) {
+ super.undeploy(unit, data);
+
+ String translatorName = data.getName();
+
+ if (this.translatorRepository != null) {
+ this.translatorRepository.removeTranslator(translatorName);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("translator_stopped", translatorName)); //$NON-NLS-1$
+ this.vdbChecker.translatorRemoved(translatorName);
+ }
+ }
+
+ ExecutionFactory buildTranslator(String executionFactoryClass, TranslatorMetaData data) throws DeploymentException {
+ ExecutionFactory executionFactory;
+ try {
+ Object o = ReflectionHelper.create(executionFactoryClass, null, Thread.currentThread().getContextClassLoader());
+ if(!(o instanceof ExecutionFactory)) {
+ throw new DeploymentException(RuntimePlugin.Util.getString("invalid_class", executionFactoryClass));//$NON-NLS-1$
+ }
+
+ executionFactory = (ExecutionFactory)o;
+ injectProperties(executionFactory, data);
+ executionFactory.start();
+ return executionFactory;
+
+ } catch (MetaMatrixCoreException e) {
+ throw new DeploymentException(e);
+ } catch (ResourceException e) {
+ throw new DeploymentException(e);
+ } catch (InvocationTargetException e) {
+ throw new DeploymentException(e);
+ } catch (IllegalAccessException e) {
+ throw new DeploymentException(e);
+ } catch (NoSuchMethodException e) {
+ throw new DeploymentException(e);
+ }
+ }
+
+ private void injectProperties(ExecutionFactory ef, final TranslatorMetaData data) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, DeploymentException{
+ Map<Method, TranslatorProperty> props = TranslatorPropertyUtil.getTranslatorProperties(ef.getClass());
+
+ for (Method method:props.keySet()) {
+ TranslatorProperty tp = props.get(method);
+ Object value = data.getPropertyValue(tp.name());
+ if (value == null) {
+ Method[] sourceMethods = data.getClass().getMethods();
+ for (Method sm:sourceMethods) {
+ ManagementProperty mp = sm.getAnnotation(ManagementProperty.class);
+ if (mp != null && mp.name().equals(tp.name())) {
+ value = sm.invoke(data);
+ break;
+ }
+ }
+ }
+
+ if (value != null) {
+ String setter = method.getName();
+ if (method.getName().startsWith("get")) { //$NON-NLS-1$
+ setter = "set"+method.getName().substring(3);//$NON-NLS-1$
+ }
+ else if (method.getName().startsWith("is")) { //$NON-NLS-1$
+ setter = "set"+method.getName().substring(2); //$NON-NLS-1$
+ }
+ Method setterMethod = ef.getClass().getMethod(setter, method.getReturnType());
+ if (setterMethod == null) {
+ throw new DeploymentException(RuntimePlugin.Util.getString("no_set_method", setter, tp.name())); //$NON-NLS-1$
+ }
+ setterMethod.invoke(ef, value);
+ }
+ }
+ }
+
+ public void setTranslatorRepository(TranslatorRepository repo) {
+ this.translatorRepository = repo;
+ }
+
+ public void setVDBStatusChecker(VDBStatusChecker checker) {
+ this.vdbChecker = checker;
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorDeployer.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorParserDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/TranslatorParserDeployer.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/deployers/TranslatorParserDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+package org.teiid.deployers;
+
+import java.io.InputStream;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.sax.SAXSource;
+
+import org.jboss.deployers.vfs.spi.deployer.AbstractVFSParsingDeployer;
+import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit;
+import org.jboss.util.xml.JBossEntityResolver;
+import org.jboss.virtual.VirtualFile;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+
+public class TranslatorParserDeployer extends AbstractVFSParsingDeployer<TranslatorMetaData> {
+ public static final String TRANSLATOR_SUFFIX = "-translator.xml"; //$NON-NLS-1$
+
+ public TranslatorParserDeployer() {
+ super(TranslatorMetaData.class);
+ setIncludeDeploymentFile(true);
+ setSuffix(TRANSLATOR_SUFFIX);
+ }
+
+ @Override
+ protected TranslatorMetaData parse(VFSDeploymentUnit unit, VirtualFile file, TranslatorMetaData root) throws Exception {
+ JAXBContext context = JAXBContext.newInstance(new Class[] {TranslatorMetaData.class});
+ Unmarshaller um = context.createUnmarshaller();
+ InputStream is = file.openStream();
+
+ try{
+ InputSource input = new InputSource(is);
+ input.setSystemId(file.toURI().toString());
+ XMLReader reader = XMLReaderFactory.createXMLReader();
+ reader.setEntityResolver(new JBossEntityResolver());
+ SAXSource source = new SAXSource(reader, input);
+ JAXBElement<TranslatorMetaData> elem = um.unmarshal(source, TranslatorMetaData.class);
+ TranslatorMetaData deployment = elem.getValue();
+ deployment.setName(file.getName().substring(0, (file.getName().length()-TRANSLATOR_SUFFIX.length())));
+ return deployment;
+ }
+ finally {
+ if (is != null)
+ is.close();
+ }
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorParserDeployer.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorPropertyUtil.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/TranslatorPropertyUtil.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/deployers/TranslatorPropertyUtil.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,56 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.teiid.resource.cci.TranslatorProperty;
+
+public class TranslatorPropertyUtil {
+
+ public static Map<Method, TranslatorProperty> getTranslatorProperties(Class<?> attachmentClass) {
+ Map<Method, TranslatorProperty> props = new HashMap<Method, TranslatorProperty>();
+ buildTranslatorProperties(attachmentClass, props);
+ return props;
+ }
+
+ private static void buildTranslatorProperties(Class<?> attachmentClass, Map<Method, TranslatorProperty> props){
+ Method[] methods = attachmentClass.getMethods();
+ for (Method m:methods) {
+ TranslatorProperty tp = m.getAnnotation(TranslatorProperty.class);
+ if (tp != null) {
+ props.put(m, tp);
+ }
+ }
+ // Now look at the base interfaces
+ Class[] baseInterfaces = attachmentClass.getInterfaces();
+ for (Class clazz:baseInterfaces) {
+ buildTranslatorProperties(clazz, props);
+ }
+ Class superClass = attachmentClass.getSuperclass();
+ if (superClass != null) {
+ buildTranslatorProperties(superClass, props);
+ }
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/deployers/TranslatorPropertyUtil.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/deployers/VDBDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -26,9 +26,6 @@
import java.util.LinkedHashMap;
import java.util.List;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
import org.jboss.deployers.spi.DeploymentException;
import org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer;
import org.jboss.deployers.structure.spi.DeploymentUnit;
@@ -38,23 +35,26 @@
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.SourceMappingMetadata;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.metadata.runtime.MetadataStore;
import org.teiid.dqp.internal.cache.DQPContextCache;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
+import org.teiid.dqp.internal.datamgr.impl.TranslatorRepository;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.metadata.TransformationMetadata.Resource;
import org.teiid.metadata.index.IndexMetadataFactory;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.cci.ExecutionFactory;
import org.teiid.runtime.RuntimePlugin;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.CoreConstants;
import com.metamatrix.core.util.FileUtils;
public class VDBDeployer extends AbstractSimpleRealDeployer<VDBMetaData> {
private VDBRepository vdbRepository;
private ConnectorManagerRepository connectorManagerRepository;
+ private TranslatorRepository translatorRepository;
private DQPContextCache contextCache;
private ObjectSerializer serializer;
@@ -62,6 +62,7 @@
super(VDBMetaData.class);
setInput(VDBMetaData.class);
setOutput(VDBMetaData.class);
+ setRelativeOrder(3001); // after the data sources
}
@Override
@@ -83,6 +84,9 @@
// 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
+ createConnectorManagers(deployment);
+
// if store is null and vdb dynamic vdb then try to get the metadata
if (store == null && deployment.isDynamic()) {
MetadataStoreGroup dynamicStore = new MetadataStoreGroup();
@@ -138,6 +142,24 @@
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(VDBMetaData deployment) {
+ for (Model model:deployment.getModels()) {
+ if (model.getName().equals(CoreConstants.SYSTEM_MODEL)){
+ continue;
+ }
+ for (String source:model.getSourceNames()) {
+ if (this.connectorManagerRepository.getConnectorManager(source) == null) {
+ ConnectorManager cm = new ConnectorManager(model.getSourceTranslatorName(source), model.getSourceConnectionJndiName(source)) {
+ protected ExecutionFactory getExecutionFactory() {
+ return VDBDeployer.this.translatorRepository.getTranslator(getTranslatorName());
+ }
+ };
+ this.connectorManagerRepository.addConnectorManager(source, cm);
+ }
+ }
+ }
+ }
+
private boolean validateSources(VDBMetaData deployment) {
boolean valid = true;
for(Model m:deployment.getModels()) {
@@ -147,14 +169,12 @@
if (mapping.getName().equals(CoreConstants.SYSTEM_MODEL)) {
continue;
}
- try {
- InitialContext ic = new InitialContext();
- ic.lookup(mapping.getJndiName());
- } catch (NamingException e) {
+ ConnectorManager cm = this.connectorManagerRepository.getConnectorManager(mapping.getName());
+ String msg = cm.getStausMessage();
+ if (msg != null && msg.length() > 0) {
valid = false;
- String msg = RuntimePlugin.Util.getString("jndi_not_found", deployment.getName(), deployment.getVersion(), mapping.getJndiName(),mapping.getName()); //$NON-NLS-1$
- model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), msg);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
+ model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), cm.getStausMessage());
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, cm.getStausMessage());
}
}
}
@@ -169,6 +189,19 @@
public void undeploy(DeploymentUnit unit, VDBMetaData deployment) {
super.undeploy(unit, deployment);
+ // there is chance that two different VDBs using the same source name, and their
+ // connector manager is removed. should we prefix vdb name??
+ for (Model model:deployment.getModels()) {
+ if (model.getName().equals(CoreConstants.SYSTEM_MODEL)){
+ continue;
+ }
+ for (String source:model.getSourceNames()) {
+ if (this.connectorManagerRepository.getConnectorManager(source) != null) {
+ this.connectorManagerRepository.removeConnectorManager(source);
+ }
+ }
+ }
+
if (this.vdbRepository != null) {
this.vdbRepository.removeVDB(deployment.getName(), deployment.getVersion());
}
@@ -232,7 +265,7 @@
Exception exception = null;
for (String sourceName: model.getSourceNames()) {
- ConnectorManager cm = this.connectorManagerRepository.getConnectorManager(model.getSourceJndiName(sourceName));
+ ConnectorManager cm = this.connectorManagerRepository.getConnectorManager(sourceName);
if (cm == null) {
continue;
}
@@ -258,4 +291,8 @@
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;
+ }
}
Modified: trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/deployers/VDBParserDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -44,13 +44,13 @@
import org.teiid.adminapi.Model;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.metadata.index.IndexConstants;
import org.teiid.metadata.index.IndexMetadataFactory;
import org.teiid.runtime.RuntimePlugin;
import org.xml.sax.SAXException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.CoreConstants;
import com.metamatrix.core.vdb.VdbConstants;
@@ -171,7 +171,7 @@
system.setName(CoreConstants.SYSTEM_MODEL);
system.setVisible(true);
system.setModelType(Model.Type.PHYSICAL);
- system.addSourceMapping(CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL);
+ system.addSourceMapping(CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL, CoreConstants.SYSTEM_MODEL);
system.setSupportsMultiSourceBindings(false);
vdb.addModel(system);
@@ -198,7 +198,7 @@
}
ManagedObject mo = this.mof.initManagedObject(m, ModelMetaData.class, m.getName(),m.getName());
if (mo == null) {
- throw new DeploymentException("could not create managed object");
+ throw new DeploymentException("could not create managed object"); //$NON-NLS-1$
}
managedObjects.put(mo.getName(), mo);
}
Modified: trunk/runtime/src/main/java/org/teiid/deployers/VDBStatusChecker.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/VDBStatusChecker.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/deployers/VDBStatusChecker.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -21,22 +21,46 @@
*/
package org.teiid.deployers;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
import org.teiid.adminapi.Model;
import org.teiid.adminapi.VDB;
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.dqp.internal.datamgr.impl.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.impl.ConnectorManagerRepository;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.runtime.RuntimePlugin;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
public class VDBStatusChecker {
private VDBRepository vdbRepository;
+ private ConnectorManagerRepository connectorManagerRepository;
- public void connectorAdded(String connectorName) {
+ public void translatorAdded(String translatorName) {
+ resourceAdded(translatorName, true);
+ }
+
+ public void translatorRemoved(String translatorName) {
+ resourceremoved(translatorName, true);
+ }
+
+ public void dataSourceAdded(String dataSourceName) {
+ resourceAdded(dataSourceName, false);
+ }
+
+ public void dataSourceRemoved(String dataSourceName) {
+ resourceremoved(dataSourceName, false);
+ }
+
+ public void setVDBRepository(VDBRepository repo) {
+ this.vdbRepository = repo;
+ }
+
+ public void setConnectorManagerRepository(ConnectorManagerRepository repo) {
+ this.connectorManagerRepository = repo;
+ }
+
+ public void resourceAdded(String resourceName, boolean translator) {
for (VDBMetaData vdb:this.vdbRepository.getVDBs()) {
if (vdb.getStatus() == VDB.Status.ACTIVE || vdb.isPreview()) {
continue;
@@ -48,27 +72,15 @@
continue;
}
- boolean inUse = false;
- for (String sourceName:model.getSourceNames()) {
- if (connectorName.equals(model.getSourceJndiName(sourceName))) {
- inUse = true;
- }
- }
-
- if (inUse) {
+ String sourceName = getSourceName(resourceName, model, translator);
+ if (sourceName != null) {
+ ConnectorManager cm = this.connectorManagerRepository.getConnectorManager(sourceName);
model.clearErrors();
- for (String sourceName:model.getSourceNames()) {
- if (!connectorName.equals(model.getSourceJndiName(sourceName))) {
- try {
- InitialContext ic = new InitialContext();
- ic.lookup(model.getSourceJndiName(sourceName));
- } catch (NamingException e) {
- String msg = RuntimePlugin.Util.getString("jndi_not_found", vdb.getName(), vdb.getVersion(), model.getSourceJndiName(sourceName), sourceName); //$NON-NLS-1$
- model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), msg);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
- }
- }
- }
+ String status = cm.getStausMessage();
+ if (status != null && status.length() > 0) {
+ model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), status);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, status);
+ }
}
}
@@ -85,31 +97,45 @@
vdb.setStatus(VDB.Status.ACTIVE);
LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_activated",vdb.getName(), vdb.getVersion())); //$NON-NLS-1$
}
-
}
}
-
- public void connectorRemoved(String connectorName) {
+
+ public void resourceremoved(String resourceName, boolean translator) {
for (VDBMetaData vdb:this.vdbRepository.getVDBs()) {
if (vdb.isPreview()) {
continue;
}
+
for (Model m:vdb.getModels()) {
ModelMetaData model = (ModelMetaData)m;
- for (String sourceName:model.getSourceNames()) {
- if (connectorName.equals(model.getSourceJndiName(sourceName))) {
- vdb.setStatus(VDB.Status.INACTIVE);
- String msg = RuntimePlugin.Util.getString("jndi_not_found", vdb.getName(), vdb.getVersion(), model.getSourceJndiName(sourceName), sourceName); //$NON-NLS-1$
- model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), msg);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
- LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_inactivated",vdb.getName(), vdb.getVersion())); //$NON-NLS-1$
+
+ String sourceName = getSourceName(resourceName, model, translator);
+ if (sourceName != null) {
+ vdb.setStatus(VDB.Status.INACTIVE);
+ String msg = null;
+ if (translator) {
+ msg = RuntimePlugin.Util.getString("translator_not_found", vdb.getName(), vdb.getVersion(), model.getSourceTranslatorName(sourceName)); //$NON-NLS-1$
}
+ else {
+ msg = RuntimePlugin.Util.getString("datasource_not_found", vdb.getName(), vdb.getVersion(), model.getSourceTranslatorName(sourceName)); //$NON-NLS-1$
+ }
+ model.addError(ModelMetaData.ValidationError.Severity.ERROR.name(), msg);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, msg);
+ LogManager.logInfo(LogConstants.CTX_RUNTIME, RuntimePlugin.Util.getString("vdb_inactivated",vdb.getName(), vdb.getVersion())); //$NON-NLS-1$
}
+ }
+ }
+ }
+
+ private String getSourceName(String translatorName, ModelMetaData model, boolean translator) {
+ for (String sourceName:model.getSourceNames()) {
+ if (translator && translatorName.equals(model.getSourceTranslatorName(sourceName))) {
+ return sourceName;
}
+ else if (translatorName.equals(model.getSourceConnectionJndiName(sourceName))) {
+ return sourceName;
+ }
}
- }
-
- public void setVDBRepository(VDBRepository repo) {
- this.vdbRepository = repo;
- }
+ return null;
+ }
}
Modified: trunk/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/logging/CommonsLogManagerAdapter.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -24,8 +24,6 @@
import org.apache.commons.logging.Log;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
/**
* This class is bridge for hooking LogManager into systems that use apache commons logging. In the Teiid
Modified: trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/logging/Log4jListener.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,8 +25,6 @@
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
-import com.metamatrix.common.log.LogListener;
-import com.metamatrix.common.log.MessageLevel;
/**
* Log4J Listener
Modified: trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -47,14 +47,14 @@
import org.teiid.deployers.VDBRepository;
import org.teiid.deployers.VirtualDatabaseException;
import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.net.ServerConnection;
import org.teiid.net.TeiidURL;
import org.teiid.runtime.RuntimePlugin;
import org.teiid.security.Credentials;
import org.teiid.security.SecurityHelper;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.util.ArgCheck;
import com.metamatrix.dqp.service.SessionService;
import com.metamatrix.dqp.service.SessionServiceException;
Modified: trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -38,12 +38,12 @@
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.runtime.RuntimePlugin;
import org.teiid.security.Credentials;
import org.teiid.security.SecurityHelper;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
/**
* This class serves as the primary implementation of the
Added: trunk/runtime/src/main/java/org/teiid/templates/TranslatorDeploymentTemplate.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/templates/TranslatorDeploymentTemplate.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/templates/TranslatorDeploymentTemplate.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,110 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.templates;
+
+import java.io.File;
+import java.io.FileWriter;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+
+import org.jboss.deployers.spi.management.DeploymentTemplate;
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedObject;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.factory.ManagedObjectFactory;
+import org.jboss.virtual.VFS;
+import org.jboss.virtual.VirtualFile;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+import org.teiid.deployers.TranslatorParserDeployer;
+
+/**
+ * Translator template writer and deployer
+ */
+public class TranslatorDeploymentTemplate implements DeploymentTemplate {
+
+ private DeploymentTemplateInfo info;
+ private ManagedObjectFactory mof;
+
+ public String getDeploymentName(String deploymentBaseName) {
+ if (deploymentBaseName == null)
+ throw new IllegalArgumentException("Null base name.");//$NON-NLS-1$
+
+ if(deploymentBaseName.endsWith(TranslatorParserDeployer.TRANSLATOR_SUFFIX) == false)
+ deploymentBaseName = deploymentBaseName + TranslatorParserDeployer.TRANSLATOR_SUFFIX;
+
+ return deploymentBaseName;
+ }
+
+ public VirtualFile applyTemplate(DeploymentTemplateInfo sourceInfo) throws Exception {
+ File dsXml = File.createTempFile(getClass().getSimpleName(),TranslatorParserDeployer.TRANSLATOR_SUFFIX);
+ writeTemplate(dsXml, sourceInfo);
+ return VFS.getRoot(dsXml.toURI());
+ }
+
+ private void writeTemplate(File dsXml, DeploymentTemplateInfo values) throws Exception {
+
+ // The management framework, will update the attachment the managed property value changes.
+ // that way the translator is configured.
+ TranslatorMetaData translator = new TranslatorMetaData();
+ this.mof.setInstanceClassFactory(TranslatorMetaData.class, new TranslatorMetadataICF(this.mof));
+ ManagedObject mo = mof.initManagedObject(translator, "teiid", "translator"); //$NON-NLS-1$ //$NON-NLS-2$
+
+ for (ManagedProperty mp : values.getProperties().values()) {
+ ManagedProperty dsProp = mo.getProperty(mp.getName());
+ if (dsProp != null) {
+ if (mp.getValue() != null) {
+ dsProp.setValue(mp.getValue());
+ }
+ }
+ }
+
+ // Now use JAXB and write the file.
+ Class[] classes = { TranslatorMetaData.class };
+ JAXBContext context = JAXBContext.newInstance(classes);
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
+
+ FileWriter fw = null;
+ try {
+ fw = new FileWriter(dsXml);
+ marshaller.marshal(translator, fw);
+ } finally {
+ if (fw != null) {
+ fw.close();
+ }
+ }
+ }
+
+ @Override
+ public DeploymentTemplateInfo getInfo() {
+ return info;
+ }
+
+ public void setInfo(DeploymentTemplateInfo info) {
+ this.info = info;
+ }
+
+ public void setManagedObjectFactory(ManagedObjectFactory mof) {
+ this.mof = mof;
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/templates/TranslatorDeploymentTemplate.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/runtime/src/main/java/org/teiid/templates/TranslatorMetadataICF.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/templates/TranslatorMetadataICF.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/templates/TranslatorMetadataICF.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,128 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.templates;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.jboss.beans.info.spi.BeanInfo;
+import org.jboss.beans.info.spi.PropertyInfo;
+import org.jboss.managed.api.Fields;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.factory.ManagedObjectFactory;
+import org.jboss.managed.plugins.factory.AbstractInstanceClassFactory;
+import org.jboss.metadata.spi.MetaData;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.teiid.adminapi.impl.PropertyMetadata;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+
+public class TranslatorMetadataICF extends AbstractInstanceClassFactory<TranslatorMetaData> {
+
+ public TranslatorMetadataICF() {
+ super();
+ }
+
+ public TranslatorMetadataICF(ManagedObjectFactory mof) {
+ super(mof);
+ }
+
+ @Override
+ public MetaValue getValue(BeanInfo beanInfo, ManagedProperty property, MetaData metaData, TranslatorMetaData attachment) {
+ // Get the property name
+ String propertyName = property.getMappedName();
+ if (propertyName == null)
+ propertyName = property.getName();
+
+ // Get the property info
+ PropertyInfo propertyInfo = property.getField(Fields.PROPERTY_INFO, PropertyInfo.class);
+ if (propertyInfo == null)
+ propertyInfo = beanInfo.getProperty(propertyName);
+
+ // Check if the property is readable
+ if (propertyInfo != null && propertyInfo.isReadable() == false)
+ return null;
+
+ MetaValue value = null;
+ if ("translator-property".equals(property.getName())) { //$NON-NLS-1$
+ MapCompositeValueSupport mapValue = new MapCompositeValueSupport(SimpleMetaType.STRING);
+ List<PropertyMetadata> list = attachment.getJAXBProperties();
+ if (list != null) {
+ for (PropertyMetadata prop : list) {
+ String name = prop.getName();
+ MetaValue svalue = SimpleValueSupport.wrap(prop.getValue());
+ mapValue.put(name, svalue);
+// MetaValue stype = SimpleValueSupport.wrap(prop.getType());
+// mapValue.put(name + ".type", stype);
+ }
+ }
+ value = mapValue;
+ } else {
+ value = super.getValue(beanInfo, property, metaData, attachment);
+ }
+ return value;
+ }
+
+ @Override
+ protected Object unwrapValue(BeanInfo beanInfo, ManagedProperty property, MetaValue value) {
+ Object unwrapValue = null;
+ if ("translator-property".equals(property.getName())) { //$NON-NLS-1$
+
+ if ((value instanceof MapCompositeValueSupport) == false) {
+ return super.unwrapValue(beanInfo, property, value);
+ }
+
+ MapCompositeValueSupport mapValue = (MapCompositeValueSupport) value;
+
+ List<PropertyMetadata> list = new ArrayList<PropertyMetadata>();
+ for (String name : mapValue.getMetaType().keySet()) {
+// // Ignore the type we've added before
+// if (name.endsWith(".type"))
+// continue;
+
+ PropertyMetadata prop = new PropertyMetadata();
+ prop.setName(name);
+ String svalue = (String) getMetaValueFactory().unwrap(mapValue.get(name));
+ prop.setValue(svalue);
+
+// String nameType = name + ".type";
+// MetaValue typeValue = mapValue.get(nameType);
+// if (typeValue != null) {
+// String type = (String) getMetaValueFactory().unwrap(typeValue);
+// prop.setType(type);
+// }
+ list.add(prop);
+ }
+ unwrapValue = list;
+ } else {
+ unwrapValue = super.unwrapValue(beanInfo, property, value);
+ }
+ return unwrapValue;
+ }
+
+ @Override
+ public Class<TranslatorMetaData> getType() {
+ return TranslatorMetaData.class;
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/templates/TranslatorMetadataICF.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfo.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfo.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfo.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.templates;
+
+import java.util.Map;
+
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.BasicDeploymentTemplateInfo;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.teiid.deployers.ManagedPropertyUtil;
+import org.teiid.resource.cci.TranslatorProperty;
+
+/**
+ * This class defines the template for all the translator classes. Each Translator's class
+ * defines its properties through {@link TranslatorProperty} annotation. This class need to
+ * present them as template properties that can be managed.
+ */
+public class TranslatorTemplateInfo extends BasicDeploymentTemplateInfo {
+
+ private static final long serialVersionUID = 9066758787789280783L;
+ static final String TEMPLATE_NAME = "template-name"; //$NON-NLS-1$
+
+
+ public TranslatorTemplateInfo(String name, String description, Map<String, ManagedProperty> properties) {
+ super(name, description, properties);
+ }
+
+ public void start() {
+ populate();
+ }
+
+ @Override
+ public TranslatorTemplateInfo copy() {
+ TranslatorTemplateInfo copy = new TranslatorTemplateInfo(getName(), getDescription(), getProperties());
+ super.copy(copy);
+ copy.populate();
+
+ return copy;
+ }
+
+ private void populate() {
+ addProperty(buildTemplateProperty(getName()));
+ }
+
+ static ManagedProperty buildTemplateProperty(String name) {
+ return ManagedPropertyUtil.createProperty(TEMPLATE_NAME,SimpleMetaType.STRING,
+ "Template Name", "The Name of the Teiid Connector Template", true, true, name);//$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfo.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfoFactory.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfoFactory.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfoFactory.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.templates;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedProperty;
+import org.teiid.deployers.ManagedPropertyUtil;
+import org.teiid.deployers.TranslatorPropertyUtil;
+import org.teiid.resource.cci.TranslatorProperty;
+
+public class TranslatorTemplateInfoFactory {
+
+ /**
+ * Create a DeploymentTemplateInfo by scanning the metadata attachment class
+ * for ManagementProperty annotations.
+ *
+ * @param infoClass - the DeploymentTemplateInfo implementation to use. Must have a ctor with sig (String,String,Map).
+ * @param attachmentClass - the metadata class to scan for ManagementProperty annotations
+ * @param name - the template name
+ * @param description - the template description
+ * @return the DeploymentTemplateInfo instance
+ * @throws Exception on failure to create the DeploymentTemplateInfo
+ */
+ public DeploymentTemplateInfo createTemplateInfo(Class<? extends DeploymentTemplateInfo> infoClass, Class<?> attachmentClass, String name, String description) throws Exception {
+
+ Map<Method, TranslatorProperty> props = TranslatorPropertyUtil.getTranslatorProperties(attachmentClass);
+
+ Map<String, ManagedProperty> infoProps = new HashMap<String, ManagedProperty>();
+
+ Collection<TranslatorProperty> propertyInfos = props.values();
+ if (propertyInfos != null && !propertyInfos.isEmpty()) {
+ for (TranslatorProperty propertyInfo : propertyInfos) {
+ ManagedProperty mp = ManagedPropertyUtil.convert(propertyInfo);
+ infoProps.put(mp.getName(), mp);
+ }
+ }
+ Class<?>[] parameterTypes = { String.class, String.class, Map.class };
+ Constructor<? extends DeploymentTemplateInfo> ctor = infoClass.getConstructor(parameterTypes);
+ DeploymentTemplateInfo info = ctor.newInstance(name, description,infoProps);
+ return info;
+ }
+}
Property changes on: trunk/runtime/src/main/java/org/teiid/templates/TranslatorTemplateInfoFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/transport/LogonImpl.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,13 +34,13 @@
import org.teiid.client.security.SessionToken;
import org.teiid.client.util.ResultsFuture;
import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.net.TeiidURL;
import org.teiid.security.Credentials;
import com.metamatrix.api.exception.ComponentNotFoundException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.CoreConstants;
import com.metamatrix.dqp.service.SessionService;
import com.metamatrix.dqp.service.SessionServiceException;
Modified: trunk/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -51,12 +51,12 @@
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.net.NetPlugin;
import org.teiid.net.socket.ObjectChannel;
import com.metamatrix.common.buffer.StorageManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
/**
* Main class for creating Netty Nio Channels
Modified: trunk/runtime/src/main/java/org/teiid/transport/ServerWorkItem.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/ServerWorkItem.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/transport/ServerWorkItem.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -34,6 +34,8 @@
import org.teiid.adminapi.AdminProcessingException;
import org.teiid.client.util.ResultsFuture;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
import org.teiid.net.socket.Message;
import org.teiid.net.socket.ServiceInvocationStruct;
import org.teiid.runtime.RuntimePlugin;
@@ -41,8 +43,6 @@
import com.metamatrix.api.exception.ExceptionHolder;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
import com.metamatrix.common.util.crypto.CryptoException;
import com.metamatrix.core.MetaMatrixRuntimeException;
Modified: trunk/runtime/src/main/java/org/teiid/transport/SocketClientInstance.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SocketClientInstance.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/transport/SocketClientInstance.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -28,15 +28,15 @@
import org.teiid.client.security.ILogon;
import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import org.teiid.net.CommunicationException;
import org.teiid.net.NetPlugin;
import org.teiid.net.socket.Handshake;
import org.teiid.net.socket.Message;
import org.teiid.net.socket.ObjectChannel;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.util.crypto.CryptoException;
import com.metamatrix.common.util.crypto.Cryptor;
import com.metamatrix.common.util.crypto.DhKeyGenerator;
Modified: trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -30,14 +30,14 @@
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import org.teiid.net.socket.ObjectChannel;
import org.teiid.runtime.RuntimePlugin;
import org.teiid.transport.ChannelListener.ChannelListenerFactory;
import com.metamatrix.common.buffer.StorageManager;
-import com.metamatrix.common.log.LogConstants;
-import com.metamatrix.common.log.LogManager;
-import com.metamatrix.common.log.MessageLevel;
import com.metamatrix.common.util.ApplicationInfo;
import com.metamatrix.core.util.NamedThreadFactory;
Modified: trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties
===================================================================
--- trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/runtime/src/main/resources/org/teiid/runtime/i18n.properties 2010-05-07 16:24:50 UTC (rev 2103)
@@ -283,7 +283,6 @@
vdb_delete_failed=Failed to delete the cached metadata files due to:
vdb_deployed=VDB "{0}" deployed in {1} state.
vdb_undeployed=VDB "{0}" undeployed.
-jndi_not_found=For {0}.{1} VDB, JNDI resource "{2}" not found for Source Name "{3}"
system_vdb_load_error=System.vdb needs to be loaded before any other VDBs.
fail_to_deploy="{0}" Can not be deployed because model "{1}" is not fully configured.
failed_to_retrive_metadata="{0}" Can not be deployed because model "{1}" can not retrieve metadata.
@@ -295,6 +294,12 @@
invalid_udf_file=No "path" information found to load the FUNCTION model {0}; FUNCTION model must have path information.
failed_matadata_load=Failed to load metadata for VDB {0}.{1}
vdb_not_found=VDB {0}.{1} not found deployed.
-jndi_not_found=For {0}.{1} VDB, JNDI resource "{2}" not found for Source Name "{3}"
+translator_not_found=For {0}.{1} VDB, Translator "{2}" not found.
+datasource_not_found=For {0}.{1} VDB, Data Source "{2}" not found.
vdb_activated={0}.{1} status has been changed to active
-vdb_inactivated={0}.{1} status has been changed to inactive. Check the connector mappings!
+vdb_inactivated={0}.{1} status has been changed to inactive. Check the required translators and data sources!
+translator_started=Teiid translator "{0}" has started.
+invalid_class={0} invalid type of class specified. Must be of type org.teiid.connector.api.Connector
+class_not_found=Class {0} not found.
+translator_stopped=Teiid translator "{0}" stopped
+no_set_method=No {0} method found for translator property {1}
\ No newline at end of file
Copied: trunk/runtime/src/test/java/org/teiid/deployers/TestExtendedPropertyMetadata.java (from rev 2076, trunk/jboss-integration/src/test/java/org/teiid/templates/connector/TestExtendedPropertyMetadata.java)
===================================================================
--- trunk/runtime/src/test/java/org/teiid/deployers/TestExtendedPropertyMetadata.java (rev 0)
+++ trunk/runtime/src/test/java/org/teiid/deployers/TestExtendedPropertyMetadata.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -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.deployers;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import junit.framework.Assert;
+
+import org.junit.Test;
+import org.teiid.deployers.ExtendedPropertyMetadata;
+
+@SuppressWarnings("nls")
+public class TestExtendedPropertyMetadata {
+
+ @Test
+ public void testDefault() {
+ ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("x", "java.lang.String", "some-name", null);
+
+ Assert.assertEquals("some-name", metadata.display());
+ Assert.assertEquals(null, metadata.description());
+ Assert.assertEquals(false, metadata.advanced());
+ Assert.assertEquals(false, metadata.required());
+ Assert.assertEquals(false, metadata.masked());
+ Assert.assertEquals(true , metadata.readOnly());
+ }
+
+ @Test
+ public void testFormatted() {
+ ArrayList<String> allowed = new ArrayList<String>();
+ allowed.add("get");
+ allowed.add("post");
+
+ ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("x", "java.lang.String", "{$display:\"Is Immutable\",$description:\"True if the source never changes.\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}", null);
+
+ Assert.assertEquals("Is Immutable", metadata.display());
+ Assert.assertEquals("True if the source never changes.", metadata.description());
+ Assert.assertEquals(true, metadata.advanced());
+ Assert.assertEquals(true, metadata.required());
+ Assert.assertEquals(false, metadata.masked());
+ Assert.assertEquals(true , metadata.readOnly());
+ Assert.assertEquals(allowed , Arrays.asList(metadata.allowed()));
+ }
+
+ @Test
+ public void testFormattedExtraCommasAndColons() {
+ ArrayList<String> allowed = new ArrayList<String>();
+ allowed.add("get");
+ allowed.add("post");
+
+ ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("x", "java.lang.String","{$display:\"Is Immu:table\",$description:\"True if the, source never changes.\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}", null);
+
+ Assert.assertEquals("Is Immu:table", metadata.display());
+ Assert.assertEquals("True if the, source never changes.", metadata.description());
+ Assert.assertEquals(true, metadata.advanced());
+ Assert.assertEquals(true, metadata.required());
+ Assert.assertEquals(false, metadata.masked());
+ Assert.assertEquals(true , metadata.readOnly());
+ Assert.assertEquals(allowed , Arrays.asList(metadata.allowed()));
+ }
+
+ @Test
+ public void testBlankProperties() {
+ ArrayList<String> allowed = new ArrayList<String>();
+ allowed.add("get");
+ allowed.add("post");
+
+ ExtendedPropertyMetadata metadata = new ExtendedPropertyMetadata("x", "java.lang.String","{$display:\"Is Immutable\",$description:\"\",$allowed:[\"get\",\"post\"], $required:\"true\",$advanced:\"true\"}", null);
+
+ Assert.assertEquals("Is Immutable", metadata.display());
+ Assert.assertEquals("", metadata.description());
+ Assert.assertEquals(true, metadata.advanced());
+ Assert.assertEquals(true, metadata.required());
+ Assert.assertEquals(false, metadata.masked());
+ Assert.assertEquals(true , metadata.readOnly());
+ Assert.assertEquals(allowed , Arrays.asList(metadata.allowed()));
+ }
+}
Added: trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java
===================================================================
--- trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java (rev 0)
+++ trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -0,0 +1,60 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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 org.junit.Test;
+import org.teiid.adminapi.impl.TranslatorMetaData;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.TranslatorProperty;
+import static org.junit.Assert.*;
+
+@SuppressWarnings("nls")
+public class TestTranslatorDeployer {
+
+ @Test
+ public void testBuildExecutionFactory() throws Exception {
+ TranslatorMetaData tm = new TranslatorMetaData();
+
+ tm.setCapabilitiesClass("capabilities");
+ tm.setXaCapable(true);
+ tm.addProperty("my-property", "correctly-assigned");
+
+ TranslatorDeployer td = new TranslatorDeployer();
+ MyTranslator my = (MyTranslator)td.buildTranslator(MyTranslator.class.getName(), tm);
+
+ assertEquals("capabilities", my.getCapabilitiesClass());
+ assertEquals("correctly-assigned", my.getMyProperty());
+ }
+
+ public static class MyTranslator extends BasicExecutionFactory {
+ String mine;
+
+ @TranslatorProperty(name="my-property")
+ public String getMyProperty() {
+ return mine;
+ }
+
+ public void setMyProperty(String value) {
+ this.mine = value;
+ }
+ }
+}
Property changes on: trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/MockConnector.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/MockConnector.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/MockConnector.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -5,15 +5,6 @@
import junit.framework.TestCase;
import org.mockito.Mockito;
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.api.ProcedureExecution;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.basic.BasicConnection;
-import org.teiid.connector.basic.BasicConnector;
-import org.teiid.connector.basic.BasicConnectorCapabilities;
import org.teiid.connector.language.Call;
import org.teiid.connector.language.ColumnReference;
import org.teiid.connector.language.DerivedColumn;
@@ -21,112 +12,108 @@
import org.teiid.connector.language.QueryExpression;
import org.teiid.connector.metadata.runtime.BaseColumn.NullType;
import org.teiid.connector.metadata.runtime.Column.SearchType;
+import org.teiid.resource.ConnectorException;
+import org.teiid.resource.adapter.BasicConnectorCapabilities;
+import org.teiid.resource.adapter.BasicExecutionFactory;
+import org.teiid.resource.cci.ConnectorCapabilities;
+import org.teiid.resource.cci.ExecutionContext;
+import org.teiid.resource.cci.ProcedureExecution;
+import org.teiid.resource.cci.ResultSetExecution;
-public class MockConnector extends BasicConnector {
+public class MockConnector extends BasicExecutionFactory {
@Override
public ConnectorCapabilities getCapabilities() {
return new BasicConnectorCapabilities();
}
+
@Override
- public Connection getConnection() throws ConnectorException {
- return new BasicConnection() {
- @Override
- public void close() {
-
- }
-
- @Override
- public ProcedureExecution createProcedureExecution(
- Call procedure, ExecutionContext executionContext,
- RuntimeMetadata metadata) throws ConnectorException {
- Properties props = new Properties();
- props.setProperty("customBehaviour", "SkipExecute");//$NON-NLS-1$ //$NON-NLS-2$
-
- AbstractMetadataRecord metaObject = procedure.getMetadataObject();
-
- TestCase.assertEquals("AnyModel.ProcedureB",procedure.getProcedureName()); //$NON-NLS-1$
- TestCase.assertEquals("PROC", metaObject.getNameInSource()); //$NON-NLS-1$
- TestCase.assertEquals(props, metaObject.getProperties());
- ProcedureExecution exec = Mockito.mock(ProcedureExecution.class);
- Mockito.stub(exec.next()).toReturn(null);
- return exec;
- }
-
- @Override
- public ResultSetExecution createResultSetExecution(
- QueryExpression query, ExecutionContext executionContext,
- RuntimeMetadata metadata) throws ConnectorException {
- Properties groupProps = new Properties();
- groupProps.setProperty("customName", "CustomTableA");//$NON-NLS-1$ //$NON-NLS-2$
- NamedTable group = (NamedTable)query.getProjectedQuery().getFrom().get(0);
- AbstractMetadataRecord groupMD = group.getMetadataObject();
- TestCase.assertEquals(groupProps, groupMD.getProperties());
-
-
- DerivedColumn symbl = query.getProjectedQuery().getDerivedColumns().get(0);
- ColumnReference element = (ColumnReference)symbl.getExpression();
- Column elementMD = element.getMetadataObject();
-
- Properties elementProps = new Properties();
- elementProps.setProperty("customPosition", "11");//$NON-NLS-1$ //$NON-NLS-2$
-
- TestCase.assertEquals(0, elementMD.getLength());
- TestCase.assertEquals("Foo", elementMD.getDefaultValue()); //$NON-NLS-1$
- TestCase.assertEquals("TrimNulls", elementMD.getFormat()); //$NON-NLS-1$
- TestCase.assertEquals(String.class, elementMD.getJavaType());
- TestCase.assertEquals(null, elementMD.getMaximumValue());
- TestCase.assertEquals(null, elementMD.getMinimumValue());
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#anySimpleType", elementMD.getBaseTypeID()); //$NON-NLS-1$
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#string", elementMD.getPrimitiveTypeID()); //$NON-NLS-1$
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#string", elementMD.getDatatypeID()); //$NON-NLS-1$
- TestCase.assertEquals("COLUMN1", elementMD.getNameInSource()); //$NON-NLS-1$
- TestCase.assertEquals("STR", elementMD.getNativeType()); //$NON-NLS-1$
- TestCase.assertEquals(NullType.Nullable, elementMD.getNullType());
- TestCase.assertEquals(0, elementMD.getPosition());
- TestCase.assertEquals(0, elementMD.getPrecision());
- TestCase.assertEquals(0, elementMD.getScale());
- TestCase.assertEquals(SearchType.Searchable, elementMD.getSearchType());
- TestCase.assertEquals(false, elementMD.isAutoIncremented());
- TestCase.assertEquals(true, elementMD.isCaseSensitive());
- TestCase.assertEquals(elementProps, elementMD.getProperties());
-
-
- DerivedColumn symbl2 = query.getProjectedQuery().getDerivedColumns().get(1);
- ColumnReference element2 = (ColumnReference)symbl2.getExpression();
- Column elementMD2 = element2.getMetadataObject();
-
- Properties elementProps2 = new Properties();
- elementProps2.setProperty("customPosition", "12");//$NON-NLS-1$ //$NON-NLS-2$
-
- TestCase.assertEquals(10, elementMD2.getLength());
- TestCase.assertEquals("23", elementMD2.getDefaultValue()); //$NON-NLS-1$
- TestCase.assertEquals("YesFormat", elementMD2.getFormat()); //$NON-NLS-1$
- TestCase.assertEquals(Integer.class, elementMD2.getJavaType());
- TestCase.assertEquals("1", elementMD2.getMaximumValue()); //$NON-NLS-1$
- TestCase.assertEquals("100", elementMD2.getMinimumValue()); //$NON-NLS-1$
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#long", elementMD2.getBaseTypeID()); //$NON-NLS-1$
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#decimal", elementMD2.getPrimitiveTypeID()); //$NON-NLS-1$
- TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#int", elementMD2.getDatatypeID()); //$NON-NLS-1$
- TestCase.assertEquals("COLUMN2", elementMD2.getNameInSource()); //$NON-NLS-1$
- TestCase.assertEquals("INT", elementMD2.getNativeType()); //$NON-NLS-1$
- TestCase.assertEquals(NullType.No_Nulls, elementMD2.getNullType());
- TestCase.assertEquals(1, elementMD2.getPosition());
- TestCase.assertEquals(0, elementMD2.getPrecision());
- TestCase.assertEquals(10, elementMD2.getScale());
- TestCase.assertEquals(SearchType.Searchable, elementMD2.getSearchType());
- TestCase.assertEquals(true, elementMD2.isAutoIncremented());
- TestCase.assertEquals(false, elementMD2.isCaseSensitive());
-
- TestCase.assertEquals(elementProps2, elementMD2.getProperties());
- ResultSetExecution exec = Mockito.mock(ResultSetExecution.class);
- Mockito.stub(exec.next()).toReturn(null);
- return exec;
- }
-
- };
+ public ProcedureExecution createProcedureExecution(
+ Call procedure, ExecutionContext executionContext,
+ RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ Properties props = new Properties();
+ props.setProperty("customBehaviour", "SkipExecute");//$NON-NLS-1$ //$NON-NLS-2$
+
+ AbstractMetadataRecord metaObject = procedure.getMetadataObject();
+
+ TestCase.assertEquals("AnyModel.ProcedureB",procedure.getProcedureName()); //$NON-NLS-1$
+ TestCase.assertEquals("PROC", metaObject.getNameInSource()); //$NON-NLS-1$
+ TestCase.assertEquals(props, metaObject.getProperties());
+ ProcedureExecution exec = Mockito.mock(ProcedureExecution.class);
+ Mockito.stub(exec.next()).toReturn(null);
+ return exec;
}
+
+ @Override
+ public ResultSetExecution createResultSetExecution(
+ QueryExpression query, ExecutionContext executionContext,
+ RuntimeMetadata metadata, Object connection) throws ConnectorException {
+ Properties groupProps = new Properties();
+ groupProps.setProperty("customName", "CustomTableA");//$NON-NLS-1$ //$NON-NLS-2$
+ NamedTable group = (NamedTable)query.getProjectedQuery().getFrom().get(0);
+ AbstractMetadataRecord groupMD = group.getMetadataObject();
+ TestCase.assertEquals(groupProps, groupMD.getProperties());
+
+
+ DerivedColumn symbl = query.getProjectedQuery().getDerivedColumns().get(0);
+ ColumnReference element = (ColumnReference)symbl.getExpression();
+ Column elementMD = element.getMetadataObject();
+ Properties elementProps = new Properties();
+ elementProps.setProperty("customPosition", "11");//$NON-NLS-1$ //$NON-NLS-2$
+
+ TestCase.assertEquals(0, elementMD.getLength());
+ TestCase.assertEquals("Foo", elementMD.getDefaultValue()); //$NON-NLS-1$
+ TestCase.assertEquals("TrimNulls", elementMD.getFormat()); //$NON-NLS-1$
+ TestCase.assertEquals(String.class, elementMD.getJavaType());
+ TestCase.assertEquals(null, elementMD.getMaximumValue());
+ TestCase.assertEquals(null, elementMD.getMinimumValue());
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#anySimpleType", elementMD.getBaseTypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#string", elementMD.getPrimitiveTypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#string", elementMD.getDatatypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("COLUMN1", elementMD.getNameInSource()); //$NON-NLS-1$
+ TestCase.assertEquals("STR", elementMD.getNativeType()); //$NON-NLS-1$
+ TestCase.assertEquals(NullType.Nullable, elementMD.getNullType());
+ TestCase.assertEquals(0, elementMD.getPosition());
+ TestCase.assertEquals(0, elementMD.getPrecision());
+ TestCase.assertEquals(0, elementMD.getScale());
+ TestCase.assertEquals(SearchType.Searchable, elementMD.getSearchType());
+ TestCase.assertEquals(false, elementMD.isAutoIncremented());
+ TestCase.assertEquals(true, elementMD.isCaseSensitive());
+ TestCase.assertEquals(elementProps, elementMD.getProperties());
+
+
+ DerivedColumn symbl2 = query.getProjectedQuery().getDerivedColumns().get(1);
+ ColumnReference element2 = (ColumnReference)symbl2.getExpression();
+ Column elementMD2 = element2.getMetadataObject();
+
+ Properties elementProps2 = new Properties();
+ elementProps2.setProperty("customPosition", "12");//$NON-NLS-1$ //$NON-NLS-2$
+
+ TestCase.assertEquals(10, elementMD2.getLength());
+ TestCase.assertEquals("23", elementMD2.getDefaultValue()); //$NON-NLS-1$
+ TestCase.assertEquals("YesFormat", elementMD2.getFormat()); //$NON-NLS-1$
+ TestCase.assertEquals(Integer.class, elementMD2.getJavaType());
+ TestCase.assertEquals("1", elementMD2.getMaximumValue()); //$NON-NLS-1$
+ TestCase.assertEquals("100", elementMD2.getMinimumValue()); //$NON-NLS-1$
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#long", elementMD2.getBaseTypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#decimal", elementMD2.getPrimitiveTypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("http://www.w3.org/2001/XMLSchema#int", elementMD2.getDatatypeID()); //$NON-NLS-1$
+ TestCase.assertEquals("COLUMN2", elementMD2.getNameInSource()); //$NON-NLS-1$
+ TestCase.assertEquals("INT", elementMD2.getNativeType()); //$NON-NLS-1$
+ TestCase.assertEquals(NullType.No_Nulls, elementMD2.getNullType());
+ TestCase.assertEquals(1, elementMD2.getPosition());
+ TestCase.assertEquals(0, elementMD2.getPrecision());
+ TestCase.assertEquals(10, elementMD2.getScale());
+ TestCase.assertEquals(SearchType.Searchable, elementMD2.getSearchType());
+ TestCase.assertEquals(true, elementMD2.isAutoIncremented());
+ TestCase.assertEquals(false, elementMD2.isCaseSensitive());
+
+ TestCase.assertEquals(elementProps2, elementMD2.getProperties());
+ ResultSetExecution exec = Mockito.mock(ResultSetExecution.class);
+ Mockito.stub(exec.next()).toReturn(null);
+ return exec;
+ }
}
Modified: trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -25,9 +25,9 @@
import java.util.Arrays;
import java.util.List;
-import org.teiid.connector.jdbc.oracle.OracleCapabilities;
-import org.teiid.connector.jdbc.sqlserver.SQLServerCapabilities;
import org.teiid.dqp.internal.datamgr.impl.CapabilitiesConverter;
+import org.teiid.translator.jdbc.oracle.OracleCapabilities;
+import org.teiid.translator.jdbc.sqlserver.SQLServerCapabilities;
import com.metamatrix.core.util.UnitTestUtil;
import com.metamatrix.query.metadata.QueryMetadataInterface;
Modified: trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -31,8 +31,8 @@
import org.mockito.Mockito;
import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.connector.api.SourceSystemFunctions;
import org.teiid.metadata.TransformationMetadata;
+import org.teiid.resource.cci.SourceSystemFunctions;
import com.metamatrix.core.util.ObjectConverterUtil;
import com.metamatrix.core.util.UnitTestUtil;
Modified: trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
===================================================================
--- trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -32,7 +32,6 @@
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.client.DQP;
import org.teiid.client.security.ILogon;
-import org.teiid.connector.api.ConnectorException;
import org.teiid.connector.metadata.runtime.MetadataStore;
import org.teiid.connector.metadata.runtime.Schema;
import org.teiid.deployers.MetadataStoreGroup;
@@ -44,6 +43,7 @@
import org.teiid.dqp.internal.process.DQPCore;
import org.teiid.metadata.index.IndexMetadataFactory;
import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.resource.ConnectorException;
import org.teiid.services.SessionServiceImpl;
import org.teiid.transport.ClientServiceRegistry;
import org.teiid.transport.ClientServiceRegistryImpl;
@@ -75,7 +75,7 @@
this.dqp.setTransactionService(new FakeTransactionService());
ConnectorManagerRepository cmr = Mockito.mock(ConnectorManagerRepository.class);
- Mockito.stub(cmr.getConnectorManager("jndi:source")).toReturn(new ConnectorManager("x") {
+ Mockito.stub(cmr.getConnectorManager("source")).toReturn(new ConnectorManager("x", "x") {
@Override
public SourceCapabilities getCapabilities()
throws ConnectorException {
@@ -104,14 +104,14 @@
ModelMetaData model = new ModelMetaData();
model.setName(schema.getName());
vdbMetaData.addModel(model);
- model.addSourceMapping("source", "jndi:source");
+ model.addSourceMapping("source", "translator", "jndi:source");
}
for (Schema schema : metadata.getSchemas().values()) {
ModelMetaData model = new ModelMetaData();
model.setName(schema.getName());
vdbMetaData.addModel(model);
- model.addSourceMapping("source", "jndi:source");
+ model.addSourceMapping("source", "translator", "jndi:source");
}
try {
Modified: trunk/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-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/db/src/test/java/org/teiid/adminapi/jboss/TestConnectorBindings.java 2010-05-07 16:24:50 UTC (rev 2103)
@@ -16,7 +16,6 @@
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
-import java.util.Properties;
import java.util.Set;
import org.junit.After;
@@ -26,8 +25,6 @@
import org.teiid.adminapi.Admin;
import org.teiid.adminapi.AdminException;
import org.teiid.adminapi.AdminFactory;
-import org.teiid.adminapi.ConnectionFactory;
-import org.teiid.adminapi.ConnectionPoolStatistics;
import org.teiid.adminapi.DataPolicy;
import org.teiid.adminapi.Model;
import org.teiid.adminapi.PropertyDefinition;
@@ -35,11 +32,11 @@
import org.teiid.adminapi.Session;
import org.teiid.adminapi.Transaction;
import org.teiid.adminapi.VDB;
-import org.teiid.adminapi.WorkerPoolStatistics;
import com.metamatrix.core.util.ObjectConverterUtil;
import com.metamatrix.core.util.UnitTestUtil;
+@SuppressWarnings("nls")
public class TestConnectorBindings extends BaseConnection {
static ServerDatasourceConnection ds;
static Admin admin;
@@ -69,89 +66,7 @@
}
admin.close();
}
-
- @Test public void testLoopbackConnectorBinding() throws Exception {
- ConnectionFactory binding = admin.getConnectionFactory("loopy"); //$NON-NLS-1$
-
- if (binding != null) {
- admin.deleteConnectionFactory("loopy"); //$NON-NLS-1$
- }
-
- Properties p = new Properties();
- p.setProperty("jndi-name", "loopy"); //$NON-NLS-1$ //$NON-NLS-2$
- p.setProperty("CapabilitiesClass", "org.teiid.connector.jdbc.loopback.LoopbackCapabilities"); //$NON-NLS-1$ //$NON-NLS-2$
-
- ConnectionFactory cf = admin.addConnectionFactory("loopy","connector-loopback-7.0.0-SNAPSHOT", p); //$NON-NLS-1$ //$NON-NLS-2$
- System.out.println(cf.getProperties());
-
-// admin.setConnectionFactoryProperty("loopy", "CapabilitiesClass", "org.teiid.connector.BasicCapabilities");
-// cf = admin.getConnectionFactory("loopy");
-// System.out.println(cf.getProperties());
- }
- @Test public void testLoopbackUpdate() throws Exception {
- ConnectionFactory cf = admin.getConnectionFactory("loopy"); //$NON-NLS-1$
- System.out.println(cf.getProperties());
-
- admin.setConnectionFactoryProperty("loopy", "CapabilitiesClass", "org.teiid.connector.LoopyCapabilities");
- cf = admin.getConnectionFactory("loopy");
- System.out.println(cf.getProperties());
- }
-
- @Test public void testGetConnectorFactories() throws Exception {
- Collection<ConnectionFactory> cfs = admin.getConnectionFactories();
- for(ConnectionFactory cf:cfs) {
- System.out.println(cf.getName());
- }
- ConnectionFactory cf = admin.getConnectionFactory("products-cf"); //$NON-NLS-1$
- System.out.println(cf.getName());
- }
-
- @Test public void testDSConnectorBinding() throws Exception {
- ConnectionFactory binding = admin.getConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
-
- if (binding != null) {
- admin.deleteConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
- }
-
- Properties p = new Properties();
- p.setProperty("jndi-name", "test-mysql-cb"); //$NON-NLS-1$ //$NON-NLS-2$
- p.setProperty("CapabilitiesClass", "org.teiid.connector.jdbc.mysql.MySQL5Capabilities"); //$NON-NLS-1$ //$NON-NLS-2$
- p.setProperty("XaCapable", "true"); //$NON-NLS-1$ //$NON-NLS-2$
-
- 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.addConnectionFactory("test-mysql-cb","connector-jdbc-xa-7.0.0-SNAPSHOT", p); //$NON-NLS-1$ //$NON-NLS-2$
-
- binding = admin.getConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
-
- assertNotNull(binding);
-
- assertEquals("org.teiid.connector.jdbc.mysql.MySQL5Capabilities", binding.getPropertyValue("CapabilitiesClass")); //$NON-NLS-1$ //$NON-NLS-2$
-
- admin.stopConnectionFactory("test-mysql-cb");
-
- admin.startConnectionFactory("test-mysql-cb");
-
- admin.setConnectionFactoryProperty("test-mysql-cb", "XaCapable", "false"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- binding = admin.getConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
-
- assertEquals("false", binding.getPropertyValue("XaCapable")); //$NON-NLS-1$ //$NON-NLS-2$
-
- //admin.deleteConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
-
- //binding = admin.getConnectionFactory("test-mysql-cb"); //$NON-NLS-1$
-
- //assertNull(binding);
- }
-
@Test public void testVDBDeploy() throws Exception {
VDB vdb = admin.getVDB("TransactionsRevisited", 1); //$NON-NLS-1$
@@ -166,9 +81,6 @@
Set<VDB> vdbs = admin.getVDBs();
assertTrue(vdbs.size() >= 1);
- Collection<ConnectionFactory> bindings = admin.getConnectionFactoriesInVDB("TransactionsRevisited",1); //$NON-NLS-1$
- assertEquals(2, bindings.size());
-
admin.deleteVDB("TransactionsRevisited", 1); //$NON-NLS-1$
assertNull(admin.getVDB("TransactionsRevisited", 1)); //$NON-NLS-1$
@@ -290,7 +202,7 @@
@Test
public void testConnectorTypeProperties() throws Exception {
- Collection<PropertyDefinition> defs = admin.getConnectorTemplatePropertyDefinitions("connector-jdbc-xa-7.0.0-SNAPSHOT"); //$NON-NLS-1$
+ Collection<PropertyDefinition> defs = admin.getTranslatorTemplatePropertyDefinitions("connector-jdbc-xa-7.0.0-SNAPSHOT"); //$NON-NLS-1$
for (PropertyDefinition pd:defs) {
System.out.println(pd.getName()+":"+pd.getPropertyTypeClassName());
if (pd.getName().equals("ExtensionTranslationClassName")) { //$NON-NLS-1$
@@ -318,7 +230,7 @@
@Test
public void testConnectorTypes() throws Exception {
- Set<String> defs = admin.getConnectorTemplateNames();
+ Set<String> defs = admin.getTranslatorTemplateNames();
// assertTrue(defs.contains("connector-salesforce-7.0.0-SNAPSHOT")); //$NON-NLS-1$
// assertTrue(defs.contains("connector-jdbc-7.0.0-SNAPSHOT")); //$NON-NLS-1$
// assertTrue(defs.contains("connector-text-7.0.0-SNAPSHOT")); //$NON-NLS-1$
@@ -327,25 +239,7 @@
System.out.println(defs);
}
-
@Test
- public void testConnectorAddDelete() throws Exception{
- File f = new File(UnitTestUtil.getTestDataPath()+"/connector-loopback.rar"); //$NON-NLS-1$
- FileInputStream fis = new FileInputStream(f);
- admin.addConnector("connector-loopy.rar", fis); //$NON-NLS-1$
- fis.close();
-
- Set<String> names = admin.getConnectorTemplateNames();
- System.out.println(names);
- assertTrue(names.contains("connector-loopy")); //$NON-NLS-1$
-
- admin.deleteConnector("connector-loopy.rar"); //$NON-NLS-1$
-
- names = admin.getConnectorTemplateNames();
- //assertTrue(!names.contains("connector-loopy")); //$NON-NLS-1$
- }
-
- @Test
public void testExportVDB() throws Exception{
File f = new File(UnitTestUtil.getTestScratchPath()+"/TransactionsRevisited.vdb"); //$NON-NLS-1$
@@ -361,7 +255,7 @@
}
@Test public void testAssignConnectorBinding() throws Exception {
- admin.assignConnectionFactoryToModel("TransactionsRevisited", 1, "pm1", "mysql", "jndi:FOO"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ 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$
@@ -371,7 +265,7 @@
List<String> sources = model.getSourceNames();
for (String source:sources) {
if (source.equals("mysql")) { //$NON-NLS-1$
- assertEquals("jndi:FOO", model.getSourceJndiName(source)); //$NON-NLS-1$
+ assertEquals("jndi:FOO", model.getSourceConnectionJndiName(source)); //$NON-NLS-1$
checked = true;
}
}
Modified: trunk/test-integration/pom.xml
===================================================================
--- trunk/test-integration/pom.xml 2010-05-07 13:30:14 UTC (rev 2102)
+++ trunk/test-integration/pom.xml 2010-05-07 16:24:50 UTC (rev 2103)
@@ -41,9 +41,8 @@
</dependency>
<dependency>
<groupId>org.jboss.teiid.connectors</groupId>
- <artifactId>connector-jdbc</artifactId>
+ <artifactId>translator-jdbc</artifactId>
<version>${project.version}</version>
- <classifier>lib</classifier>
</dependency>
<dependency>
<groupId>org.jboss.teiid</groupId>
13 years, 11 months
teiid SVN: r2102 - in trunk: connector-api/src/main/java/org/teiid/connector/api and 6 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-07 09:30:14 -0400 (Fri, 07 May 2010)
New Revision: 2102
Modified:
trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java
trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java
trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java
trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java
trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties
trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java
trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
Log:
TEIID-171 adding support for xmlpi and xmlcomment
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -46,7 +46,7 @@
public final class XMLType extends Streamable<SQLXML> implements SQLXML {
public enum Type {
- UNKNOWN, DOCUMENT, FRAGMENT, SIBLINGS
+ UNKNOWN, DOCUMENT, FRAGMENT, SIBLINGS, COMMENT, PI
}
private static final long serialVersionUID = -7922647237095135723L;
Modified: trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -139,5 +139,7 @@
public static final String XSLTRANSFORM = "xsltransform"; //$NON-NLS-1$
public static final String XMLELEMENT = "xmlelement"; //$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$
}
Modified: trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml 2010-05-07 13:30:14 UTC (rev 2102)
@@ -1998,10 +1998,36 @@
</para>
</entry>
<entry>
- <para>Name is an identifier. exp can be any type. Return value is xml.
+ <para>Name is an identifier. Exp can be any type. Return value is xml.
</para>
</entry>
</row>
+ <row>
+ <entry>
+ <para><code>XMLCOMMENT(comment)</code></para>
+ </entry>
+ <entry>
+ <para>Returns an xml comment.
+ </para>
+ </entry>
+ <entry>
+ <para>Comment is a string. Return value is xml.
+ </para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para><code>XMLPI([NAME] name [, content])</code></para>
+ </entry>
+ <entry>
+ <para>Returns an xml processing instruction.
+ </para>
+ </entry>
+ <entry>
+ <para>Name is an identifier. Content is a string. Return value is xml.
+ </para>
+ </entry>
+ </row>
</tbody>
</tgroup>
</informaltable>
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -170,6 +170,8 @@
addXslTransformFunction();
addXmlElement();
addXmlConcat();
+ addXmlComment();
+ addXmlPi();
addSecurityFunctions();
@@ -931,6 +933,26 @@
new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlement_result")), true, FunctionMethod.DETERMINISTIC ) ); //$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 addXmlConcat() {
functions.add(new FunctionMethod(SourceSystemFunctions.XMLCONCAT, QueryPlugin.Util.getString("SystemSource.xmlconcat_description"), XML, FunctionMethod.CAN_PUSHDOWN, XML_FUNCTION_CLASS, "xmlConcat", //$NON-NLS-1$ //$NON-NLS-2$
new FunctionParameter[] {
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -56,6 +56,7 @@
import com.metamatrix.api.exception.query.FunctionExecutionException;
import com.metamatrix.common.types.ClobType;
import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.common.types.SQLXMLImpl;
import com.metamatrix.common.types.Streamable;
import com.metamatrix.common.types.TransformationException;
import com.metamatrix.common.types.XMLTranslator;
@@ -276,6 +277,21 @@
return result;
}
+ public static XMLType xmlPi(String name) {
+ return xmlPi(name, ""); //$NON-NLS-1$
+ }
+
+ public static XMLType xmlPi(String name, String content) {
+ int start = 0;
+ char[] chars = content.toCharArray();
+ while (start < chars.length && chars[start] == ' ') {
+ start++;
+ }
+ XMLType result = new XMLType(new SQLXMLImpl("<?" + name + " " + content.substring(start) + "?>")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ result.setType(Type.PI);
+ return result;
+ }
+
static String getStringValue(Object object) throws TransformerException {
if (object instanceof Timestamp) {
try {
@@ -307,7 +323,9 @@
}
switch(xml.getType()) {
case FRAGMENT:
- case SIBLINGS: //write the value directly to the writer
+ case SIBLINGS:
+ case PI:
+ case COMMENT: //write the value directly to the writer
eventWriter.flush();
int chr = -1;
while ((chr = r.read()) != -1) {
@@ -341,6 +359,10 @@
//TODO: blob - with base64 encoding
//TODO: full clob?
}
+
+ public static XMLType xmlComment(String comment) {
+ return new XMLType(new SQLXMLImpl("<!--" + comment + "-->")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
/**
* Formats a timestamp to an xs:dateTime. This uses DATETIME_FORMAT
Modified: trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
===================================================================
--- trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-05-07 13:30:14 UTC (rev 2102)
@@ -2918,7 +2918,8 @@
(
(funcToken = <LEFT> | funcToken = <RIGHT> | funcToken = <CHAR> | funcToken = <USER>
| funcToken = <YEAR> | funcToken = <MONTH> | funcToken = <HOUR>
- | funcToken = <MINUTE> | funcToken = <SECOND> | funcToken = <XMLCONCAT>)
+ | funcToken = <MINUTE> | funcToken = <SECOND> | funcToken = <XMLCONCAT>
+ | funcToken = <XMLCOMMENT>)
<LPAREN>
[
expression = expression(info)
@@ -3002,6 +3003,26 @@
)*
<RPAREN>
)
+ | ( funcToken = <XMLPI>
+ <LPAREN>
+ (
+ LOOKAHEAD(<ID>, { "name".equalsIgnoreCase(getToken(1).image) }) <ID> expression = idExpression()
+ |
+ expression = idExpression()
+ )
+ {
+ args.add(expression);
+ expression = null;
+ }
+ [
+ <COMMA> expression = expression(info)
+ {
+ args.add(expression);
+ expression = null;
+ }
+ ]
+ <RPAREN>
+ )
|
LOOKAHEAD(<XMLFOREST>) (
expression = sqlXmlFunction(info)
Modified: trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties 2010-05-07 13:30:14 UTC (rev 2102)
@@ -778,8 +778,13 @@
SystemSource.xmlelement_result=XML result
SystemSource.xmlconcat_description=Concat XML types.
SystemSource.xmlconcat_param1=First element
-SystemSource.xmlconcat_param2=Other elements
+SystemSource.xmlcomment_description=Creates an XML comment.
+SystemSource.xmlconcat_param1=String comment
SystemSource.xmlconcat_result=XML result
+SystemSource.xmlpi_description=Creates an XML processing instruction.
+SystemSource.xmlpi_param1=Target
+SystemSource.xmlpi_param2=Content
+SystemSource.xmlpi_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
Modified: trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -1380,4 +1380,14 @@
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);
+ }
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-05-06 21:39:42 UTC (rev 2101)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-05-07 13:30:14 UTC (rev 2102)
@@ -7555,5 +7555,20 @@
helpProcess(plan, dataManager, expected);
}
+ @Test public void testXmlElementWithPi() {
+ String sql = "SELECT xmlelement(x, xmlpi(name e1, ' 1'))"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<x><?e1 1?></x>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
private static final boolean DEBUG = false;
}
13 years, 11 months
teiid SVN: r2101 - trunk/client/src/main/java/org/teiid/adminapi/impl.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-06 17:39:42 -0400 (Thu, 06 May 2010)
New Revision: 2101
Removed:
trunk/client/src/main/java/org/teiid/adminapi/impl/AdminPlugin.java
Modified:
trunk/client/src/main/java/org/teiid/adminapi/impl/PropertyDefinitionMetadata.java
trunk/client/src/main/java/org/teiid/adminapi/impl/TransactionMetadata.java
Log:
TEIID-1086 removing the use of the admin plugin class
Deleted: trunk/client/src/main/java/org/teiid/adminapi/impl/AdminPlugin.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/AdminPlugin.java 2010-05-06 17:17:44 UTC (rev 2100)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/AdminPlugin.java 2010-05-06 21:39:42 UTC (rev 2101)
@@ -1,38 +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.ResourceBundle;
-import com.metamatrix.core.BundleUtil;
-
-/**
- * The main plugin class to be used in the desktop.
- */
-public class AdminPlugin {
-
- public static final String PLUGIN_ID = AdminPlugin.class.getPackage().getName();
-
- public static final BundleUtil Util = new BundleUtil(PLUGIN_ID,
- PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
-
-}
Modified: trunk/client/src/main/java/org/teiid/adminapi/impl/PropertyDefinitionMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/PropertyDefinitionMetadata.java 2010-05-06 17:17:44 UTC (rev 2100)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/PropertyDefinitionMetadata.java 2010-05-06 21:39:42 UTC (rev 2101)
@@ -49,17 +49,17 @@
*/
public String toString() {
StringBuffer result = new StringBuffer();
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Display_name")).append(getDisplayName()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Description")).append(getDescription()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Property_type_class_name")).append(getPropertyTypeClassName()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Default_value")).append(getDefaultValue()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Constrained_to_allow_values")).append(isConstrainedToAllowedValues()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Allowed_values")).append(getAllowedValues()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Required")).append(isRequired()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Expert")).append(isAdvanced()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Masked")).append(isMasked()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.Modifiable")).append(isModifiable()); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("MMPropertyDefinition.RequiresRestart")).append(getRequiresRestart()); //$NON-NLS-1$
+ result.append("Display Name:").append(getDisplayName()); //$NON-NLS-1$
+ result.append("Description:").append(getDescription()); //$NON-NLS-1$
+ result.append("Property Type Classname:").append(getPropertyTypeClassName()); //$NON-NLS-1$
+ result.append("Default Value:").append(getDefaultValue()); //$NON-NLS-1$
+ result.append("Constrained To Allow Values:").append(isConstrainedToAllowedValues()); //$NON-NLS-1$
+ result.append("Allowed Values:").append(getAllowedValues()); //$NON-NLS-1$
+ result.append("Required:").append(isRequired()); //$NON-NLS-1$
+ result.append("Expert:").append(isAdvanced()); //$NON-NLS-1$
+ result.append("Masked:").append(isMasked()); //$NON-NLS-1$
+ result.append("Modifiable:").append(isModifiable()); //$NON-NLS-1$
+ result.append("RequiresRestart:").append(getRequiresRestart()); //$NON-NLS-1$
return result.toString();
}
Modified: trunk/client/src/main/java/org/teiid/adminapi/impl/TransactionMetadata.java
===================================================================
--- trunk/client/src/main/java/org/teiid/adminapi/impl/TransactionMetadata.java 2010-05-06 17:17:44 UTC (rev 2100)
+++ trunk/client/src/main/java/org/teiid/adminapi/impl/TransactionMetadata.java 2010-05-06 21:39:42 UTC (rev 2101)
@@ -81,10 +81,10 @@
@Override
public String toString() {
StringBuffer result = new StringBuffer();
- result.append(AdminPlugin.Util.getString("TransactionImpl.associatedSession")).append(associatedSession); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("TransactionImpl.scope")).append(scope); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("TransactionImpl.id")).append(id); //$NON-NLS-1$
- result.append(AdminPlugin.Util.getString("TransactionImpl.createdTime")).append(new Date(createdTime)); //$NON-NLS-1$
+ result.append("Associated Session:").append(associatedSession); //$NON-NLS-1$
+ result.append("Scope:").append(scope); //$NON-NLS-1$
+ result.append("Id:").append(id); //$NON-NLS-1$
+ result.append("CreatedTime:").append(new Date(createdTime)); //$NON-NLS-1$
return result.toString();
}
13 years, 11 months
teiid SVN: r2100 - in trunk: common-core/src/main/java/com/metamatrix/common/types and 41 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-06 13:17:44 -0400 (Thu, 06 May 2010)
New Revision: 2100
Added:
trunk/engine/src/main/java/com/metamatrix/query/sql/symbol/SQLXMLFunction.java
Modified:
trunk/client/src/main/java/org/teiid/jdbc/DataTypeTransformer.java
trunk/common-core/src/main/java/com/metamatrix/common/types/DataTypeManager.java
trunk/common-core/src/main/java/com/metamatrix/common/types/TransformationException.java
trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java
trunk/common-core/src/main/java/com/metamatrix/common/types/basic/ClobToSQLXMLTransform.java
trunk/common-core/src/main/java/com/metamatrix/common/types/basic/StringToSQLXMLTransform.java
trunk/common-core/src/test/java/com/metamatrix/common/types/basic/TestStringToXmlTransform.java
trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java
trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java
trunk/connectors/connector-xml-file/src/main/java/org/teiid/connector/xml/file/FileProcedureExecution.java
trunk/connectors/connector-xml/src/test/java/com/metamatrix/connector/xml/TestElementCollector.java
trunk/documentation/reference/src/main/docbook/en-US/content/grammar.xml
trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java
trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java
trunk/engine/src/main/java/com/metamatrix/query/function/FunctionLibrary.java
trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java
trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/FrameUtil.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/JoinUtil.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/QueryUtil.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLUtil.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLValueTranslator.java
trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java
trunk/engine/src/main/java/com/metamatrix/query/resolver/util/ResolverVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
trunk/engine/src/main/java/com/metamatrix/query/sql/LanguageVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/sql/navigator/PreOrPostOrderNavigator.java
trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/ExpressionMappingVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/SQLStringVisitor.java
trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties
trunk/engine/src/test/java/com/metamatrix/cdk/CommandBuilder.java
trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinWithFunction.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestOptimizer.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/batch/TestBatchedUpdatePlanner.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/proc/TestProcedurePlanner.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/rules/TestCalculateCostUtil.java
trunk/engine/src/test/java/com/metamatrix/query/optimizer/xml/TestXMLPlanner.java
trunk/engine/src/test/java/com/metamatrix/query/parser/TestParser.java
trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java
trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestInstructions.java
trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestXMLProcessor.java
trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestOrderByRewrite.java
trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java
trunk/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java
trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
Log:
TEIID-171 refining support for the xmlelement function, adding xmlattributes, xmlconcat, and xmlforest
Modified: trunk/client/src/main/java/org/teiid/jdbc/DataTypeTransformer.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/DataTypeTransformer.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/client/src/main/java/org/teiid/jdbc/DataTypeTransformer.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -68,10 +68,10 @@
private static final <T> T transform(Object value, Class<T> targetType, Class<?> runtimeType, String typeName) throws SQLException {
if (value == null || targetType.isAssignableFrom(value.getClass())) {
- return (T)value;
+ return targetType.cast(value);
}
try {
- return (T)DataTypeManager.transformValue(DataTypeManager.convertToRuntimeType(value), runtimeType);
+ return targetType.cast(DataTypeManager.transformValue(DataTypeManager.convertToRuntimeType(value), runtimeType));
} catch (TransformationException e) {
String valueStr = value.toString();
if (valueStr.length() > 20) {
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/DataTypeManager.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/DataTypeManager.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/DataTypeManager.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -449,7 +449,7 @@
* @param type
* @return true if yes; false otherwise
*/
- public static boolean isLOB(Class type) {
+ public static boolean isLOB(Class<?> type) {
return DataTypeManager.DefaultDataClasses.BLOB.equals(type)
|| DataTypeManager.DefaultDataClasses.CLOB.equals(type)
|| DataTypeManager.DefaultDataClasses.XML.equals(type);
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/TransformationException.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/TransformationException.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/TransformationException.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -22,13 +22,13 @@
package com.metamatrix.common.types;
-import com.metamatrix.api.exception.MetaMatrixException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
/**
* The exception is thrown when an error occurs during data transformation,
* typically a formatting error or an invalid input type.
*/
-public class TransformationException extends MetaMatrixException {
+public class TransformationException extends MetaMatrixProcessingException {
/**
* No-Arg Constructor
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/XMLType.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -44,8 +44,14 @@
* only SQLXML interface on top of this.
*/
public final class XMLType extends Streamable<SQLXML> implements SQLXML {
-
+
+ public enum Type {
+ UNKNOWN, DOCUMENT, FRAGMENT, SIBLINGS
+ }
+
private static final long serialVersionUID = -7922647237095135723L;
+
+ private transient Type type = Type.UNKNOWN;
public XMLType(){
@@ -90,5 +96,14 @@
public <T extends Result> T setResult(Class<T> resultClass)
throws SQLException {
return this.reference.setResult(resultClass);
- }
+ }
+
+ public Type getType() {
+ return type;
+ }
+
+ public void setType(Type type) {
+ this.type = type;
+ }
+
}
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/basic/ClobToSQLXMLTransform.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/basic/ClobToSQLXMLTransform.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/basic/ClobToSQLXMLTransform.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -37,6 +37,7 @@
import com.metamatrix.common.types.Transform;
import com.metamatrix.common.types.TransformationException;
import com.metamatrix.common.types.XMLType;
+import com.metamatrix.common.types.XMLType.Type;
import com.metamatrix.common.util.ReaderInputStream;
import com.metamatrix.core.CorePlugin;
@@ -66,21 +67,25 @@
Reader reader = null;
try {
reader = source.getCharacterStream();
- StringToSQLXMLTransform.isXml(reader);
+ XMLType result = null;
+ Type type = StringToSQLXMLTransform.isXml(reader);
if (source.getReference() instanceof ClobImpl) {
ClobImpl clob = (ClobImpl)source.getReference();
- return new XMLType(new SQLXMLImpl(clob.getStreamFactory()));
- }
- return new XMLType(new SQLXMLImpl(new InputStreamFactory(Streamable.ENCODING) {
- @Override
- public InputStream getInputStream() throws IOException {
- try {
- return new ReaderInputStream(source.getCharacterStream(), Charset.forName(Streamable.ENCODING));
- } catch (SQLException e) {
- throw new IOException(e);
- }
- }
- }));
+ result = new XMLType(new SQLXMLImpl(clob.getStreamFactory()));
+ } else {
+ result = new XMLType(new SQLXMLImpl(new InputStreamFactory(Streamable.ENCODING) {
+ @Override
+ public InputStream getInputStream() throws IOException {
+ try {
+ return new ReaderInputStream(source.getCharacterStream(), Charset.forName(Streamable.ENCODING));
+ } catch (SQLException e) {
+ throw new IOException(e);
+ }
+ }
+ }));
+ }
+ result.setType(type);
+ return result;
} catch (SQLException e) {
throw new TransformationException(e, CorePlugin.Util.getString("failed_convert", new Object[] {getSourceType().getName(), getTargetType().getName()})); //$NON-NLS-1$
} finally {
Modified: trunk/common-core/src/main/java/com/metamatrix/common/types/basic/StringToSQLXMLTransform.java
===================================================================
--- trunk/common-core/src/main/java/com/metamatrix/common/types/basic/StringToSQLXMLTransform.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/main/java/com/metamatrix/common/types/basic/StringToSQLXMLTransform.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -26,17 +26,16 @@
import java.io.Reader;
import java.io.StringReader;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.events.XMLEvent;
-import org.xml.sax.InputSource;
-import org.xml.sax.helpers.DefaultHandler;
-
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.types.SQLXMLImpl;
import com.metamatrix.common.types.Transform;
import com.metamatrix.common.types.TransformationException;
import com.metamatrix.common.types.XMLType;
+import com.metamatrix.common.types.XMLType.Type;
import com.metamatrix.core.CorePlugin;
public class StringToSQLXMLTransform extends Transform {
@@ -52,15 +51,23 @@
public Object transformDirect(Object value) throws TransformationException {
String xml = (String)value;
Reader reader = new StringReader(xml);
- isXml(reader);
- return new XMLType(new SQLXMLImpl(xml));
+ Type type = isXml(reader);
+ XMLType result = new XMLType(new SQLXMLImpl(xml));
+ result.setType(type);
+ return result;
}
- static void isXml(Reader reader) throws TransformationException {
- SAXParserFactory spf = SAXParserFactory.newInstance();
+ static Type isXml(Reader reader) throws TransformationException {
+ Type type = Type.FRAGMENT;
+ XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try{
- SAXParser sp = spf.newSAXParser();
- sp.parse(new InputSource(reader), new DefaultHandler());
+ XMLEventReader xmlReader = inputFactory.createXMLEventReader(reader);
+ while (xmlReader.hasNext()) {
+ XMLEvent event = xmlReader.nextEvent();
+ if (event.isStartDocument() && event.getLocation().getColumnNumber() != 1) {
+ type = Type.DOCUMENT;
+ }
+ }
} catch (Exception e){
throw new TransformationException(e, CorePlugin.Util.getString("invalid_string")); //$NON-NLS-1$
} finally {
@@ -69,6 +76,7 @@
} catch (IOException e) {
}
}
+ return type;
}
/**
Modified: trunk/common-core/src/test/java/com/metamatrix/common/types/basic/TestStringToXmlTransform.java
===================================================================
--- trunk/common-core/src/test/java/com/metamatrix/common/types/basic/TestStringToXmlTransform.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/common-core/src/test/java/com/metamatrix/common/types/basic/TestStringToXmlTransform.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -27,7 +27,6 @@
import java.sql.SQLXML;
-import org.junit.Ignore;
import org.junit.Test;
import com.metamatrix.common.types.TransformationException;
@@ -58,14 +57,4 @@
transform.transformDirect(xml);
}
- @Ignore("TODO: allow for fragments in the xml type")
- @Test public void testXMLFragment() throws Exception {
- String xml = "<name>ABC</name>" + //$NON-NLS-1$
- "<age>32</age>"; //$NON-NLS-1$
-
- StringToSQLXMLTransform transform = new StringToSQLXMLTransform();
-
- transform.transformDirect(xml);
- }
-
}
Modified: trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java
===================================================================
--- trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/connector-api/src/main/java/org/teiid/connector/api/SourceSystemFunctions.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -138,5 +138,6 @@
public static final String XPATHVALUE = "xpathvalue"; //$NON-NLS-1$
public static final String XSLTRANSFORM = "xsltransform"; //$NON-NLS-1$
public static final String XMLELEMENT = "xmlelement"; //$NON-NLS-1$
+ public static final String XMLCONCAT = "xmlconcat"; //$NON-NLS-1$
}
Modified: trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/connectors/connector-jdbc/src/test/java/org/teiid/connector/jdbc/oracle/TestOracleTranslator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -425,12 +425,7 @@
*/
@Test public void test_sdo_within_distance3() throws Exception {
String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance(STRINGKEY, 'SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- // using ? for bind value as r marks the criteria as bindEligible
- // due to literal of type Object appearing in left side of criteria.
- // The literal Object is a result of the sdo_within_distance function
- // signature being sdo_within_distance(string, object, string) : string
- // as the signature was the best match for this query.
- String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SmallA.StringKey, SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = ?"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SmallA.StringKey, SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
input, output,
@@ -446,12 +441,7 @@
*/
@Test public void test_sdo_within_distance4() throws Exception {
String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance('SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
- // using ? for bind value as r marks the criteria as bindEligible
- // due to literal of type Object appearing in left side of criteria.
- // The literal Object is a result of the sdo_within_distance function
- // signature being sdo_within_distance(string, object, string) : string
- // as the signature was the best match for this query.
- String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = ?"; //$NON-NLS-1$
+ String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'"; //$NON-NLS-1$
TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, UDF,
input, output,
Modified: trunk/connectors/connector-xml/src/test/java/com/metamatrix/connector/xml/TestElementCollector.java
===================================================================
--- trunk/connectors/connector-xml/src/test/java/com/metamatrix/connector/xml/TestElementCollector.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/connectors/connector-xml/src/test/java/com/metamatrix/connector/xml/TestElementCollector.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -11,10 +11,10 @@
import junit.framework.TestCase;
-import org.teiid.connector.basic.TypeFacilityImpl;
import org.teiid.connector.language.Select;
import com.metamatrix.common.types.InputStreamFactory;
+import com.metamatrix.common.types.SQLXMLImpl;
import com.metamatrix.connector.xml.base.ExecutionInfo;
import com.metamatrix.connector.xml.base.ProxyObjectFactory;
import com.metamatrix.connector.xml.base.QueryAnalyzer;
@@ -23,6 +23,7 @@
import com.metamatrix.connector.xml.streaming.ReaderFactory;
import com.metamatrix.connector.xml.streaming.StreamingRowCollector;
+@SuppressWarnings("nls")
public class TestElementCollector extends TestCase {
StreamingRowCollector builder;
@@ -80,6 +81,6 @@
return in;
}
};
- return (SQLXML)new TypeFacilityImpl().convertToRuntimeType(isf);
+ return new SQLXMLImpl(isf);
}
}
Modified: trunk/connectors/connector-xml-file/src/main/java/org/teiid/connector/xml/file/FileProcedureExecution.java
===================================================================
--- trunk/connectors/connector-xml-file/src/main/java/org/teiid/connector/xml/file/FileProcedureExecution.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/connectors/connector-xml-file/src/main/java/org/teiid/connector/xml/file/FileProcedureExecution.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -41,6 +41,7 @@
import org.teiid.connector.metadata.runtime.RuntimeMetadata;
import com.metamatrix.common.types.InputStreamFactory;
+import com.metamatrix.common.types.SQLXMLImpl;
/**
@@ -94,7 +95,7 @@
String encoding = this.config.getCharacterEncodingScheme();
- returnValue = (SQLXML)this.config.getTypeFacility().convertToRuntimeType(new InputStreamFactory(encoding) {
+ returnValue = new SQLXMLImpl(new InputStreamFactory(encoding) {
@Override
public InputStream getInputStream() throws IOException {
Modified: trunk/documentation/reference/src/main/docbook/en-US/content/grammar.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/grammar.xml 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/documentation/reference/src/main/docbook/en-US/content/grammar.xml 2010-05-06 17:17:44 UTC (rev 2100)
@@ -121,7 +121,6 @@
| <DAY: "day">
| <DEALLOCATE: "deallocate">
| <DEFAULT_KEYWORD: "default">
-| <DEBUG: "debug">
| <DECLARE: "declare">
| <DELETE: "delete">
| <DESC: "desc">
@@ -211,7 +210,6 @@
| <OVERLAPS: "OVERLAPS">
| <PARAMETER: "parameter">
| <PARTITION: "partition">
-| <PLANONLY: "planonly">
| <PRECISION: "precision">
| <PREPARE: "prepare">
| <PRIMARY: "primary">
@@ -237,7 +235,6 @@
| <SENSITIVE: "sensitive">
| <SESSION_USER: "session_user">
| <SET: "set">
-| <SHOWPLAN: "showplan">
| <SIMILAR: "similar">
| <SPECIFIC: "specific">
| <SOME: "some">
@@ -551,45 +548,53 @@
<row>
<entry align="right" valign="top"><para><anchor id="prod52" xreflabel="selectSymbol"/>selectSymbol</para></entry>
<entry align="left" valign="top"><para>::=
-( ( <ALL_IN_GROUP> ) | ( <link linkend="prod16">expression</link> ) ( ( <AS> )? ( <link linkend="prod2">id</link> ) )? )</para></entry></row>
+( <link linkend="prod53">selectExpression</link> | <link linkend="prod54">allInGroupSymbol</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod53" xreflabel="aggregateSymbol"/>aggregateSymbol</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod53" xreflabel="selectExpression"/>selectExpression</para></entry>
<entry align="left" valign="top"><para>::=
+( <link linkend="prod16">expression</link> ( ( <AS> )? ( <link linkend="prod2">id</link> ) )? )</para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod54" xreflabel="allInGroupSymbol"/>allInGroupSymbol</para></entry>
+<entry align="left" valign="top"><para>::=
+( <ALL_IN_GROUP> )</para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod55" xreflabel="aggregateSymbol"/>aggregateSymbol</para></entry>
+<entry align="left" valign="top"><para>::=
( ( <COUNT> <LPAREN> <STAR> <RPAREN> ) | ( ( <COUNT> | <SUM> | <AVG> | <MIN> | <MAX> ) <LPAREN> ( <DISTINCT> )? <link linkend="prod16">expression</link> <RPAREN> ) )</para></entry></row>
<row>
<entry align="right" valign="top"><para><anchor id="prod49" xreflabel="from"/>from</para></entry>
<entry align="left" valign="top"><para>::=
-<FROM> ( <link linkend="prod54">tableReference</link> ( <COMMA> <link linkend="prod54">tableReference</link> )* )</para></entry></row>
+<FROM> ( <link linkend="prod56">tableReference</link> ( <COMMA> <link linkend="prod56">tableReference</link> )* )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod54" xreflabel="tableReference"/>tableReference</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod56" xreflabel="tableReference"/>tableReference</para></entry>
<entry align="left" valign="top"><para>::=
-( ( <LBRACE> <OJ> <link linkend="prod55">tableReferenceUnescaped</link> <RBRACE> ) | <link linkend="prod55">tableReferenceUnescaped</link> )</para></entry></row>
+( ( <LBRACE> <OJ> <link linkend="prod57">tableReferenceUnescaped</link> <RBRACE> ) | <link linkend="prod57">tableReferenceUnescaped</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod55" xreflabel="tableReferenceUnescaped"/>tableReferenceUnescaped</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod57" xreflabel="tableReferenceUnescaped"/>tableReferenceUnescaped</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod56">joinedTable</link> | <link linkend="prod57">tablePrimary</link> )</para></entry></row>
+( <link linkend="prod58">joinedTable</link> | <link linkend="prod59">tablePrimary</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod56" xreflabel="joinedTable"/>joinedTable</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod58" xreflabel="joinedTable"/>joinedTable</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod57">tablePrimary</link> ( ( <link linkend="prod58">crossJoin</link> | <link linkend="prod59">qualifiedJoin</link> ) )+</para></entry></row>
+<link linkend="prod59">tablePrimary</link> ( ( <link linkend="prod60">crossJoin</link> | <link linkend="prod61">qualifiedJoin</link> ) )+</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod58" xreflabel="crossJoin"/>crossJoin</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod60" xreflabel="crossJoin"/>crossJoin</para></entry>
<entry align="left" valign="top"><para>::=
-( ( <CROSS> | <UNION> ) <JOIN> <link linkend="prod57">tablePrimary</link> )</para></entry></row>
+( ( <CROSS> | <UNION> ) <JOIN> <link linkend="prod59">tablePrimary</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod59" xreflabel="qualifiedJoin"/>qualifiedJoin</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod61" xreflabel="qualifiedJoin"/>qualifiedJoin</para></entry>
<entry align="left" valign="top"><para>::=
-( ( ( <RIGHT> ( <OUTER> )? ) | ( <LEFT> ( <OUTER> )? ) | ( <FULL> ( <OUTER> )? ) | <INNER> )? <JOIN> <link linkend="prod54">tableReference</link> <ON> <link linkend="prod28">criteria</link> )</para></entry></row>
+( ( ( <RIGHT> ( <OUTER> )? ) | ( <LEFT> ( <OUTER> )? ) | ( <FULL> ( <OUTER> )? ) | <INNER> )? <JOIN> <link linkend="prod56">tableReference</link> <ON> <link linkend="prod28">criteria</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod57" xreflabel="tablePrimary"/>tablePrimary</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod59" xreflabel="tablePrimary"/>tablePrimary</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod60">unaryFromClause</link> | <link linkend="prod61">subqueryFromClause</link> | ( <LPAREN> <link linkend="prod56">joinedTable</link> <RPAREN> ) ) ( ( <MAKEDEP> ) | ( <MAKENOTDEP> ) )?</para></entry></row>
+( <link linkend="prod62">unaryFromClause</link> | <link linkend="prod63">subqueryFromClause</link> | ( <LPAREN> <link linkend="prod58">joinedTable</link> <RPAREN> ) ) ( ( <MAKEDEP> ) | ( <MAKENOTDEP> ) )?</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod61" xreflabel="subqueryFromClause"/>subqueryFromClause</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod63" xreflabel="subqueryFromClause"/>subqueryFromClause</para></entry>
<entry align="left" valign="top"><para>::=
<LPAREN> ( <link linkend="prod7">queryExpression</link> | <link linkend="prod8">storedProcedure</link> ) <RPAREN> ( <AS> )? <link linkend="prod2">id</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod60" xreflabel="unaryFromClause"/>unaryFromClause</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod62" xreflabel="unaryFromClause"/>unaryFromClause</para></entry>
<entry align="left" valign="top"><para>::=
( <ID> ( ( <AS> )? <link linkend="prod2">id</link> )? )</para></entry></row>
<row>
@@ -599,69 +604,69 @@
<row>
<entry align="right" valign="top"><para><anchor id="prod28" xreflabel="criteria"/>criteria</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod62">compoundCritOr</link></para></entry></row>
+<link linkend="prod64">compoundCritOr</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod62" xreflabel="compoundCritOr"/>compoundCritOr</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod64" xreflabel="compoundCritOr"/>compoundCritOr</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod63">compoundCritAnd</link> ( <OR> <link linkend="prod63">compoundCritAnd</link> )*</para></entry></row>
+<link linkend="prod65">compoundCritAnd</link> ( <OR> <link linkend="prod65">compoundCritAnd</link> )*</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod63" xreflabel="compoundCritAnd"/>compoundCritAnd</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod65" xreflabel="compoundCritAnd"/>compoundCritAnd</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod64">notCrit</link> ( <AND> <link linkend="prod64">notCrit</link> )*</para></entry></row>
+<link linkend="prod66">notCrit</link> ( <AND> <link linkend="prod66">notCrit</link> )*</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod64" xreflabel="notCrit"/>notCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod66" xreflabel="notCrit"/>notCrit</para></entry>
<entry align="left" valign="top"><para>::=
-( <NOT> )? <link linkend="prod65">primary</link></para></entry></row>
+( <NOT> )? <link linkend="prod67">primary</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod65" xreflabel="primary"/>primary</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod67" xreflabel="primary"/>primary</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod66">predicate</link> | ( <LPAREN> <link linkend="prod28">criteria</link> <RPAREN> ) )</para></entry></row>
+( <link linkend="prod68">predicate</link> | ( <LPAREN> <link linkend="prod28">criteria</link> <RPAREN> ) )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod66" xreflabel="predicate"/>predicate</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod68" xreflabel="predicate"/>predicate</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod67">subqueryCompareCriteria</link> | <link linkend="prod68">compareCrit</link> | <link linkend="prod69">matchCrit</link> | <link linkend="prod70">betweenCrit</link> | <link linkend="prod71">setCrit</link> | <link linkend="prod72">existsCriteria</link> | <link linkend="prod30">hasCriteria</link> | <link linkend="prod34">translateCriteria</link> | <link linkend="prod73">isNullCrit</link> )</para></entry></row>
+( <link linkend="prod69">subqueryCompareCriteria</link> | <link linkend="prod70">compareCrit</link> | <link linkend="prod71">matchCrit</link> | <link linkend="prod72">betweenCrit</link> | <link linkend="prod73">setCrit</link> | <link linkend="prod74">existsCriteria</link> | <link linkend="prod30">hasCriteria</link> | <link linkend="prod34">translateCriteria</link> | <link linkend="prod75">isNullCrit</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod68" xreflabel="compareCrit"/>compareCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod70" xreflabel="compareCrit"/>compareCrit</para></entry>
<entry align="left" valign="top"><para>::=
<link linkend="prod16">expression</link> ( <EQ> | <NE> | <NE2> | <LT> | <LE> | <GT> | <GE> ) <link linkend="prod16">expression</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod74" xreflabel="subquery"/>subquery</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod76" xreflabel="subquery"/>subquery</para></entry>
<entry align="left" valign="top"><para>::=
<LPAREN> ( <link linkend="prod7">queryExpression</link> | <link linkend="prod8">storedProcedure</link> ) <RPAREN></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod67" xreflabel="subqueryCompareCriteria"/>subqueryCompareCriteria</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod69" xreflabel="subqueryCompareCriteria"/>subqueryCompareCriteria</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod16">expression</link> ( <EQ> | <NE> | <NE2> | <LT> | <LE> | <GT> | <GE> ) ( <ANY> | <SOME> | <ALL> ) <link linkend="prod74">subquery</link></para></entry></row>
+<link linkend="prod16">expression</link> ( <EQ> | <NE> | <NE2> | <LT> | <LE> | <GT> | <GE> ) ( <ANY> | <SOME> | <ALL> ) <link linkend="prod76">subquery</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod69" xreflabel="matchCrit"/>matchCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod71" xreflabel="matchCrit"/>matchCrit</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod16">expression</link> ( <NOT> )? <LIKE> <link linkend="prod16">expression</link> ( <link linkend="prod75">escapeChar</link> | ( <LBRACE> <link linkend="prod75">escapeChar</link> <RBRACE> ) )? )</para></entry></row>
+( <link linkend="prod16">expression</link> ( <NOT> )? <LIKE> <link linkend="prod16">expression</link> ( <link linkend="prod77">escapeChar</link> | ( <LBRACE> <link linkend="prod77">escapeChar</link> <RBRACE> ) )? )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod75" xreflabel="escapeChar"/>escapeChar</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod77" xreflabel="escapeChar"/>escapeChar</para></entry>
<entry align="left" valign="top"><para>::=
<ESCAPE> <link linkend="prod1">stringVal</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod70" xreflabel="betweenCrit"/>betweenCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod72" xreflabel="betweenCrit"/>betweenCrit</para></entry>
<entry align="left" valign="top"><para>::=
<link linkend="prod16">expression</link> ( <NOT> )? <BETWEEN> <link linkend="prod16">expression</link> <AND> <link linkend="prod16">expression</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod73" xreflabel="isNullCrit"/>isNullCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod75" xreflabel="isNullCrit"/>isNullCrit</para></entry>
<entry align="left" valign="top"><para>::=
<link linkend="prod16">expression</link> <IS> ( <NOT> )? <NULL></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod71" xreflabel="setCrit"/>setCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod73" xreflabel="setCrit"/>setCrit</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod16">expression</link> ( <NOT> )? <IN> ( ( <link linkend="prod74">subquery</link> ) | ( <LPAREN> <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* <RPAREN> ) )</para></entry></row>
+<link linkend="prod16">expression</link> ( <NOT> )? <IN> ( ( <link linkend="prod76">subquery</link> ) | ( <LPAREN> <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* <RPAREN> ) )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod72" xreflabel="existsCriteria"/>existsCriteria</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod74" xreflabel="existsCriteria"/>existsCriteria</para></entry>
<entry align="left" valign="top"><para>::=
-<EXISTS> <link linkend="prod74">subquery</link></para></entry></row>
+<EXISTS> <link linkend="prod76">subquery</link></para></entry></row>
<row>
<entry align="right" valign="top"><para><anchor id="prod50" xreflabel="groupBy"/>groupBy</para></entry>
<entry align="left" valign="top"><para>::=
-<GROUP> <BY> ( <link linkend="prod76">groupByItem</link> ( <COMMA> <link linkend="prod76">groupByItem</link> )* )</para></entry></row>
+<GROUP> <BY> ( <link linkend="prod78">groupByItem</link> ( <COMMA> <link linkend="prod78">groupByItem</link> )* )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod76" xreflabel="groupByItem"/>groupByItem</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod78" xreflabel="groupByItem"/>groupByItem</para></entry>
<entry align="left" valign="top"><para>::=
<link linkend="prod16">expression</link></para></entry></row>
<row>
@@ -671,9 +676,9 @@
<row>
<entry align="right" valign="top"><para><anchor id="prod43" xreflabel="orderby"/>orderby</para></entry>
<entry align="left" valign="top"><para>::=
-<ORDER> <BY> <link linkend="prod77">sortKey</link> ( <ASC> | <DESC> )? ( <COMMA> <link linkend="prod77">sortKey</link> ( <ASC> | <DESC> )? )*</para></entry></row>
+<ORDER> <BY> <link linkend="prod79">sortKey</link> ( <ASC> | <DESC> )? ( <COMMA> <link linkend="prod79">sortKey</link> ( <ASC> | <DESC> )? )*</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod77" xreflabel="sortKey"/>sortKey</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod79" xreflabel="sortKey"/>sortKey</para></entry>
<entry align="left" valign="top"><para>::=
<link linkend="prod16">expression</link></para></entry></row>
<row>
@@ -683,57 +688,65 @@
<row>
<entry align="right" valign="top"><para><anchor id="prod37" xreflabel="option"/>option</para></entry>
<entry align="left" valign="top"><para>::=
-<OPTION> ( <SHOWPLAN> | <PLANONLY> | <DEBUG> | <MAKEDEP> <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* | <MAKENOTDEP> <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* | <NOCACHE> ( <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* )? )*</para></entry></row>
+<OPTION> ( <MAKEDEP> <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* | <MAKENOTDEP> <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* | <NOCACHE> ( <link linkend="prod2">id</link> ( <COMMA> <link linkend="prod2">id</link> )* )? )*</para></entry></row>
<row>
<entry align="right" valign="top"><para><anchor id="prod16" xreflabel="expression"/>expression</para></entry>
<entry align="left" valign="top"><para>::=
-<link linkend="prod78">concatExpression</link></para></entry></row>
+<link linkend="prod80">concatExpression</link></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod78" xreflabel="concatExpression"/>concatExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod80" xreflabel="concatExpression"/>concatExpression</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod79">plusExpression</link> ( <CONCAT_OP> <link linkend="prod79">plusExpression</link> )* )</para></entry></row>
+( <link linkend="prod81">plusExpression</link> ( <CONCAT_OP> <link linkend="prod81">plusExpression</link> )* )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod79" xreflabel="plusExpression"/>plusExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod81" xreflabel="plusExpression"/>plusExpression</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod80">timesExpression</link> ( <link linkend="prod81">plusOperator</link> <link linkend="prod80">timesExpression</link> )* )</para></entry></row>
+( <link linkend="prod82">timesExpression</link> ( <link linkend="prod83">plusOperator</link> <link linkend="prod82">timesExpression</link> )* )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod81" xreflabel="plusOperator"/>plusOperator</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod83" xreflabel="plusOperator"/>plusOperator</para></entry>
<entry align="left" valign="top"><para>::=
( <PLUS> | <MINUS> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod80" xreflabel="timesExpression"/>timesExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod82" xreflabel="timesExpression"/>timesExpression</para></entry>
<entry align="left" valign="top"><para>::=
-( <link linkend="prod82">basicExpression</link> ( <link linkend="prod83">timesOperator</link> <link linkend="prod82">basicExpression</link> )* )</para></entry></row>
+( <link linkend="prod84">basicExpression</link> ( <link linkend="prod85">timesOperator</link> <link linkend="prod84">basicExpression</link> )* )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod83" xreflabel="timesOperator"/>timesOperator</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod85" xreflabel="timesOperator"/>timesOperator</para></entry>
<entry align="left" valign="top"><para>::=
( <STAR> | <SLASH> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod82" xreflabel="basicExpression"/>basicExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod84" xreflabel="basicExpression"/>basicExpression</para></entry>
<entry align="left" valign="top"><para>::=
-( <QMARK> | <link linkend="prod84">literal</link> | ( <LBRACE> <FN> <link linkend="prod85">function</link> <RBRACE> ) | ( <link linkend="prod53">aggregateSymbol</link> ) | ( <link linkend="prod85">function</link> ) | ( <ID> ) | ( <LPAREN> <link linkend="prod16">expression</link> <RPAREN> ) | <link linkend="prod74">subquery</link> | <link linkend="prod86">caseExpression</link> | <link linkend="prod87">searchedCaseExpression</link> )</para></entry></row>
+( <QMARK> | <link linkend="prod86">literal</link> | ( <LBRACE> <FN> <link linkend="prod87">function</link> <RBRACE> ) | ( <link linkend="prod55">aggregateSymbol</link> ) | ( <link linkend="prod87">function</link> ) | ( <ID> ) | ( <LPAREN> <link linkend="prod16">expression</link> <RPAREN> ) | <link linkend="prod76">subquery</link> | <link linkend="prod88">caseExpression</link> | <link linkend="prod89">searchedCaseExpression</link> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod86" xreflabel="caseExpression"/>caseExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod88" xreflabel="caseExpression"/>caseExpression</para></entry>
<entry align="left" valign="top"><para>::=
<CASE> <link linkend="prod16">expression</link> ( <WHEN> <link linkend="prod16">expression</link> <THEN> <link linkend="prod16">expression</link> )+ ( <ELSE> <link linkend="prod16">expression</link> )? <END></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod87" xreflabel="searchedCaseExpression"/>searchedCaseExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod89" xreflabel="searchedCaseExpression"/>searchedCaseExpression</para></entry>
<entry align="left" valign="top"><para>::=
<CASE> ( <WHEN> <link linkend="prod28">criteria</link> <THEN> <link linkend="prod16">expression</link> )+ ( <ELSE> <link linkend="prod16">expression</link> )? <END></para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod85" xreflabel="function"/>function</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod87" xreflabel="function"/>function</para></entry>
<entry align="left" valign="top"><para>::=
-( ( <CONVERT> <LPAREN> <link linkend="prod16">expression</link> <COMMA> <link linkend="prod31">dataType</link> <RPAREN> ) | ( <CAST> <LPAREN> <link linkend="prod16">expression</link> <AS> <link linkend="prod31">dataType</link> <RPAREN> ) | ( ( <TIMESTAMPADD> | <TIMESTAMPDIFF> ) <LPAREN> <link linkend="prod88">intervalType</link> <COMMA> <link linkend="prod16">expression</link> <COMMA> <link linkend="prod16">expression</link> <RPAREN> ) | ( ( <LEFT> | <RIGHT> | <CHAR> | <USER> | <YEAR> | <MONTH> | <HOUR> | <MINUTE> | <SECOND> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) | ( ( <INSERT> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) | ( ( <TRANSLAT!
E> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) | ( <link linkend="prod2">id</link> <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) )</para></entry></row>
+( ( <CONVERT> <LPAREN> <link linkend="prod16">expression</link> <COMMA> <link linkend="prod31">dataType</link> <RPAREN> ) | ( <CAST> <LPAREN> <link linkend="prod16">expression</link> <AS> <link linkend="prod31">dataType</link> <RPAREN> ) | ( ( <TIMESTAMPADD> | <TIMESTAMPDIFF> ) <LPAREN> <link linkend="prod90">intervalType</link> <COMMA> <link linkend="prod16">expression</link> <COMMA> <link linkend="prod16">expression</link> <RPAREN> ) | ( ( <LEFT> | <RIGHT> | <CHAR> | <USER> | <YEAR> | <MONTH> | <HOUR> | <MINUTE> | <SECOND> | <XMLCONCAT> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) | ( ( <INSERT> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> !
) | ( ( <TRANSLATE> ) <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) | ( <XMLELEMENT> <LPAREN> ( <ID> <link linkend="prod91">idExpression</link> | <link linkend="prod91">idExpression</link> ) ( <COMMA> <link linkend="prod92">sqlXmlFunction</link> )? ( <COMMA> <link linkend="prod16">expression</link> )* <RPAREN> ) | ( <link linkend="prod92">sqlXmlFunction</link> ) | ( <link linkend="prod2">id</link> <LPAREN> ( <link linkend="prod16">expression</link> ( <COMMA> <link linkend="prod16">expression</link> )* )? <RPAREN> ) )</para></entry></row>
<row>
+<entry align="right" valign="top"><para><anchor id="prod92" xreflabel="sqlXmlFunction"/>sqlXmlFunction</para></entry>
+<entry align="left" valign="top"><para>::=
+( <XMLFOREST> | <XMLATTRIBUTES> ) <LPAREN> <link linkend="prod53">selectExpression</link> ( <COMMA> <link linkend="prod53">selectExpression</link> )* <RPAREN></para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod91" xreflabel="idExpression"/>idExpression</para></entry>
+<entry align="left" valign="top"><para>::=
+<link linkend="prod2">id</link></para></entry></row>
+<row>
<entry align="right" valign="top"><para><anchor id="prod31" xreflabel="dataType"/>dataType</para></entry>
<entry align="left" valign="top"><para>::=
( <STRING> | <VARCHAR> | <BOOLEAN> | <BYTE> | <TINYINT> | <SHORT> | <SMALLINT> | <CHAR> | <INTEGER> | <LONG> | <BIGINT> | <BIGINTEGER> | <FLOAT> | <REAL> | <DOUBLE> | <BIGDECIMAL> | <DECIMAL> | <DATE> | <TIME> | <TIMESTAMP> | <OBJECT> | <BLOB> | <CLOB> | <XML> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod88" xreflabel="intervalType"/>intervalType</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod90" xreflabel="intervalType"/>intervalType</para></entry>
<entry align="left" valign="top"><para>::=
( <SQL_TSI_FRAC_SECOND> | <SQL_TSI_SECOND> | <SQL_TSI_MINUTE> | <SQL_TSI_HOUR> | <SQL_TSI_DAY> | <SQL_TSI_WEEK> | <SQL_TSI_MONTH> | <SQL_TSI_QUARTER> | <SQL_TSI_YEAR> )</para></entry></row>
<row>
-<entry align="right" valign="top"><para><anchor id="prod84" xreflabel="literal"/>literal</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod86" xreflabel="literal"/>literal</para></entry>
<entry align="left" valign="top"><para>::=
( <link linkend="prod1">stringVal</link> | <INTEGERVAL> | <FLOATVAL> | <FALSE> | <TRUE> | <UNKNOWN> | <NULL> | ( ( <BOOLEANTYPE> | <TIMESTAMPTYPE> | <DATETYPE> | <TIMETYPE> ) <link linkend="prod1">stringVal</link> <RBRACE> ) )</para></entry></row>
</tbody>
Modified: trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml 2010-05-06 17:17:44 UTC (rev 2100)
@@ -1950,30 +1950,58 @@
</entry>
<entry>
<para>Takes a document and an xsl stylesheet and returns a
- clob of the result.</para>
+ clob of the result. If either argument is null, the result is null.</para>
</entry>
<entry>
- <para>Doc, xsl in {xml}. Return value is a clob.
+ <para>Doc, xsl in {string, xml}. Return value is a clob.
</para>
</entry>
</row>
<row>
<entry>
- <para><code>XMLELEMENT(name [, content]*)</code></para>
+ <para><code>XMLELEMENT([NAME] name [, <ATTR>][, exp]*)</code>
+ ATTR:=<code>XMLATTRIBUTES(exp [AS name] [, exp [AS name]]*)</code></para>
</entry>
<entry>
- <para>Returns an XML element with the given name and conent. If the content value is of a type other than xml,
+ <para>Returns an XML element with the given name and content. 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>Example: with an xml_value of <doc/>, <code>xmlelement('myelement', 1, '<2/>', xml_value)</code>
- Returns: <code><myelement>1&lt;2/&gt;<doc/>></code>
+ <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>Example: with an xml_value of <doc/>, <code>xmlelement('elem', 1, '<2/>', xml_value)</code>
+ Returns: <code><elem>1&lt;2/&gt;<doc/><elem/></code>
</para>
</entry>
<entry>
- <para>Name in {string}. Content can be any type. Return value is xml.
+ <para>Name is an identifier. exp can be any type. Return value is xml.
</para>
</entry>
</row>
+ <row>
+ <entry>
+ <para><code>XMLCONCAT(xml [, other]*)</code></para>
+ </entry>
+ <entry>
+ <para>Returns an XML with the concatination of the given xml types. If a value is null, it will be ignored.
+ </para>
+ </entry>
+ <entry>
+ <para>Name is an identifier. Content can be any type. Return value is xml.
+ </para>
+ </entry>
+ </row>
+ <row>
+ <entry>
+ <para><code>XMLFOREST(exp [AS name], [exp [AS name]]*)</code></para>
+ </entry>
+ <entry>
+ <para>Returns an concatination of an XML element for each non-null expression exp. If a name is not supplied, the expression must be a column reference, in which case the element name will be the column name.
+ </para>
+ </entry>
+ <entry>
+ <para>Name is an identifier. exp can be any type. Return value is xml.
+ </para>
+ </entry>
+ </row>
</tbody>
</tgroup>
</informaltable>
Modified: trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/common/buffer/impl/BufferManagerImpl.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -44,6 +44,7 @@
import javax.xml.transform.Source;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BatchManager;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.FileStore;
@@ -364,6 +365,7 @@
@Override
public void initialize() throws MetaMatrixComponentException {
+ //TODO: remove me - connectors should be able to do this statefully
DataTypeManager.addSourceTransform(Source.class, new SourceTransform<Source, XMLType>() {
@Override
public XMLType transform(Source value) {
@@ -376,12 +378,14 @@
sqlxml = XMLUtil.saveToBufferManager(BufferManagerImpl.this, sxt, Streamable.STREAMING_BATCH_SIZE_IN_BYTES);
} catch (MetaMatrixComponentException e) {
throw new MetaMatrixRuntimeException(e);
+ } catch (MetaMatrixProcessingException e) {
+ throw new MetaMatrixRuntimeException(e);
}
return new XMLType(sqlxml);
}
});
}
-
+
@Override
public void releaseBuffers(int count) {
if (count < 1) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -37,6 +37,7 @@
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.CriteriaEvaluationException;
import com.metamatrix.api.exception.query.ExpressionEvaluationException;
+import com.metamatrix.api.exception.query.FunctionExecutionException;
import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.types.Sequencable;
import com.metamatrix.core.util.Assertion;
@@ -45,6 +46,8 @@
import com.metamatrix.query.function.FunctionDescriptor;
import com.metamatrix.query.function.FunctionLibrary;
import com.metamatrix.query.function.metadata.FunctionMethod;
+import com.metamatrix.query.function.source.XMLSystemFunctions;
+import com.metamatrix.query.function.source.XMLSystemFunctions.NameValuePair;
import com.metamatrix.query.processor.ProcessorDataManager;
import com.metamatrix.query.sql.LanguageObject;
import com.metamatrix.query.sql.lang.AbstractSetCriteria;
@@ -62,6 +65,7 @@
import com.metamatrix.query.sql.lang.SubqueryContainer;
import com.metamatrix.query.sql.lang.SubquerySetCriteria;
import com.metamatrix.query.sql.symbol.AggregateSymbol;
+import com.metamatrix.query.sql.symbol.AliasSymbol;
import com.metamatrix.query.sql.symbol.CaseExpression;
import com.metamatrix.query.sql.symbol.Constant;
import com.metamatrix.query.sql.symbol.ContextReference;
@@ -69,6 +73,7 @@
import com.metamatrix.query.sql.symbol.ExpressionSymbol;
import com.metamatrix.query.sql.symbol.Function;
import com.metamatrix.query.sql.symbol.Reference;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
@@ -556,6 +561,27 @@
return internalEvaluate(ref.getExpression(), tuple);
} else if(expression instanceof ScalarSubquery) {
return evaluate((ScalarSubquery) expression, tuple);
+ } else if (expression instanceof SQLXMLFunction){
+ SQLXMLFunction function = (SQLXMLFunction)expression;
+ List<SingleElementSymbol> args = function.getArgs();
+ NameValuePair[] nameValuePairs = new NameValuePair[args.size()];
+ for(int i=0; i < args.size(); i++) {
+ SingleElementSymbol symbol = args.get(i);
+ String name = symbol.getShortName();
+ Expression ex = symbol;
+ if (symbol instanceof AliasSymbol) {
+ ex = ((AliasSymbol)symbol).getSymbol();
+ }
+ nameValuePairs[i] = new NameValuePair(name, internalEvaluate(ex, tuple));
+ }
+ if (FunctionLibrary.XMLFOREST.equalsIgnoreCase(function.getName())) {
+ try {
+ return XMLSystemFunctions.xmlForest(context, nameValuePairs);
+ } catch (MetaMatrixProcessingException e) {
+ throw new FunctionExecutionException(e, e.getMessage());
+ }
+ }
+ return nameValuePairs;
} else {
throw new MetaMatrixComponentException(ErrorMessageKeys.PROCESSOR_0016, QueryPlugin.Util.getString(ErrorMessageKeys.PROCESSOR_0016, expression.getClass().getName()));
}
@@ -636,7 +662,7 @@
} catch (MetaMatrixProcessingException e) {
throw new ExpressionEvaluationException(e, e.getMessage());
}
- }
+ }
// Execute function
Object result = fd.invokeFunction(values);
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/FunctionLibrary.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/FunctionLibrary.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/FunctionLibrary.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -87,6 +87,9 @@
public static final String SPACE = "space"; //$NON-NLS-1$
+ public static final String XMLFOREST = "xmlforest"; //$NON-NLS-1$
+ public static final String XMLATTRIBUTES = "xmlattributes"; //$NON-NLS-1$
+
// Function tree for system functions (never reloaded)
private FunctionTree systemFunctions;
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/source/SystemSource.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -169,6 +169,7 @@
addXpathFunction();
addXslTransformFunction();
addXmlElement();
+ addXmlConcat();
addSecurityFunctions();
@@ -903,16 +904,41 @@
new FunctionParameter("document", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
new FunctionParameter("xsl", DataTypeManager.DefaultDataTypes.XML, 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$
+ 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", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("xsl", DataTypeManager.DefaultDataTypes.STRING, 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$
+
+ 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", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("xsl", DataTypeManager.DefaultDataTypes.XML, 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$
+
+ 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", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xsltransform_param1")), //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("xsl", DataTypeManager.DefaultDataTypes.STRING, 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 addXmlElement() {
- functions.add(new FunctionMethod(SourceSystemFunctions.XMLELEMENT, QueryPlugin.Util.getString("SystemSource.xsltransform_description"), XML, XML_FUNCTION_CLASS, "xmlElement", //$NON-NLS-1$ //$NON-NLS-2$
+ functions.add(new FunctionMethod(SourceSystemFunctions.XMLELEMENT, QueryPlugin.Util.getString("SystemSource.xmlelement_description"), XML, FunctionMethod.CAN_PUSHDOWN, XML_FUNCTION_CLASS, "xmlElement", //$NON-NLS-1$ //$NON-NLS-2$
new FunctionParameter[] {
new FunctionParameter("name", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.xmlelement_param1")), //$NON-NLS-1$ //$NON-NLS-2$
new FunctionParameter("value", DataTypeManager.DefaultDataTypes.OBJECT, QueryPlugin.Util.getString("SystemSource.xmlelement_param2"), true)}, //$NON-NLS-1$ //$NON-NLS-2$
- new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlement_result")) ) ); //$NON-NLS-1$ //$NON-NLS-2$
+ new FunctionParameter("result", DataTypeManager.DefaultDataTypes.XML, QueryPlugin.Util.getString("SystemSource.xmlement_result")), true, FunctionMethod.DETERMINISTIC ) ); //$NON-NLS-1$ //$NON-NLS-2$
}
+ private void addXmlConcat() {
+ functions.add(new FunctionMethod(SourceSystemFunctions.XMLCONCAT, QueryPlugin.Util.getString("SystemSource.xmlconcat_description"), XML, FunctionMethod.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, FunctionMethod.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[] {
@@ -970,7 +996,7 @@
* @return Class reference
* @throws ClassNotFoundException If class could not be found
*/
- public Class getInvocationClass(String className) throws ClassNotFoundException {
+ public Class<?> getInvocationClass(String className) throws ClassNotFoundException {
return Class.forName(className);
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/function/source/XMLSystemFunctions.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -22,14 +22,19 @@
package com.metamatrix.query.function.source;
+import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.sql.SQLException;
import java.sql.SQLXML;
+import java.sql.Timestamp;
+import java.util.Calendar;
+import javax.xml.namespace.QName;
import javax.xml.stream.EventFilter;
+import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
@@ -47,6 +52,7 @@
import net.sf.saxon.trans.XPathException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.FunctionExecutionException;
import com.metamatrix.common.types.ClobType;
import com.metamatrix.common.types.DataTypeManager;
@@ -54,8 +60,10 @@
import com.metamatrix.common.types.TransformationException;
import com.metamatrix.common.types.XMLTranslator;
import com.metamatrix.common.types.XMLType;
+import com.metamatrix.common.types.XMLType.Type;
import com.metamatrix.internal.core.xml.XPathHelper;
import com.metamatrix.query.QueryPlugin;
+import com.metamatrix.query.function.FunctionMethods;
import com.metamatrix.query.processor.xml.XMLUtil;
import com.metamatrix.query.util.CommandContext;
@@ -65,6 +73,31 @@
* @since 4.2
*/
public class XMLSystemFunctions {
+
+ public static class NameValuePair {
+ String name;
+ Object value;
+
+ public NameValuePair(String name, Object value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //YEAR 0 in the server timezone. used to determine negative years
+ public static long YEAR_ZERO;
+ static String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$
+
+ static String TIMESTAMP_MICROZEROS = "000000000"; //$NON-NLS-1$
+
+ static {
+ Calendar cal = Calendar.getInstance();
+
+ for (int i = 0; i <= Calendar.MILLISECOND; i++) {
+ cal.set(i, 0);
+ }
+ YEAR_ZERO = cal.getTimeInMillis();
+ }
public static Object xpathValue(Object document, Object xpathStr) throws FunctionExecutionException {
Reader stream = null;
@@ -89,7 +122,19 @@
throw new FunctionExecutionException(QueryPlugin.Util.getString("XMLSystemFunctions.wrap_exception", xpathStr, e.getMessage())); //$NON-NLS-1$
}
}
-
+
+ public static ClobType xslTransform(CommandContext context, String xmlResults, String styleSheet) throws Exception {
+ return xslTransform(context, DataTypeManager.transformValue(xmlResults, DataTypeManager.DefaultDataClasses.XML), DataTypeManager.transformValue(styleSheet, DataTypeManager.DefaultDataClasses.XML));
+ }
+
+ public static ClobType xslTransform(CommandContext context, String xmlResults, XMLType styleSheet) throws Exception {
+ return xslTransform(context, DataTypeManager.transformValue(xmlResults, DataTypeManager.DefaultDataClasses.XML), styleSheet);
+ }
+
+ public static ClobType xslTransform(CommandContext context, XMLType xmlResults, String styleSheet) throws Exception {
+ return xslTransform(context, xmlResults, DataTypeManager.transformValue(styleSheet, DataTypeManager.DefaultDataClasses.XML));
+ }
+
public static ClobType xslTransform(CommandContext context, XMLType xmlResults, XMLType styleSheet) throws Exception {
Reader styleSheetReader = styleSheet.getCharacterStream();
final Source styleSource = new StreamSource(styleSheetReader);
@@ -103,6 +148,7 @@
public void translate(Writer writer) throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(styleSource);
+ //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
// Feed the resultant I/O stream into the XSLT processor
transformer.transform(xmlSource, new StreamResult(writer));
}
@@ -119,17 +165,55 @@
}
}
}
+
+ public static XMLType xmlForest(final CommandContext context, final NameValuePair[] values) throws MetaMatrixComponentException, MetaMatrixProcessingException {
+ boolean valueExists = false;
+ for (NameValuePair nameValuePair : values) {
+ if (nameValuePair.value != null) {
+ valueExists = true;
+ break;
+ }
+ }
+ if (!valueExists) {
+ return null;
+ }
+
+ XMLType result = new XMLType(XMLUtil.saveToBufferManager(context.getBufferManager(), new XMLTranslator() {
+
+ @Override
+ public void translate(Writer writer) throws TransformerException,
+ IOException {
+ try {
+ XMLOutputFactory factory = XMLOutputFactory.newInstance();
+ XMLEventWriter eventWriter = factory.createXMLEventWriter(writer);
+ XMLEventFactory eventFactory = XMLEventFactory.newInstance();
+ for (NameValuePair nameValuePair : values) {
+ if (nameValuePair.value == null) {
+ continue;
+ }
+ addElement(nameValuePair.name, writer, eventWriter, eventFactory, nameValuePair.value);
+ }
+ } catch (XMLStreamException e) {
+ throw new TransformerException(e);
+ }
+ }
+ }, context.getStreamingBatchSize()));
+ result.setType(Type.SIBLINGS);
+ return result;
+ }
/**
- * Basic support for xmlelement. Attributes are not yet supported.
+ * Basic support for xmlelement. namespaces are not yet supported.
* @param context
* @param name
* @param contents
* @return
* @throws MetaMatrixComponentException
+ * @throws MetaMatrixProcessingException
*/
- public static XMLType xmlElement(CommandContext context, final String name, final Object... contents) throws MetaMatrixComponentException {
- return new XMLType(XMLUtil.saveToBufferManager(context.getBufferManager(), new XMLTranslator() {
+ public static XMLType xmlElement(CommandContext context, final String name,
+ final Object... contents) throws MetaMatrixComponentException, MetaMatrixProcessingException {
+ XMLType result = new XMLType(XMLUtil.saveToBufferManager(context.getBufferManager(), new XMLTranslator() {
@Override
public void translate(Writer writer) throws TransformerException,
@@ -138,48 +222,162 @@
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLEventWriter eventWriter = factory.createXMLEventWriter(writer);
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
- eventWriter.add(eventFactory.createStartElement("", null, name)); //$NON-NLS-1$
- for (Object object : contents) {
- if (object == null) {
- continue;
- }
- if (object instanceof XMLType) {
- Reader r = null;
- try {
- r = ((XMLType)object).getCharacterStream();
- XMLInputFactory inputFactory = XMLInputFactory.newInstance();
- XMLEventReader xmlEventReader = inputFactory.createFilteredReader(inputFactory.createXMLEventReader(r), new EventFilter() {
-
- @Override
- public boolean accept(XMLEvent event) {
- return !event.isStartDocument() && !event.isEndDocument();
- }
- });
- eventWriter.add(xmlEventReader);
- } catch (SQLException e) {
- throw new IOException(e);
- } finally {
- if (r != null) {
- r.close();
- }
- }
- } else {
- try {
- String result = DataTypeManager.transformValue(object, DataTypeManager.DefaultDataClasses.STRING);
- eventWriter.add(eventFactory.createCharacters(result));
- } catch (TransformationException e) {
- throw new TransformerException(e);
- }
- }
- }
- eventWriter.add(eventFactory.createEndElement("", null, name)); //$NON-NLS-1$
+ addElement(name, writer, eventWriter, eventFactory, contents);
} catch (XMLStreamException e) {
throw new TransformerException(e);
- } finally {
-
+ }
+ }
+
+ }, context.getStreamingBatchSize()));
+ result.setType(Type.FRAGMENT);
+ return result;
+ }
+
+ private static void addElement(final String name, Writer writer, XMLEventWriter eventWriter, XMLEventFactory eventFactory,
+ Object... contents) throws XMLStreamException, IOException, TransformerException {
+ eventWriter.add(eventFactory.createStartElement("", null, name)); //$NON-NLS-1$
+ int start = 0;
+ if (contents.length > 0 && contents[0] instanceof NameValuePair[]) {
+ for (NameValuePair nameValuePair : (NameValuePair[])contents[0]) {
+ if (nameValuePair.value != null) {
+ eventWriter.add(eventFactory.createAttribute(new QName(nameValuePair.name), getStringValue(nameValuePair.value)));
}
}
+ start = 1;
+ }
+ //add empty chars to close the start tag
+ eventWriter.add(eventFactory.createCharacters("")); //$NON-NLS-1$
+ for (int i = start; i < contents.length; i++) {
+ convertValue(writer, eventWriter, eventFactory, contents[i]);
+ }
+ eventWriter.add(eventFactory.createEndElement("", null, name)); //$NON-NLS-1$
+ }
+
+ public static XMLType xmlConcat(CommandContext context, final XMLType xml, final Object... other) throws MetaMatrixComponentException, MetaMatrixProcessingException {
+ XMLType result = new XMLType(XMLUtil.saveToBufferManager(context.getBufferManager(), new XMLTranslator() {
+
+ @Override
+ public void translate(Writer writer) throws TransformerException,
+ IOException {
+ try {
+ XMLOutputFactory factory = XMLOutputFactory.newInstance();
+ XMLEventWriter eventWriter = factory.createXMLEventWriter(writer);
+ XMLEventFactory eventFactory = XMLEventFactory.newInstance();
+ convertValue(writer, eventWriter, eventFactory, xml);
+ for (Object object : other) {
+ convertValue(writer, eventWriter, eventFactory, object);
+ }
+ } catch (XMLStreamException e) {
+ throw new TransformerException(e);
+ }
+ }
}, context.getStreamingBatchSize()));
+ result.setType(Type.SIBLINGS);
+ return result;
}
+ static String getStringValue(Object object) throws TransformerException {
+ if (object instanceof Timestamp) {
+ try {
+ return timestampToDateTime((Timestamp)object);
+ } catch (FunctionExecutionException e) {
+ throw new TransformerException(e);
+ }
+ }
+ try {
+ return DataTypeManager.transformValue(object, DataTypeManager.DefaultDataClasses.STRING);
+ } catch (TransformationException e) {
+ throw new TransformerException(e);
+ }
+ }
+
+ static void convertValue(Writer writer, XMLEventWriter eventWriter, XMLEventFactory eventFactory, Object object) throws IOException,
+ FactoryConfigurationError, XMLStreamException,
+ TransformerException {
+ if (object == null) {
+ return;
+ }
+ if (object instanceof XMLType) {
+ XMLType xml = (XMLType)object;
+ Reader r = null;
+ try {
+ r = xml.getCharacterStream();
+ if (!(r instanceof BufferedReader)) {
+ r = new BufferedReader(r);
+ }
+ switch(xml.getType()) {
+ case FRAGMENT:
+ case SIBLINGS: //write the value directly to the writer
+ eventWriter.flush();
+ int chr = -1;
+ while ((chr = r.read()) != -1) {
+ writer.write(chr);
+ }
+ break;
+ case UNKNOWN: //assume a document
+ case DOCUMENT: //filter the doc declaration
+ XMLInputFactory inputFactory = XMLInputFactory.newInstance();
+ XMLEventReader eventReader = inputFactory.createXMLEventReader(r);
+ eventReader = inputFactory.createFilteredReader(eventReader, new EventFilter() {
+ @Override
+ public boolean accept(XMLEvent event) {
+ return !event.isStartDocument() && !event.isEndDocument();
+ }
+ });
+ eventWriter.add(eventReader);
+ break;
+ }
+ } catch (SQLException e) {
+ throw new IOException(e);
+ } finally {
+ if (r != null) {
+ r.close();
+ }
+ }
+ } else {
+ String val = getStringValue(object);
+ eventWriter.add(eventFactory.createCharacters(val));
+ }
+ //TODO: blob - with base64 encoding
+ //TODO: full clob?
+ }
+
+ /**
+ * Formats a timestamp to an xs:dateTime. This uses DATETIME_FORMAT
+ * with a trailing string for nanoseconds (without right zeros).
+ */
+ public static String timestampToDateTime(Timestamp time) throws FunctionExecutionException {
+ String result = FunctionMethods.format(time, DATETIME_FORMAT);
+ int nanos = time.getNanos();
+ if (nanos == 0) {
+ return result;
+ }
+
+ StringBuffer resultBuffer = new StringBuffer();
+ boolean first = true;
+ int i = 0;
+ for (; i < 9 && nanos > 0; i++) {
+ int digit = nanos%10;
+ if (first) {
+ if (digit > 0) {
+ resultBuffer.insert(0, digit);
+ first = false;
+ }
+ } else {
+ resultBuffer.insert(0, digit);
+ }
+ nanos /= 10;
+ }
+ if (i < 9) {
+ resultBuffer.insert(0, TIMESTAMP_MICROZEROS.substring(i));
+ }
+ resultBuffer.insert(0, "."); //$NON-NLS-1$
+ resultBuffer.insert(0, result);
+ if (time.getTime() < YEAR_ZERO) {
+ resultBuffer.insert(0, "-"); //$NON-NLS-1$
+ }
+ return resultBuffer.toString();
+
+ }
+
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -36,11 +36,11 @@
import org.teiid.dqp.internal.process.Request;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.log.LogConstants;
import com.metamatrix.common.log.LogManager;
import com.metamatrix.core.id.IDGenerator;
@@ -144,10 +144,8 @@
PlanNode plan;
try {
plan = generatePlan(command);
- } catch (QueryResolverException e) {
+ } catch (MetaMatrixProcessingException e) {
throw new QueryPlannerException(e, e.getMessage());
- } catch (QueryValidatorException e) {
- throw new QueryPlannerException(e, e.getMessage());
}
if(debug) {
@@ -371,7 +369,7 @@
return plan;
}
- public PlanNode generatePlan(Command cmd) throws QueryPlannerException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public PlanNode generatePlan(Command cmd) throws MetaMatrixComponentException, MetaMatrixProcessingException {
//cascade the option clause nocache
Option savedOption = option;
option = cmd.getOption();
@@ -423,7 +421,7 @@
return result;
}
- PlanNode createUpdatePlan(Command command) throws QueryPlannerException, MetaMatrixComponentException, QueryResolverException, QueryValidatorException {
+ PlanNode createUpdatePlan(Command command) throws MetaMatrixComponentException, MetaMatrixProcessingException {
// Create top project node - define output columns for stored query / procedure
PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
@@ -462,8 +460,7 @@
private void addNestedProcedure(PlanNode sourceNode,
ProcedureContainer container) throws MetaMatrixComponentException,
- QueryMetadataException, QueryResolverException,
- QueryValidatorException, QueryPlannerException {
+ QueryMetadataException, MetaMatrixProcessingException {
//plan any subqueries in criteria/parameters/values
for (SubqueryContainer subqueryContainer : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(container)) {
ProcessorPlan plan = QueryOptimizer.optimizePlan(subqueryContainer.getCommand(), metadata, null, capFinder, analysisRecord, context);
@@ -490,7 +487,7 @@
}
}
- PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryPlannerException, QueryResolverException, QueryValidatorException, QueryMetadataException, MetaMatrixComponentException {
+ PlanNode createStoredProcedurePlan(StoredProcedure storedProc) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
// Create top project node - define output columns for stored query / procedure
PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
@@ -514,7 +511,7 @@
}
PlanNode createQueryPlan(QueryCommand command)
- throws QueryPlannerException, MetaMatrixComponentException, QueryResolverException, QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
// Build canonical plan
PlanNode node = null;
if(command instanceof Query) {
@@ -545,7 +542,7 @@
}
private PlanNode createQueryPlan(Query query)
- throws QueryPlannerException, QueryMetadataException, MetaMatrixComponentException, QueryResolverException, QueryValidatorException {
+ throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
PlanNode plan = null;
@@ -616,11 +613,10 @@
* as internal
* @throws MetaMatrixComponentException
* @throws QueryMetadataException
- * @throws QueryValidatorException
- * @throws QueryResolverException
+ * @throws MetaMatrixProcessingException
*/
void buildTree(FromClause clause, PlanNode parent)
- throws QueryPlannerException, QueryMetadataException, MetaMatrixComponentException, QueryResolverException, QueryValidatorException {
+ throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
PlanNode node = null;
@@ -694,9 +690,7 @@
}
private void addNestedCommand(PlanNode node,
- GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws QueryPlannerException,
- MetaMatrixComponentException, QueryResolverException,
- QueryValidatorException, QueryMetadataException {
+ GroupSymbol group, Command nestedCommand, Command toPlan, boolean merge) throws MetaMatrixComponentException, QueryMetadataException, MetaMatrixProcessingException {
if (nestedCommand instanceof QueryCommand) {
//remove unnecessary order by
QueryCommand queryCommand = (QueryCommand)nestedCommand;
@@ -871,7 +865,7 @@
}
private Command resolveVirtualGroup(GroupSymbol virtualGroup)
- throws QueryMetadataException, MetaMatrixComponentException, QueryResolverException, QueryValidatorException {
+ throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
QueryNode qnode = null;
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -60,6 +60,7 @@
import com.metamatrix.query.sql.symbol.CaseExpression;
import com.metamatrix.query.sql.symbol.Function;
import com.metamatrix.query.sql.symbol.GroupSymbol;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.util.SymbolMap;
@@ -94,6 +95,11 @@
this.caps = caps;
}
+ @Override
+ public void visit(SQLXMLFunction obj) {
+ markInvalid();
+ }
+
public void visit(AggregateSymbol obj) {
try {
if(! CapabilitiesUtil.supportsAggregateFunction(modelID, obj, metadata, capFinder)) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/FrameUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/FrameUtil.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/FrameUtil.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -32,10 +32,11 @@
import java.util.Set;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.metadata.QueryMetadataInterface;
@@ -282,8 +283,10 @@
// Simplify criteria if possible
try {
return QueryRewriter.rewriteCriteria(criteria, null, null, metadata);
- } catch(QueryValidatorException e) {
+ } catch(MetaMatrixProcessingException e) {
throw new QueryPlannerException(e, QueryExecPlugin.Util.getString(ErrorMessageKeys.OPTIMIZER_0023, criteria));
+ } catch (MetaMatrixComponentException e) {
+ throw new MetaMatrixRuntimeException(e);
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/JoinUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/JoinUtil.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/JoinUtil.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -26,7 +26,7 @@
import java.util.List;
import java.util.Set;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixException;
import com.metamatrix.core.util.Assertion;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.optimizer.relational.plantree.NodeConstants;
@@ -140,7 +140,7 @@
Criteria simplifiedCrit = (Criteria)replaceWithNullValues(innerGroups, crit);
try {
simplifiedCrit = QueryRewriter.rewriteCriteria(simplifiedCrit, null, null, metadata);
- } catch (QueryValidatorException err) {
+ } catch (MetaMatrixException err) {
//log the exception
return true;
}
@@ -153,7 +153,7 @@
Expression simplifiedExpression = (Expression)replaceWithNullValues(innerGroups, expr);
try {
simplifiedExpression = QueryRewriter.rewriteExpression(simplifiedExpression, null, null, metadata);
- } catch (QueryValidatorException err) {
+ } catch (MetaMatrixException err) {
//log the exception
return true;
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/QueryUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/QueryUtil.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/xml/QueryUtil.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -31,11 +31,11 @@
import java.util.Map;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.execution.QueryExecPlugin;
import com.metamatrix.query.mapping.relational.QueryNode;
@@ -112,13 +112,14 @@
* @param query The query to rewrite
* @param planEnv The planner environment
* @throws QueryPlannerException
+ * @throws MetaMatrixComponentException
* @since 4.3
*/
static Command rewriteQuery(Command query, QueryMetadataInterface metadata, CommandContext context)
- throws QueryPlannerException {
+ throws QueryPlannerException, MetaMatrixComponentException {
try {
return QueryRewriter.rewrite(query, metadata, context);
- } catch(QueryValidatorException e) {
+ } catch(MetaMatrixProcessingException e) {
throw new QueryPlannerException(e, e.getMessage());
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLUtil.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLUtil.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLUtil.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -31,6 +31,7 @@
import javax.xml.transform.TransformerException;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.FileStore;
import com.metamatrix.common.buffer.FileStore.FileStoreOutputStream;
@@ -50,7 +51,7 @@
* Documents less than the maxMemorySize will be held directly in memory
*/
public static SQLXMLImpl saveToBufferManager(BufferManager bufferMgr, XMLTranslator translator, int maxMemorySize)
- throws MetaMatrixComponentException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
boolean success = false;
final FileStore lobBuffer = bufferMgr.createFileStore("xml"); //$NON-NLS-1$
try{
@@ -66,7 +67,7 @@
} catch(IOException e) {
throw new MetaMatrixComponentException(e);
} catch(TransformerException e) {
- throw new MetaMatrixComponentException(e);
+ throw new MetaMatrixProcessingException(e);
} finally {
if (!success && lobBuffer != null) {
lobBuffer.remove();
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLValueTranslator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLValueTranslator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xml/XMLValueTranslator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -24,23 +24,23 @@
import java.math.BigInteger;
import java.sql.Timestamp;
-import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
-import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.query.FunctionExecutionException;
import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.common.types.TransformationException;
import com.metamatrix.query.function.FunctionMethods;
+import com.metamatrix.query.function.source.XMLSystemFunctions;
/**
* This class will make a minimal effort to output xsd formatted values for a given
- * builtin type. It will not attempt to narrrow or otherwise fit most values into
+ * built-in type. It will not attempt to narrow or otherwise fit most values into
* their output space (months can be greater than 12, nonNegative numbers can be
* negative, etc.)
*/
-final class XMLValueTranslator {
+public final class XMLValueTranslator {
private static String NEGATIVE_INFINITY = "-INF"; //$NON-NLS-1$
private static String POSITIVE_INFINITY = "INF"; //$NON-NLS-1$
@@ -48,22 +48,7 @@
private static String GMONTHDAY_FORMAT = "--MM-dd"; //$NON-NLS-1$
private static String GYEAR_FORMAT = "0000"; //$NON-NLS-1$
private static String GYEARMONTH_FORMAT = "yyyy-MM"; //$NON-NLS-1$
- private static String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$
- //YEAR 0 in the server timezone. used to determine negative years
- private static long YEAR_ZERO;
-
- static {
- Calendar cal = Calendar.getInstance();
-
- for (int i = 0; i <= Calendar.MILLISECOND; i++) {
- cal.set(i, 0);
- }
- YEAR_ZERO = cal.getTimeInMillis();
- }
-
- private static String TIMESTAMP_MICROZEROS = "000000000"; //$NON-NLS-1$
-
public static final String DATETIME = "dateTime"; //$NON-NLS-1$
public static final String DOUBLE = "double"; //$NON-NLS-1$
public static final String FLOAT = "float"; //$NON-NLS-1$
@@ -75,7 +60,7 @@
public static final String STRING = "string"; //$NON-NLS-1$
- private static final Map TYPE_CODE_MAP;
+ private static final Map<String, Integer> TYPE_CODE_MAP;
private static final int DATETIME_CODE = 0;
private static final int DOUBLE_CODE = 1;
@@ -87,7 +72,7 @@
private static final int GYEARMONTH_CODE = 7;
static {
- TYPE_CODE_MAP = new HashMap(20);
+ TYPE_CODE_MAP = new HashMap<String, Integer>(20);
TYPE_CODE_MAP.put(DATETIME, new Integer(DATETIME_CODE));
TYPE_CODE_MAP.put(DOUBLE, new Integer(DOUBLE_CODE));
TYPE_CODE_MAP.put(FLOAT, new Integer(FLOAT_CODE));
@@ -112,14 +97,15 @@
* @param builtInType The design-time atomic built-in type (or null if none)
* @return String representing the value
* @throws FunctionExecutionException
+ * @throws TransformationException
* @since 5.0
*/
- static String translateToXMLValue(Object value, Class runtimeType, String builtInType) throws MetaMatrixComponentException, FunctionExecutionException {
+ public static String translateToXMLValue(Object value, Class<?> runtimeType, String builtInType) throws FunctionExecutionException, TransformationException {
if (value == null) {
return null;
}
- Integer typeCode = (Integer)TYPE_CODE_MAP.get(builtInType);
+ Integer typeCode = TYPE_CODE_MAP.get(builtInType);
String valueStr = null;
@@ -131,7 +117,7 @@
switch (type) {
case DATETIME_CODE:
- valueStr = timestampToDateTime((Timestamp)value);
+ valueStr = XMLSystemFunctions.timestampToDateTime((Timestamp)value);
break;
case DOUBLE_CODE:
valueStr = doubleToDouble((Double)value);
@@ -178,62 +164,25 @@
private static String timestampTogYearMonth(Object value) throws FunctionExecutionException {
String valueStr;
Timestamp time = (Timestamp)value;
- valueStr = (String)FunctionMethods.format(time, GYEARMONTH_FORMAT);
- if (time.getTime() < YEAR_ZERO) {
+ valueStr = FunctionMethods.format(time, GYEARMONTH_FORMAT);
+ if (time.getTime() < XMLSystemFunctions.YEAR_ZERO) {
valueStr = "-" + valueStr; //$NON-NLS-1$
}
return valueStr;
}
/**
- * Formats a timestamp to an xs:dateTime. This uses DATETIME_FORMAT
- * with a trailing string for nanoseconds (without right zeros).
- */
- static String timestampToDateTime(Timestamp time) throws FunctionExecutionException {
- String result = (String)FunctionMethods.format(time, DATETIME_FORMAT);
- int nanos = time.getNanos();
- if (nanos == 0) {
- return result;
- }
-
- StringBuffer resultBuffer = new StringBuffer();
- boolean first = true;
- int i = 0;
- for (; i < 9 && nanos > 0; i++) {
- int digit = nanos%10;
- if (first) {
- if (digit > 0) {
- resultBuffer.insert(0, digit);
- first = false;
- }
- } else {
- resultBuffer.insert(0, digit);
- }
- nanos /= 10;
- }
- if (i < 9) {
- resultBuffer.insert(0, TIMESTAMP_MICROZEROS.substring(i));
- }
- resultBuffer.insert(0, "."); //$NON-NLS-1$
- resultBuffer.insert(0, result);
- if (time.getTime() < YEAR_ZERO) {
- resultBuffer.insert(0, "-"); //$NON-NLS-1$
- }
- return resultBuffer.toString();
-
- }
-
- /**
* Translate any non-null value to a string by using the Object toString() method.
* This works in any case where the Java string representation of an object is the
* same as the expected XML Schema output form.
*
* @param value Value returned from a mapping class
* @return String content to put in XML output
+ * @throws TransformationException
* @since 5.0
*/
- static String defaultTranslation(Object value) {
- return value.toString();
+ static String defaultTranslation(Object value) throws TransformationException {
+ return DataTypeManager.transformValue(value, DataTypeManager.DefaultDataClasses.STRING);
}
/**
@@ -243,9 +192,10 @@
*
* @param f Runtime float
* @return String representing xs:float
+ * @throws TransformationException
* @since 5.0
*/
- static String floatToFloat(Float f) {
+ static String floatToFloat(Float f) throws TransformationException {
if(f.floatValue() == Float.NEGATIVE_INFINITY) {
return NEGATIVE_INFINITY;
} else if(f.floatValue() == Float.POSITIVE_INFINITY) {
@@ -261,9 +211,10 @@
*
* @param d Runtime double
* @return String representing xs:double
+ * @throws TransformationException
* @since 5.0
*/
- static String doubleToDouble(Double d) {
+ static String doubleToDouble(Double d) throws TransformationException {
if(d.doubleValue() == Double.NEGATIVE_INFINITY) {
return NEGATIVE_INFINITY;
} else if(d.doubleValue() == Double.POSITIVE_INFINITY) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/xquery/XQueryPlan.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -139,8 +139,9 @@
* memory "atomically" (from the XQueryEngine layer).
* @param rawResults
* @return
+ * @throws MetaMatrixProcessingException
*/
- private TupleBatch packResultsIntoBatch(XMLTranslator translator) throws MetaMatrixComponentException{
+ private TupleBatch packResultsIntoBatch(XMLTranslator translator) throws MetaMatrixComponentException, MetaMatrixProcessingException{
List rows = new ArrayList(1);
List row = new ArrayList(1);
Modified: trunk/engine/src/main/java/com/metamatrix/query/resolver/util/ResolverVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/resolver/util/ResolverVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/resolver/util/ResolverVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -497,7 +497,7 @@
setDesiredType(args[i], newType, function);
//only currently typed expressions need conversions
- if (types[i] != null) {
+ if (types[i] != null && newType != DataTypeManager.DefaultDataClasses.OBJECT) {
function.insertConversion(i, conversions[i]);
}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -48,7 +48,6 @@
import com.metamatrix.api.exception.MetaMatrixException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.CriteriaEvaluationException;
-import com.metamatrix.api.exception.query.ExpressionEvaluationException;
import com.metamatrix.api.exception.query.FunctionExecutionException;
import com.metamatrix.api.exception.query.QueryMetadataException;
import com.metamatrix.api.exception.query.QueryResolverException;
@@ -136,6 +135,7 @@
import com.metamatrix.query.sql.symbol.Function;
import com.metamatrix.query.sql.symbol.GroupSymbol;
import com.metamatrix.query.sql.symbol.Reference;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
@@ -192,26 +192,10 @@
QueryRewriter queryRewriter = new QueryRewriter(metadata, context, null);
queryRewriter.dataMgr = dataMgr;
queryRewriter.rewriteSubcommands = true;
- try {
- return queryRewriter.rewriteCommand(command, false);
- } catch (MetaMatrixRuntimeException err) {
- Throwable e = err.getChild();
-
- if (e == null) {
- throw err;
- }
-
- if(e instanceof ExpressionEvaluationException) {
- throw (ExpressionEvaluationException) e;
- } else if(e instanceof MetaMatrixComponentException) {
- throw (MetaMatrixComponentException) e;
- } else {
- throw new MetaMatrixComponentException(e, e.getMessage());
- }
- }
+ return queryRewriter.rewriteCommand(command, false);
}
- public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map variableValues, int commandType) throws QueryValidatorException {
+ public static Command rewrite(Command command, CreateUpdateProcedureCommand procCommand, QueryMetadataInterface metadata, CommandContext context, Map variableValues, int commandType) throws MetaMatrixComponentException, MetaMatrixProcessingException{
QueryRewriter rewriter = new QueryRewriter(metadata, context, procCommand);
rewriter.rewriteSubcommands = true;
rewriter.variables = variableValues;
@@ -219,7 +203,7 @@
return rewriter.rewriteCommand(command, false);
}
- public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws QueryValidatorException {
+ public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws MetaMatrixComponentException, MetaMatrixProcessingException{
return rewrite(command, null, metadata, context, null, Command.TYPE_UNKNOWN);
}
@@ -231,7 +215,7 @@
* @return
* @throws QueryValidatorException
*/
- private Command rewriteCommand(Command command, boolean removeOrderBy) throws QueryValidatorException {
+ private Command rewriteCommand(Command command, boolean removeOrderBy) throws MetaMatrixComponentException, MetaMatrixProcessingException{
QueryMetadataInterface oldMetadata = metadata;
CreateUpdateProcedureCommand oldProcCommand = procCommand;
@@ -287,20 +271,12 @@
}
private Command rewriteUpdateProcedure(CreateUpdateProcedureCommand command)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
Map oldVariables = variables;
- try {
- if (command.getUserCommand() != null) {
- variables = QueryResolver.getVariableValues(command.getUserCommand(), metadata);
- commandType = command.getUserCommand().getType();
- }
- } catch (QueryMetadataException err) {
- throw new QueryValidatorException(err, err.getMessage());
- } catch (QueryResolverException err) {
- throw new QueryValidatorException(err, err.getMessage());
- } catch (MetaMatrixComponentException err) {
- throw new QueryValidatorException(err, err.getMessage());
- }
+ if (command.getUserCommand() != null) {
+ variables = QueryResolver.getVariableValues(command.getUserCommand(), metadata);
+ commandType = command.getUserCommand().getType();
+ }
Block block = rewriteBlock(command.getBlock());
command.setBlock(block);
@@ -311,7 +287,7 @@
}
private Block rewriteBlock(Block block)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
List statements = block.getStatements();
Iterator stmtIter = statements.iterator();
@@ -333,7 +309,7 @@
}
private Object rewriteStatement(Statement statement)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
// evaluate the HAS Criteria on the procedure and rewrite
int stmtType = statement.getType();
@@ -434,7 +410,7 @@
* @param assStmt
* @throws QueryValidatorException
*/
- private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws QueryValidatorException {
+ private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (rewriteSubcommands && container.getCommand() != null && container.getCommand().getProcessorPlan() == null) {
container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
}
@@ -552,7 +528,7 @@
* virtual group.</p>
*/
private Criteria rewriteCriteria(TranslateCriteria transCrit)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
// criteria translated
Criteria translatedCriteria = null;
@@ -607,7 +583,7 @@
// apply any implicit conversions
try {
ResolverVisitor.resolveLanguageObject(translatedCriteria, metadata);
- } catch(Exception ex) {
+ } catch(MetaMatrixException ex) {
throw new QueryValidatorException(ex, ErrorMessageKeys.REWRITER_0002, QueryExecPlugin.Util.getString(ErrorMessageKeys.REWRITER_0002, translatedCriteria));
}
@@ -615,7 +591,7 @@
}
private Command rewriteQuery(Query query)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
// Rewrite from clause
From from = query.getFrom();
@@ -672,7 +648,7 @@
* @return
* @throws QueryValidatorException
*/
- private Query rewriteGroupBy(Query query) throws QueryValidatorException {
+ private Query rewriteGroupBy(Query query) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (query.getGroupBy() == null) {
return query;
}
@@ -723,11 +699,7 @@
Query outerQuery = null;
try {
outerQuery = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), query, metadata, query.getSelect().getProjectedSymbols()); //$NON-NLS-1$
- } catch (QueryMetadataException err) {
- throw new QueryValidatorException(err, err.getMessage());
- } catch (QueryResolverException err) {
- throw new QueryValidatorException(err, err.getMessage());
- } catch (MetaMatrixComponentException err) {
+ } catch (MetaMatrixException err) {
throw new MetaMatrixRuntimeException(err);
}
Iterator iter = outerQuery.getSelect().getProjectedSymbols().iterator();
@@ -751,7 +723,7 @@
return query;
}
- private void rewriteExpressions(LanguageObject obj) throws QueryValidatorException {
+ private void rewriteExpressions(LanguageObject obj) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (obj == null) {
return;
}
@@ -763,7 +735,7 @@
public Expression replaceExpression(Expression element) {
try {
return rewriteExpressionDirect(element);
- } catch (QueryValidatorException err) {
+ } catch (MetaMatrixException err) {
throw new MetaMatrixRuntimeException(err);
}
}
@@ -771,9 +743,12 @@
try {
PostOrderNavigator.doVisit(obj, visitor);
} catch (MetaMatrixRuntimeException err) {
- if (err.getChild() instanceof QueryValidatorException) {
- throw (QueryValidatorException)err.getChild();
+ if (err.getChild() instanceof MetaMatrixComponentException) {
+ throw (MetaMatrixComponentException)err.getChild();
}
+ if (err.getChild() instanceof MetaMatrixProcessingException) {
+ throw (MetaMatrixProcessingException)err.getChild();
+ }
throw err;
}
}
@@ -783,9 +758,9 @@
* Unrelated order by expressions will cause the creation of nested inline views.
*
* @param query
- * @throws QueryValidatorException
+ * @throws MetaMatrixComponentException, MetaMatrixProcessingException
*/
- public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws QueryValidatorException {
+ public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws MetaMatrixComponentException, MetaMatrixProcessingException{
final OrderBy orderBy = queryCommand.getOrderBy();
if (orderBy == null) {
return queryCommand;
@@ -852,13 +827,9 @@
}
ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
//now the order by should only contain element symbols
- } catch (QueryResolverException e) {
- throw new QueryValidatorException(e, e.getMessage());
- } catch (QueryMetadataException e) {
- throw new QueryValidatorException(e, e.getMessage());
- } catch (MetaMatrixComponentException e) {
- throw new QueryValidatorException(e, e.getMessage());
- }
+ } catch (MetaMatrixException err) {
+ throw new MetaMatrixRuntimeException(err);
+ }
List symbols = top.getSelect().getSymbols();
top.getSelect().setSymbols(symbols.subList(0, originalSymbolCount));
top.setInto(into);
@@ -874,7 +845,7 @@
* @param query
* @throws QueryValidatorException
*/
- private Insert rewriteSelectInto(Query query) throws QueryValidatorException {
+ private Insert rewriteSelectInto(Query query) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Into into = query.getInto();
try {
List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
@@ -889,7 +860,7 @@
}
}
- private Insert correctDatatypes(Insert insert) throws QueryValidatorException {
+ private Insert correctDatatypes(Insert insert) throws MetaMatrixComponentException, MetaMatrixProcessingException{
boolean needsView = false;
for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
SingleElementSymbol ses = (SingleElementSymbol)insert.getVariables().get(i);
@@ -900,13 +871,9 @@
if (needsView) {
try {
insert.setQueryExpression(createInlineViewQuery(insert.getGroup(), insert.getQueryExpression(), metadata, insert.getVariables()));
- } catch (QueryResolverException e) {
- throw new QueryValidatorException(e, e.getMessage());
- } catch (QueryMetadataException e) {
- throw new QueryValidatorException(e, e.getMessage());
- } catch (MetaMatrixComponentException e) {
- throw new MetaMatrixRuntimeException(e);
- }
+ } catch (MetaMatrixException err) {
+ throw new MetaMatrixRuntimeException(err);
+ }
}
return insert;
}
@@ -921,7 +888,7 @@
}
private SetQuery rewriteSetQuery(SetQuery setQuery)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (setQuery.getProjectedTypes() != null) {
for (QueryCommand command : setQuery.getQueryCommands()) {
@@ -946,7 +913,7 @@
}
private FromClause rewriteFromClause(Query parent, FromClause clause)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
if(clause instanceof JoinPredicate) {
return rewriteJoinPredicate(parent, (JoinPredicate) clause);
} else if (clause instanceof SubqueryFromClause) {
@@ -956,7 +923,7 @@
}
private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
List joinCrits = predicate.getJoinCriteria();
if(joinCrits != null && joinCrits.size() > 0) {
//rewrite join crits by rewriting a compound criteria
@@ -995,7 +962,7 @@
* in the procedural language.
* @return The re-written criteria
*/
- public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+ public static Criteria rewriteCriteria(Criteria criteria, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException{
return new QueryRewriter(metadata, context, procCommand).rewriteCriteria(criteria);
}
@@ -1006,7 +973,7 @@
* in the procedural language.
* @return The re-written criteria
*/
- private Criteria rewriteCriteria(Criteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(Criteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if(criteria instanceof CompoundCriteria) {
return rewriteCriteria((CompoundCriteria)criteria, true);
} else if(criteria instanceof NotCriteria) {
@@ -1043,7 +1010,7 @@
}
private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (dataMgr == null) {
return rewriteCriteria(dsc);
}
@@ -1076,7 +1043,7 @@
public static Criteria optimizeCriteria(CompoundCriteria criteria, QueryMetadataInterface metadata) {
try {
return new QueryRewriter(metadata, null, null).rewriteCriteria(criteria, false);
- } catch (QueryValidatorException err) {
+ } catch (MetaMatrixException err) {
//shouldn't happen
return criteria;
}
@@ -1085,7 +1052,7 @@
/** 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 QueryValidatorException {
+ private Criteria rewriteCriteria(CompoundCriteria criteria, boolean rewrite) throws MetaMatrixComponentException, MetaMatrixProcessingException{
List<Criteria> crits = criteria.getCriteria();
int operator = criteria.getOperator();
@@ -1141,7 +1108,7 @@
}
}
- private Criteria evaluateCriteria(Criteria crit) throws QueryValidatorException {
+ private Criteria evaluateCriteria(Criteria crit) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if(EvaluatableVisitor.isFullyEvaluatable(crit, true)) {
try {
Boolean eval = new Evaluator(Collections.emptyMap(), this.dataMgr, context).evaluateTVL(crit, Collections.emptyList());
@@ -1158,15 +1125,13 @@
} catch(CriteriaEvaluationException e) {
throw new QueryValidatorException(e, ErrorMessageKeys.REWRITER_0001, QueryExecPlugin.Util.getString(ErrorMessageKeys.REWRITER_0001, crit));
- } catch(MetaMatrixComponentException e) {
- throw new MetaMatrixRuntimeException(e);
}
}
return crit;
}
- private Criteria rewriteCriteria(NotCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(NotCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Criteria innerCrit = criteria.getCriteria();
if (innerCrit instanceof CompoundCriteria) {
//reduce to only negation of predicates, so that the null/unknown handling criteria is applied appropriately
@@ -1197,7 +1162,7 @@
* @return
* @throws QueryValidatorException
*/
- private Criteria rewriteCriteria(BetweenCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(BetweenCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
CompareCriteria lowerCriteria = new CompareCriteria(criteria.getExpression(),
criteria.isNegated() ? CompareCriteria.LT: CompareCriteria.GE,
criteria.getLowerExpression());
@@ -1211,7 +1176,7 @@
return rewriteCriteria(newCriteria);
}
- private Criteria rewriteCriteria(CompareCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(CompareCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
Expression rightExpr = rewriteExpressionDirect(criteria.getRightExpression());
criteria.setLeftExpression(leftExpr);
@@ -1264,7 +1229,7 @@
* 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 QueryValidatorException {
+ private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
@@ -1283,7 +1248,7 @@
return criteria;
}
- private Criteria simplifyWithInverse(CompareCriteria criteria) throws QueryValidatorException {
+ private Criteria simplifyWithInverse(CompareCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Expression leftExpr = criteria.getLeftExpression();
Function leftFunction = (Function) leftExpr;
@@ -1324,7 +1289,7 @@
* @return CompareCriteria
*/
private CompareCriteria simplifyMathematicalCriteria(CompareCriteria criteria)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
Expression leftExpr = criteria.getLeftExpression();
Expression rightExpr = criteria.getRightExpression();
@@ -1457,7 +1422,7 @@
* @throws QueryValidatorException
* @since 4.2
*/
- private Criteria simplifyConvertFunction(CompareCriteria crit) throws QueryValidatorException {
+ private Criteria simplifyConvertFunction(CompareCriteria crit) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Function leftFunction = (Function) crit.getLeftExpression();
Expression leftExpr = leftFunction.getArgs()[0];
@@ -1516,7 +1481,7 @@
* @throws QueryValidatorException
* @since 4.2
*/
- private Criteria simplifyConvertFunction(SetCriteria crit) throws QueryValidatorException {
+ private Criteria simplifyConvertFunction(SetCriteria crit) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Function leftFunction = (Function) crit.getExpression();
Expression leftExpr = leftFunction.getArgs()[0];
String leftExprTypeName = DataTypeManager.getDataTypeName(leftExpr.getType());
@@ -1567,7 +1532,7 @@
return rewriteCriteria(crit);
}
- private Criteria simplifyParseFormatFunction(CompareCriteria crit) throws QueryValidatorException {
+ private Criteria simplifyParseFormatFunction(CompareCriteria crit) throws MetaMatrixComponentException, MetaMatrixProcessingException{
//TODO: this can be relaxed for order preserving operations
if(!(crit.getOperator() == CompareCriteria.EQ || crit.getOperator() == CompareCriteria.NE)) {
return crit;
@@ -1765,7 +1730,7 @@
}
}
- private Criteria rewriteCriteria(MatchCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(MatchCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
criteria.setLeftExpression( rewriteExpressionDirect(criteria.getLeftExpression()));
criteria.setRightExpression( rewriteExpressionDirect(criteria.getRightExpression()));
@@ -1817,7 +1782,7 @@
return FALSE_CRITERIA;
}
- private Criteria rewriteCriteria(AbstractSetCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(AbstractSetCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
if (isNull(criteria.getExpression())) {
@@ -1827,7 +1792,7 @@
return criteria;
}
- private Criteria rewriteCriteria(SetCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(SetCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
if (isNull(criteria.getExpression())) {
@@ -1866,16 +1831,16 @@
return criteria;
}
- private Criteria rewriteCriteria(IsNullCriteria criteria) throws QueryValidatorException {
+ private Criteria rewriteCriteria(IsNullCriteria criteria) throws MetaMatrixComponentException, MetaMatrixProcessingException{
criteria.setExpression(rewriteExpressionDirect(criteria.getExpression()));
return criteria;
}
- public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws QueryValidatorException {
+ public static Expression rewriteExpression(Expression expression, CreateUpdateProcedureCommand procCommand, CommandContext context, QueryMetadataInterface metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException{
return new QueryRewriter(metadata, context, procCommand).rewriteExpressionDirect(expression);
}
- private Expression rewriteExpressionDirect(Expression expression) throws QueryValidatorException {
+ private Expression rewriteExpressionDirect(Expression expression) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (expression instanceof Constant) {
return expression;
}
@@ -1927,16 +1892,17 @@
} else {
expression = rewriteExpressionDirect(((ExpressionSymbol)expression).getExpression());
}
- }
- if (dataMgr == null || (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING))) {
- return expression;
- }
- Object value;
- try {
- value = new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(expression, Collections.emptyList());
- } catch (MetaMatrixException err) {
- throw new MetaMatrixRuntimeException(err);
}
+
+ if(dataMgr == null) {
+ if (!EvaluatableVisitor.isFullyEvaluatable(expression, true)) {
+ return expression;
+ }
+ } else if (!(expression instanceof Reference) && !EvaluatableVisitor.isEvaluatable(expression, EvaluationLevel.PROCESSING)) {
+ return expression;
+ }
+
+ Object value = new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(expression, Collections.emptyList());
if (value instanceof Constant) {
return (Constant)value; //multi valued substitution
}
@@ -1973,7 +1939,7 @@
FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
}
- private Expression rewriteFunction(Function function) throws QueryValidatorException {
+ private Expression rewriteFunction(Function function) throws MetaMatrixComponentException, MetaMatrixProcessingException{
//rewrite alias functions
String functionLowerName = function.getName().toLowerCase();
String actualName =ALIASED_FUNCTIONS.get(functionLowerName);
@@ -2123,26 +2089,6 @@
return convertDecodeFunction(function);
}
- if(EvaluatableVisitor.isFullyEvaluatable(function, true)) {
- try {
- Object result = new Evaluator(Collections.emptyMap(), null, context).evaluate(function, Collections.emptyList());
- Constant constant = new Constant(result, function.getType());
- return constant;
- } catch(ExpressionEvaluationException e) {
- String funcName = function.getName();
- if(FunctionLibrary.isConvert(function)) {
- Expression expr = newArgs[0];
- String sourceType = DataTypeManager.getDataTypeName(newArgs[0].getType());
- String targetType = (String) ((Constant) newArgs[1]).getValue();
- throw new QueryValidatorException(e, ErrorMessageKeys.REWRITER_0004,
- QueryExecPlugin.Util.getString(ErrorMessageKeys.REWRITER_0004, new Object[] {funcName, expr, sourceType, targetType}));
-
- }
- throw new QueryValidatorException(e, e.getMessage());
- } catch(MetaMatrixComponentException e) {
- throw new MetaMatrixRuntimeException(e);
- }
- }
return function;
}
@@ -2232,7 +2178,7 @@
}
private Expression rewriteCaseExpression(CaseExpression expr)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
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));
@@ -2244,7 +2190,7 @@
}
private Expression rewriteCaseExpression(SearchedCaseExpression expr)
- throws QueryValidatorException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException{
int whenCount = expr.getWhenCount();
ArrayList<Criteria> whens = new ArrayList<Criteria>(whenCount);
ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
@@ -2265,7 +2211,9 @@
thens.add(rewriteExpressionDirect(expr.getThenExpression(i)));
}
- expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
+ if (expr.getElseExpression() != null) {
+ expr.setElseExpression(rewriteExpressionDirect(expr.getElseExpression()));
+ }
Expression elseExpr = expr.getElseExpression();
if(whens.size() == 0) {
@@ -2304,7 +2252,7 @@
return expr;
}
- private Command rewriteExec(StoredProcedure storedProcedure) throws QueryValidatorException {
+ private Command rewriteExec(StoredProcedure storedProcedure) throws MetaMatrixComponentException, MetaMatrixProcessingException{
//After this method, no longer need to display named parameters
storedProcedure.setDisplayNamedParameters(false);
@@ -2315,7 +2263,7 @@
return storedProcedure;
}
- private Insert rewriteInsert(Insert insert) throws QueryValidatorException {
+ private Insert rewriteInsert(Insert insert) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if ( insert.getQueryExpression() != null ) {
insert.setQueryExpression((QueryCommand)rewriteCommand(insert.getQueryExpression(), true));
@@ -2426,7 +2374,7 @@
}
}
- private Update rewriteUpdate(Update update) throws QueryValidatorException {
+ private Update rewriteUpdate(Update update) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (commandType == Command.TYPE_UPDATE && variables != null) {
SetClauseList newChangeList = new SetClauseList();
for (SetClause entry : update.getChangeList().getClauses()) {
@@ -2458,9 +2406,9 @@
* 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 QueryValidatorException
+ * @throws MetaMatrixComponentException, MetaMatrixProcessingException
*/
- private boolean checkInputVariables(Expression expr) throws QueryValidatorException {
+ private boolean checkInputVariables(Expression expr) throws MetaMatrixComponentException, MetaMatrixProcessingException{
Boolean result = null;
for (ElementSymbol var : ElementCollectorVisitor.getElements(expr, false)) {
String grpName = var.getGroupSymbol().getName();
@@ -2485,7 +2433,7 @@
return true;
}
- private Delete rewriteDelete(Delete delete) throws QueryValidatorException {
+ private Delete rewriteDelete(Delete delete) throws MetaMatrixComponentException, MetaMatrixProcessingException{
// Rewrite criteria
Criteria crit = delete.getCriteria();
if(crit != null) {
@@ -2495,7 +2443,7 @@
return delete;
}
- private Limit rewriteLimitClause(Limit limit) throws QueryValidatorException {
+ private Limit rewriteLimitClause(Limit limit) throws MetaMatrixComponentException, MetaMatrixProcessingException{
if (limit.getOffset() != null) {
limit.setOffset(rewriteExpressionDirect(limit.getOffset()));
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/LanguageVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/LanguageVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/LanguageVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -126,4 +126,5 @@
public void visit(SetClauseList obj) {}
public void visit(SetClause obj) {}
public void visit(OrderByItem obj) {}
+ public void visit(SQLXMLFunction obj) {}
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/navigator/PreOrPostOrderNavigator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/navigator/PreOrPostOrderNavigator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/navigator/PreOrPostOrderNavigator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -92,6 +92,9 @@
import com.metamatrix.query.sql.symbol.Reference;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
+import com.metamatrix.query.sql.symbol.SingleElementSymbol;
+import com.metamatrix.query.sql.util.SymbolMap;
/**
@@ -507,6 +510,16 @@
postVisitVisitor(obj);
}
+ @Override
+ public void visit(SQLXMLFunction obj) {
+ preVisitVisitor(obj);
+ //we just want the underlying expressions, not the wrapping alias/expression symbols
+ for (SingleElementSymbol symbol : obj.getArgs()) {
+ visitNode(SymbolMap.getExpression(symbol));
+ }
+ postVisitVisitor(obj);
+ }
+
public static void doVisit(LanguageObject object, LanguageVisitor visitor, boolean order) {
PreOrPostOrderNavigator nav = new PreOrPostOrderNavigator(visitor, order);
object.acceptVisitor(nav);
Added: trunk/engine/src/main/java/com/metamatrix/query/sql/symbol/SQLXMLFunction.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/symbol/SQLXMLFunction.java (rev 0)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/symbol/SQLXMLFunction.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -0,0 +1,98 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package com.metamatrix.query.sql.symbol;
+
+import java.util.List;
+
+import com.metamatrix.common.types.DataTypeManager;
+import com.metamatrix.core.util.HashCodeUtil;
+import com.metamatrix.query.sql.LanguageObject;
+import com.metamatrix.query.sql.LanguageVisitor;
+import com.metamatrix.query.sql.visitor.SQLStringVisitor;
+
+/**
+ * Represents XMLATTRIBUTES or XMLFOREST name value pairs
+ */
+public class SQLXMLFunction implements Expression {
+
+ private static final long serialVersionUID = -3348922701950966494L;
+ private List<SingleElementSymbol> args;
+ private String name;
+
+ public SQLXMLFunction(String name, List<SingleElementSymbol> args) {
+ this.name = name;
+ this.args = args;
+ }
+
+ public List<SingleElementSymbol> getArgs() {
+ return args;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public Class<?> getType() {
+ return DataTypeManager.DefaultDataClasses.XML;
+ }
+
+ @Override
+ public boolean isResolved() {
+ for (SingleElementSymbol arg : args) {
+ if (!arg.isResolved()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void acceptVisitor(LanguageVisitor visitor) {
+ visitor.visit(this);
+ }
+
+ @Override
+ public SQLXMLFunction clone() {
+ return new SQLXMLFunction(name, LanguageObject.Util.deepClone(args, SingleElementSymbol.class));
+ }
+
+ @Override
+ public int hashCode() {
+ return HashCodeUtil.hashCode(name.toUpperCase().hashCode(), args.hashCode());
+ }
+
+ public boolean equals(Object obj) {
+ if (!(obj instanceof SQLXMLFunction)) {
+ return false;
+ }
+ SQLXMLFunction other = (SQLXMLFunction)obj;
+ return name.equalsIgnoreCase(other.name) && args.equals(other.args);
+ }
+
+ @Override
+ public String toString() {
+ return SQLStringVisitor.getSQLString(this);
+ }
+
+}
Property changes on: trunk/engine/src/main/java/com/metamatrix/query/sql/symbol/SQLXMLFunction.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -45,6 +45,7 @@
import com.metamatrix.query.sql.symbol.ExpressionSymbol;
import com.metamatrix.query.sql.symbol.Function;
import com.metamatrix.query.sql.symbol.Reference;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
/**
@@ -171,6 +172,9 @@
}
public static final boolean isEvaluatable(LanguageObject obj, EvaluationLevel target) {
+ if (obj instanceof SQLXMLFunction && (FunctionLibrary.XMLATTRIBUTES.equalsIgnoreCase(((SQLXMLFunction)obj).getName()))) {
+ return false; //we want to preserve xmlattributes unless the parent xmlelement can be evaluated
+ }
EvaluatableVisitor visitor = new EvaluatableVisitor();
visitor.targetLevel = target;
PreOrderNavigator.doVisit(obj, visitor);
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/ExpressionMappingVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/ExpressionMappingVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/ExpressionMappingVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -57,6 +57,7 @@
import com.metamatrix.query.sql.symbol.Expression;
import com.metamatrix.query.sql.symbol.ExpressionSymbol;
import com.metamatrix.query.sql.symbol.Function;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
@@ -83,6 +84,11 @@
public void visit(Select obj) {
replaceSymbols(obj.getSymbols(), true);
}
+
+ @Override
+ public void visit(SQLXMLFunction obj) {
+ replaceSymbols(obj.getArgs(), true);
+ }
private void replaceSymbols(List symbols, boolean alias) {
for (int i = 0; i < symbols.size(); i++) {
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/SQLStringVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/SQLStringVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/SQLStringVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -109,6 +109,7 @@
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.symbol.SelectSymbol;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
/**
* <p>The SQLStringVisitor will visit a set of language objects and return the
@@ -1238,46 +1239,32 @@
if(args != null && args.length > 0) {
parts.add(((Constant)args[0]).getValue());
-
- for(int i=1; i<args.length; i++) {
- parts.add(", "); //$NON-NLS-1$
- parts.add(registerNode(args[i]));
- }
+ registerNodes(args, 1);
}
parts.add(")"); //$NON-NLS-1$
- } else if (name.equalsIgnoreCase(SourceSystemFunctions.XSLTRANSFORM)){
+ } else if (name.equalsIgnoreCase(SourceSystemFunctions.XMLELEMENT)){
parts.add(name);
- parts.add("("); //$NON-NLS-1$
-
- parts.add(registerNode(args[0]));
- parts.add(SPACE);
- parts.add(SQLReservedWords.USING);
- parts.add(SPACE);
- parts.add(registerNode(args[1]));
- if (args.length > 2) {
- parts.add(SPACE);
- parts.add(SQLReservedWords.AS);
- parts.add(SPACE);
- parts.add(((Constant)args[2]).getValue());
- }
+ parts.add("(NAME "); //$NON-NLS-1$
+ outputDisplayName((String)((Constant)args[0]).getValue());
+ registerNodes(args, 1);
parts.add(")"); //$NON-NLS-1$
} else {
parts.add(name);
parts.add("("); //$NON-NLS-1$
-
- if(args.length > 0) {
- for(int i=0; i<args.length; i++) {
- parts.add(registerNode(args[i]));
- if(i < (args.length-1)) {
- parts.add(", "); //$NON-NLS-1$
- }
- }
- }
-
+ registerNodes(args, 0);
parts.add(")"); //$NON-NLS-1$
}
}
+
+ private void registerNodes(LanguageObject[] objects, int begin) {
+ for (int i = begin; i < objects.length; i++) {
+ if (i > 0) {
+ parts.add(", "); //$NON-NLS-1$
+ }
+ parts.add(registerNode(objects[i]));
+ }
+ }
public void visit(GroupSymbol obj) {
String alias = null;
@@ -1552,6 +1539,13 @@
parts.add(")"); //$NON-NLS-1$
}
+ @Override
+ public void visit(SQLXMLFunction obj) {
+ parts.add(obj.getName());
+ parts.add("("); //$NON-NLS-1$
+ registerNodes(obj.getArgs().toArray(new LanguageObject[obj.getArgs().size()]), 0);
+ parts.add(")"); //$NON-NLS-1$
+ }
public void visit(Limit obj) {
parts.add(SQLReservedWords.LIMIT);
Modified: trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/com/metamatrix/query/validator/ValidationVisitor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -94,6 +94,7 @@
import com.metamatrix.query.sql.symbol.Function;
import com.metamatrix.query.sql.symbol.GroupSymbol;
import com.metamatrix.query.sql.symbol.Reference;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
import com.metamatrix.query.sql.util.SymbolMap;
import com.metamatrix.query.sql.visitor.AggregateSymbolCollectorVisitor;
@@ -1113,5 +1114,14 @@
((Reference)limitExpr).setConstraint(new PositiveIntegerConstraint("ValidationVisitor.badlimit2")); //$NON-NLS-1$
}
}
+
+ @Override
+ public void visit(SQLXMLFunction obj) {
+ for (SingleElementSymbol arg : obj.getArgs()) {
+ if (arg instanceof ExpressionSymbol) {
+ handleValidationError("ValidationVisitor.expression_requires_name", arg); //$NON-NLS-1$
+ }
+ }
+ }
}
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -30,9 +30,9 @@
import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.ExpressionEvaluationException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.QueryValidatorException;
@@ -123,13 +123,10 @@
/**
* @throws MetaMatrixComponentException
- * @throws QueryValidatorException
- * @throws QueryResolverException
- * @throws QueryParserException
- * @throws QueryPlannerException
+ * @throws MetaMatrixProcessingException
* @see org.teiid.dqp.internal.process.Request#generatePlan()
*/
- protected void generatePlan() throws QueryPlannerException, QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ protected void generatePlan() throws MetaMatrixComponentException, MetaMatrixProcessingException {
String sqlQuery = requestMsg.getCommands()[0];
CacheID id = new CacheID(this.workContext, Request.createParseInfo(this.requestMsg), sqlQuery);
prepPlan = prepPlanCache.get(id);
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -381,12 +381,9 @@
* sets the processor plan
*
* @throws MetaMatrixComponentException
- * @throws QueryPlannerException
- * @throws QueryParserException
- * @throws QueryResolverException
- * @throws QueryValidatorException
+ * @throws MetaMatrixProcessingException
*/
- protected void generatePlan() throws MetaMatrixComponentException, QueryPlannerException, QueryParserException, QueryResolverException, QueryValidatorException {
+ protected void generatePlan() throws MetaMatrixComponentException, MetaMatrixProcessingException {
Command command = parseCommand();
List<Reference> references = ReferenceCollectorVisitor.getReferences(command);
@@ -449,7 +446,7 @@
}
public void processRequest()
- throws QueryValidatorException, QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryPlannerException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
LogManager.logDetail(LogConstants.CTX_DQP, this.requestId, "executing", this.requestMsg.isPreparedStatement()?"prepared":"", this.requestMsg.getCommandString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -31,7 +31,7 @@
import org.teiid.dqp.internal.process.DQPWorkContext;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.query.CriteriaEvaluationException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.core.id.IDGenerator;
@@ -70,7 +70,7 @@
if (node instanceof AccessNode) {
try {
return multiSourceModify((AccessNode)node);
- } catch (CriteriaEvaluationException e) {
+ } catch (MetaMatrixProcessingException e) {
throw new QueryPlannerException(e, e.getMessage());
}
}
@@ -78,7 +78,7 @@
return node;
}
- private RelationalNode multiSourceModify(AccessNode accessNode) throws MetaMatrixComponentException, CriteriaEvaluationException {
+ private RelationalNode multiSourceModify(AccessNode accessNode) throws MetaMatrixComponentException, MetaMatrixProcessingException {
String modelName = accessNode.getModelName();
if(!this.multiSourceModels.contains(modelName)) {
Modified: trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj
===================================================================
--- trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/javacc/com/metamatrix/query/parser/SQLParser.jj 2010-05-06 17:17:44 UTC (rev 2100)
@@ -16,7 +16,6 @@
import java.math.BigInteger;
import java.util.*;
import com.metamatrix.common.types.*;
-import com.metamatrix.core.util.StringUtil;
import com.metamatrix.query.QueryPlugin;
import com.metamatrix.query.sql.LanguageObject;
import com.metamatrix.query.sql.lang.*;
@@ -1595,50 +1594,65 @@
SelectSymbol selectSymbol(ParseInfo info) :
{
+ SelectSymbol symbol = null;
+}
+{
+ (
+ symbol = selectExpression(info)
+ |
+ symbol = allInGroupSymbol()
+ )
+ {
+ return symbol;
+ }
+}
+
+SingleElementSymbol selectExpression(ParseInfo info) :
+{
Expression expression = null;
String alias = null;
- Token allInGroupToken = null;
}
{
(
- // Group.*
- (
- allInGroupToken = <ALL_IN_GROUP>
- )
- |
- (
- // Expression
- expression=expression(info)
- )
+ // Expression
+ expression=expression(info)
[[<AS>] ( alias=id() )
]
)
- {
- // Validate alias
- if(alias != null) {
- alias = validateAlias(alias);
- }
-
- if(allInGroupToken != null) {
- // Group.*
- return new AllInGroupSymbol(normalizeId(allInGroupToken.image));
- }
+ {
SingleElementSymbol es = null;
if(expression instanceof ElementSymbol) {
es = (ElementSymbol) expression;
- } else if(expression instanceof AggregateSymbol) {
- es = (AggregateSymbol)expression;
} else {
- String functionName = generateFunctionName(info, null);
- es = new ExpressionSymbol(functionName, expression);
+ String func = null;
+ if(expression instanceof AggregateSymbol) {
+ es = (AggregateSymbol)expression;
+ func = ((AggregateSymbol)expression).getAggregateFunction();
+ } else {
+ String functionName = generateFunctionName(info, null);
+ es = new ExpressionSymbol(functionName, expression);
+ }
}
- if(alias != null) {
+ if(alias != null) {
+ alias = validateAlias(alias);
return new AliasSymbol(alias, es);
}
return es;
}
}
+AllInGroupSymbol allInGroupSymbol() :
+{
+ Token allInGroupToken = null;
+
+}
+{
+ allInGroupToken = <ALL_IN_GROUP>
+ {
+ return new AllInGroupSymbol(normalizeId(allInGroupToken.image));
+ }
+}
+
AggregateSymbol aggregateSymbol(ParseInfo info) :
{
Token functionToken = null;
@@ -2836,7 +2850,7 @@
* @return Parsed function
* @throws ParseException if parsing failed
*/
-Function function(ParseInfo info) :
+Expression function(ParseInfo info) :
{
String funcName = null;
@@ -2904,7 +2918,7 @@
(
(funcToken = <LEFT> | funcToken = <RIGHT> | funcToken = <CHAR> | funcToken = <USER>
| funcToken = <YEAR> | funcToken = <MONTH> | funcToken = <HOUR>
- | funcToken = <MINUTE> | funcToken = <SECOND> | funcToken = <XMLELEMENT>)
+ | funcToken = <MINUTE> | funcToken = <SECOND> | funcToken = <XMLCONCAT>)
<LPAREN>
[
expression = expression(info)
@@ -2962,7 +2976,40 @@
]
<RPAREN>
)
+ | ( funcToken = <XMLELEMENT>
+ <LPAREN>
+ (
+ LOOKAHEAD(<ID>, { "name".equalsIgnoreCase(getToken(1).image) }) <ID> expression = idExpression()
+ |
+ expression = idExpression()
+ )
+ {
+ args.add(expression);
+ expression = null;
+ }
+ [
+ LOOKAHEAD(2) <COMMA> expression = sqlXmlFunction(info)
+ {
+ args.add(expression);
+ expression = null;
+ }
+ ]
+ (<COMMA> expression=expression(info)
+ {
+ args.add(expression);
+ expression = null;
+ }
+ )*
+ <RPAREN>
+ )
|
+ LOOKAHEAD(<XMLFOREST>) (
+ expression = sqlXmlFunction(info)
+ {
+ return expression;
+ }
+ )
+ |
( funcName = id()
{
funcName = validateFunctionName(funcName);
@@ -2989,14 +3036,48 @@
funcName = funcToken.image;
}
- Expression[] expressions = new Expression[args.size()];
- for(int i=0; i<args.size(); i++) {
- expressions[i] = (Expression) args.get(i);
- }
- return new Function(funcName, expressions);
+ return new Function(funcName, (Expression[])args.toArray(new Expression[args.size()]));
}
}
+SQLXMLFunction sqlXmlFunction(ParseInfo info) :
+{
+ Expression expression = null;
+ ArrayList args = new ArrayList();
+ Token funcToken = null;
+}
+{
+ (funcToken = <XMLFOREST> | funcToken = <XMLATTRIBUTES>)
+ <LPAREN>
+ expression = selectExpression(info)
+ {
+ args.add(expression);
+ expression = null;
+ }
+ (<COMMA> expression=selectExpression(info)
+ {
+ args.add(expression);
+ expression = null;
+ }
+ )*
+ <RPAREN>
+ {
+ return new SQLXMLFunction(funcToken.image, args);
+ }
+}
+
+Constant idExpression() :
+{
+ String id = null;
+}
+{
+ id = id()
+ {
+ return new Constant(id);
+ }
+}
+
+
/**
* Parse a data type name - used only in conversion.
* @return Data type parsed into a constant string object
Modified: trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/main/resources/com/metamatrix/query/i18n.properties 2010-05-06 17:17:44 UTC (rev 2100)
@@ -279,6 +279,7 @@
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, 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 or XMLFOREST
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
@@ -775,6 +776,10 @@
SystemSource.xmlelement_param1=Element name
SystemSource.xmlelement_param2=Element contents
SystemSource.xmlelement_result=XML result
+SystemSource.xmlconcat_description=Concat XML types.
+SystemSource.xmlconcat_param1=First element
+SystemSource.xmlconcat_param2=Other elements
+SystemSource.xmlconcat_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
Modified: trunk/engine/src/test/java/com/metamatrix/cdk/CommandBuilder.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/cdk/CommandBuilder.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/cdk/CommandBuilder.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -29,10 +29,7 @@
import org.teiid.connector.language.LanguageFactory;
import org.teiid.dqp.internal.datamgr.language.LanguageBridgeFactory;
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixException;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.optimizer.relational.AliasGenerator;
@@ -77,15 +74,9 @@
command.acceptVisitor(new AliasGenerator(supportsGroupAlias));
}
return new LanguageBridgeFactory(metadata).translate(command);
- } catch (QueryParserException e) {
+ } catch (MetaMatrixException e) {
throw new MetaMatrixRuntimeException(e);
- } catch (QueryResolverException e) {
- throw new MetaMatrixRuntimeException(e);
- } catch (MetaMatrixComponentException e) {
- throw new MetaMatrixRuntimeException(e);
- } catch (QueryValidatorException e) {
- throw new MetaMatrixRuntimeException(e);
- }
+ }
}
/**
Modified: trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/function/TestFunctionLibrary.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -27,6 +27,7 @@
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
+import java.sql.Time;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collection;
@@ -45,7 +46,7 @@
import com.metamatrix.common.buffer.BufferManagerFactory;
import com.metamatrix.common.types.ClobType;
import com.metamatrix.common.types.DataTypeManager;
-import com.metamatrix.common.types.SQLXMLImpl;
+import com.metamatrix.common.types.NullType;
import com.metamatrix.common.types.XMLType;
import com.metamatrix.common.util.TimestampWithTimezone;
import com.metamatrix.core.util.ObjectConverterUtil;
@@ -57,17 +58,17 @@
public class TestFunctionLibrary {
// These are just used as shorthand convenience to make unit tests more readable below
- private static final Class T_STRING = DataTypeManager.DefaultDataClasses.STRING;
- private static final Class T_INTEGER = DataTypeManager.DefaultDataClasses.INTEGER;
- private static final Class T_BIG_INTEGER = DataTypeManager.DefaultDataClasses.BIG_INTEGER;
- private static final Class T_BIG_DECIMAL = DataTypeManager.DefaultDataClasses.BIG_DECIMAL;
- private static final Class T_LONG = DataTypeManager.DefaultDataClasses.LONG;
- private static final Class T_FLOAT = DataTypeManager.DefaultDataClasses.FLOAT;
- private static final Class T_DOUBLE = DataTypeManager.DefaultDataClasses.DOUBLE;
- private static final Class T_NULL = DataTypeManager.DefaultDataClasses.NULL;
- private static final Class T_TIME = DataTypeManager.DefaultDataClasses.TIME;
- private static final Class T_DATE = DataTypeManager.DefaultDataClasses.DATE;
- private static final Class T_TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
+ 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(SystemFunctionManager.getSystemFunctions(), new FunctionTree(new UDFSource(Collections.EMPTY_LIST)));
@@ -1333,8 +1334,8 @@
CommandContext c = new CommandContext();
c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
ClobType result = (ClobType)helpInvokeMethod("xsltransform", new Class[] {DataTypeManager.DefaultDataClasses.XML, DataTypeManager.DefaultDataClasses.XML},
- new Object[] {new XMLType(new SQLXMLImpl("<?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>")),
- new XMLType(new SQLXMLImpl("<?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>"))}, c);
+ 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);
@@ -1344,10 +1345,39 @@
CommandContext c = new CommandContext();
c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
XMLType result = (XMLType)helpInvokeMethod("xmlelement", new Class[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.OBJECT, DataTypeManager.DefaultDataClasses.OBJECT},
- new Object[] {"foo", "<bar>", new XMLType(new SQLXMLImpl("<?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>"))}, c);
+ new Object[] {"foo", "<bar>", 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)}, c);
String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
assertEquals("<foo><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></foo>", xml);
}
+ @Test public void testInvokeXmlElementWithFragment() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ XMLType result = (XMLType)helpInvokeMethod("xmlelement", new Class[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.OBJECT, DataTypeManager.DefaultDataClasses.OBJECT},
+ new Object[] {"foo", "<bar>", 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("<foo><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></foo>", xml);
+ }
+
+ @Test public void testInvokeXmlElement2() throws Exception {
+ CommandContext c = new CommandContext();
+ c.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
+ XMLType result = (XMLType)helpInvokeMethod("xmlelement", new Class[] {DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.OBJECT},
+ new Object[] {"foo", new Timestamp(0)}, c);
+
+ String xml = ObjectConverterUtil.convertToString(result.getCharacterStream());
+ assertEquals("<foo>1969-12-31T18:00:00</foo>", 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);
+ }
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinWithFunction.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinWithFunction.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestJoinWithFunction.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -62,7 +62,7 @@
* @throws QueryResolverException
* @throws QueryParserException
*/
- public void testNonDeterministicPostJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testNonDeterministicPostJoin() throws Exception {
// source query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -124,7 +124,7 @@
* @throws QueryResolverException
* @throws QueryParserException
*/
- public void testNonDeterministicPreJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testNonDeterministicPreJoin() throws Exception {
// source query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, RAND() AS RandomLeft " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -181,7 +181,7 @@
* @see #testNonDeterministicPostJoin
* @see #testNonDeterministicPreJoin
*/
- public void testNonDeterministicPrePostJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testNonDeterministicPrePostJoin() throws Exception {
// source query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, RAND() AS RandomLeft " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -237,7 +237,7 @@
* @throws QueryResolverException
* @throws QueryParserException
*/
- public void testDeterministicPostJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testDeterministicPostJoin() throws Exception {
// source query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -308,7 +308,7 @@
* @throws QueryResolverException
* @throws QueryParserException
*/
- public void testDeterministicPreJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testDeterministicPreJoin() throws Exception {
// source query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, SQRT(100) AS SqrtLeft " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -375,7 +375,7 @@
* @see #testDeterministicPostJoin
* @see #testDeterministicPreJoin
*/
- public void testDeterministicPrePostJoin() throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public void testDeterministicPrePostJoin() throws Exception {
// sub-query for one side of a JOIN
String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, SQRT(100) AS SqrtLeft " //$NON-NLS-1$
+ "FROM pm1.g1"; //$NON-NLS-1$
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestOptimizer.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestOptimizer.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/TestOptimizer.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -36,10 +36,8 @@
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixException;
-import com.metamatrix.api.exception.query.QueryParserException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.MetaMatrixRuntimeException;
@@ -170,11 +168,11 @@
public static ProcessorPlan helpPlan(String sql,
QueryMetadataInterface md, String[] expected,
CapabilitiesFinder capFinder,
- ComparisonMode mode) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ ComparisonMode mode) throws MetaMatrixComponentException, MetaMatrixProcessingException {
return helpPlan(sql, md, null, capFinder, expected, mode);
}
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic, ComparisonMode mode) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, String[] expectedAtomic, ComparisonMode mode) throws MetaMatrixComponentException, MetaMatrixProcessingException {
return helpPlan(sql, md, null, getGenericFinder(), expectedAtomic, mode);
}
@@ -189,14 +187,14 @@
return helpPlanCommand(command, md, capFinder, null, expectedAtomic, shouldSucceed ? ComparisonMode.CORRECTED_COMMAND_STRING : ComparisonMode.FAILED_PLANNING);
}
- public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, ComparisonMode mode) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ public static ProcessorPlan helpPlan(String sql, QueryMetadataInterface md, List bindings, CapabilitiesFinder capFinder, String[] expectedAtomic, ComparisonMode mode) throws MetaMatrixComponentException, MetaMatrixProcessingException {
Command command = helpGetCommand(sql, md, bindings);
return helpPlanCommand(command, md, capFinder, null, expectedAtomic, mode);
}
- public static Command helpGetCommand(String sql, QueryMetadataInterface md, List bindings) throws QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ public static Command helpGetCommand(String sql, QueryMetadataInterface md, List bindings) throws MetaMatrixComponentException, MetaMatrixProcessingException {
if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
Command command = QueryParser.getQueryParser().parseCommand(sql);
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/batch/TestBatchedUpdatePlanner.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/batch/TestBatchedUpdatePlanner.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/batch/TestBatchedUpdatePlanner.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -29,11 +29,9 @@
import junit.framework.TestCase;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.optimizer.QueryOptimizer;
@@ -67,7 +65,7 @@
super(name);
}
- public static List<Command> helpGetCommands(String[] sql, QueryMetadataInterface md) throws QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ public static List<Command> helpGetCommands(String[] sql, QueryMetadataInterface md) throws MetaMatrixComponentException, MetaMatrixProcessingException {
if(DEBUG) System.out.println("\n####################################\n" + sql); //$NON-NLS-1$
List<Command> commands = new ArrayList<Command>(sql.length);
for (int i = 0; i < sql.length; i++) {
@@ -86,7 +84,7 @@
return commands;
}
- private BatchedUpdateCommand helpGetCommand(String[] sql, QueryMetadataInterface md) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException {
+ private BatchedUpdateCommand helpGetCommand(String[] sql, QueryMetadataInterface md) throws MetaMatrixComponentException, MetaMatrixProcessingException {
BatchedUpdateCommand command = new BatchedUpdateCommand(helpGetCommands(sql, md));
return command;
}
@@ -130,11 +128,11 @@
return new DefaultCapabilitiesFinder(new FakeCapabilities(true));
}
- private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException, QueryPlannerException, QueryMetadataException {
+ private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md) throws MetaMatrixComponentException, QueryMetadataException, MetaMatrixProcessingException {
return helpPlan(sql, md, getGenericFinder(), true);
}
- private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws QueryParserException, QueryResolverException, QueryValidatorException, MetaMatrixComponentException, QueryPlannerException, QueryMetadataException {
+ private BatchedUpdatePlan helpPlan(String[] sql, QueryMetadataInterface md, CapabilitiesFinder capFinder, boolean shouldSucceed) throws MetaMatrixComponentException, QueryMetadataException, MetaMatrixProcessingException {
Command command = helpGetCommand(sql, md);
if (capFinder == null){
@@ -156,7 +154,7 @@
}
}
- private void helpTestPlanner(String[] sql, boolean[] expectedBatching) throws QueryParserException, QueryResolverException, QueryValidatorException, QueryPlannerException, QueryMetadataException, MetaMatrixComponentException {
+ private void helpTestPlanner(String[] sql, boolean[] expectedBatching) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached());
List plans = plan.getUpdatePlans();
assertEquals("Number of child plans did not match expected", expectedBatching.length, plans.size()); //$NON-NLS-1$
@@ -165,7 +163,7 @@
}
}
- private void helpTestPlanner(String[] sql, boolean[] expectedBatching, CapabilitiesFinder capFinder) throws QueryParserException, QueryResolverException, QueryValidatorException, QueryPlannerException, QueryMetadataException, MetaMatrixComponentException {
+ private void helpTestPlanner(String[] sql, boolean[] expectedBatching, CapabilitiesFinder capFinder) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), capFinder, true);
List plans = plan.getUpdatePlans();
assertEquals("Number of child plans did not match expected", expectedBatching.length, plans.size()); //$NON-NLS-1$
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/proc/TestProcedurePlanner.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/proc/TestProcedurePlanner.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/proc/TestProcedurePlanner.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -25,10 +25,8 @@
import junit.framework.TestCase;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.query.analysis.AnalysisRecord;
import com.metamatrix.query.metadata.QueryMetadataInterface;
@@ -57,18 +55,14 @@
// ################ getReplacementClause tests ###################
- private ProcessorPlan helpPlanProcedure(String procedure, String procedureType) throws QueryParserException, QueryResolverException, QueryValidatorException, QueryPlannerException, QueryMetadataException, MetaMatrixComponentException {
+ private ProcessorPlan helpPlanProcedure(String procedure, String procedureType) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
return helpPlanProcedure(null, procedure, procedureType);
}
private ProcessorPlan helpPlanProcedure(String userQuery,
String procedure,
- String procedureType) throws QueryParserException,
- QueryResolverException,
- MetaMatrixComponentException,
- QueryValidatorException,
- QueryPlannerException,
- QueryMetadataException {
+ String procedureType) throws MetaMatrixComponentException,
+ QueryMetadataException, MetaMatrixProcessingException {
QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
QueryParser parser = QueryParser.getQueryParser();
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/TestAliasGenerator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -26,7 +26,8 @@
import org.junit.Test;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.parser.QueryParser;
import com.metamatrix.query.resolver.TestResolver;
@@ -43,7 +44,7 @@
private Command helpTest(String sql,
String expected,
boolean aliasGroups,
- QueryMetadataInterface metadata) throws QueryValidatorException {
+ QueryMetadataInterface metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException {
Command command = TestResolver.helpResolve(sql, metadata, null);
command = QueryRewriter.rewrite(command, metadata, null);
command.acceptVisitor(new AliasGenerator(aliasGroups));
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/rules/TestCalculateCostUtil.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/rules/TestCalculateCostUtil.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/relational/rules/TestCalculateCostUtil.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -27,10 +27,8 @@
import org.junit.Test;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.optimizer.TestOptimizer;
import com.metamatrix.query.optimizer.TestOptimizer.ComparisonMode;
@@ -55,7 +53,7 @@
// HELPERS
// =====================================================================
- private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, QueryMetadataException, MetaMatrixComponentException, QueryValidatorException{
+ private static Criteria helpGetCriteria(String critString, QueryMetadataInterface metadata) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException{
Criteria result = QueryParser.getQueryParser().parseCriteria(critString);
QueryResolver.resolveCriteria(result, metadata);
Modified: trunk/engine/src/test/java/com/metamatrix/query/optimizer/xml/TestXMLPlanner.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/optimizer/xml/TestXMLPlanner.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/optimizer/xml/TestXMLPlanner.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -28,11 +28,9 @@
import junit.framework.TestCase;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.core.id.IDGenerator;
import com.metamatrix.core.id.IntegerIDFactory;
@@ -80,7 +78,7 @@
return preparePlan(command, md, TestOptimizer.getGenericFinder(), null);
}
- private void helpPlanException(String sql, QueryMetadataInterface md) throws QueryMetadataException, MetaMatrixComponentException, QueryParserException, QueryResolverException, QueryValidatorException {
+ private void helpPlanException(String sql, QueryMetadataInterface md) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
Command command = TestXMLProcessor.helpGetCommand(sql, md);
try {
Modified: trunk/engine/src/test/java/com/metamatrix/query/parser/TestParser.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/parser/TestParser.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/parser/TestParser.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -103,9 +103,12 @@
import com.metamatrix.query.sql.symbol.Reference;
import com.metamatrix.query.sql.symbol.ScalarSubquery;
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
+import com.metamatrix.query.sql.symbol.SingleElementSymbol;
import com.metamatrix.query.sql.symbol.TestCaseExpression;
import com.metamatrix.query.sql.symbol.TestSearchedCaseExpression;
+import com.metamatrix.query.sql.symbol.SQLXMLFunction;
+@SuppressWarnings("nls")
public class TestParser {
static void helpTest(String sql, String expectedString, Command expectedCommand) {
@@ -124,7 +127,15 @@
assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
assertEquals("Command objects do not match: ", expectedCommand, actualCommand); //$NON-NLS-1$
}
-
+
+ static void helpTestExpression(String sql, String expectedString, Expression expected) throws QueryParserException {
+ Expression actual = QueryParser.getQueryParser().parseExpression(sql);
+ String actualString = actual.toString();
+
+ assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
+ assertEquals("Command objects do not match: ", expected, actual); //$NON-NLS-1$
+ }
+
static void helpException(String sql) {
helpException(sql, null);
}
@@ -6706,5 +6717,25 @@
create.setColumns(columns);
helpTest("Create local TEMPORARY table tempTable (c1 varchar, c2 tinyint, c3 smallint, c4 real, c5 decimal)", "CREATE LOCAL TEMPORARY TABLE tempTable (c1 string, c2 byte, c3 short, c4 float, c5 bigdecimal)", create); //$NON-NLS-1$
}
+
+ @Test public void testXmlElement() throws Exception {
+ Function f = new Function("xmlelement", new Expression[] {new Constant("table"), new Constant("x")});
+ helpTestExpression("xmlelement(name \"table\", 'x')", "xmlelement(NAME \"table\", 'x')", f);
+ }
+ @Test public void testXmlElement1() throws Exception {
+ Function f = new Function("xmlelement", new Expression[] {new Constant("table"), new Constant("x")});
+ helpTestExpression("xmlelement(\"table\", 'x')", "xmlelement(NAME \"table\", 'x')", f);
+ }
+
+ @Test public void testXmlElementWithAttributes() throws Exception {
+ Function f = new Function("xmlelement", new Expression[] {new Constant("y"), new SQLXMLFunction("xmlattributes", Arrays.asList((SingleElementSymbol)new AliasSymbol("val", new ExpressionSymbol("", new Constant("a")))))});
+ helpTestExpression("xmlelement(y, xmlattributes('a' as val))", "xmlelement(NAME y, xmlattributes('a' AS val))", f);
+ }
+
+ @Test public void testXmlForest() throws Exception {
+ SQLXMLFunction f = new SQLXMLFunction("xmlforest", Arrays.asList((SingleElementSymbol)new AliasSymbol("table", new ElementSymbol("a"))));
+ helpTestExpression("xmlforest(a as \"table\")", "xmlforest(a AS \"table\")", f);
+ }
+
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -25,10 +25,10 @@
import java.util.Arrays;
import java.util.List;
+import junit.framework.TestCase;
+
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.query.optimizer.TestOptimizer;
import com.metamatrix.query.optimizer.capabilities.BasicSourceCapabilities;
import com.metamatrix.query.optimizer.capabilities.FakeCapabilitiesFinder;
@@ -41,9 +41,7 @@
import com.metamatrix.query.unittest.FakeMetadataFactory;
import com.metamatrix.query.unittest.FakeMetadataObject;
-import junit.framework.TestCase;
-
public class TestDependentJoins extends TestCase {
/**
@@ -512,8 +510,7 @@
}
private HardcodedDataManager helpTestDependentJoin(boolean unlimitIn)
- throws QueryParserException, QueryResolverException,
- QueryValidatorException, MetaMatrixComponentException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/TestProcessor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -7487,12 +7487,12 @@
String sql = "SELECT xmlelement(e1, e2) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
List[] expected = new List[] {
- Arrays.asList(new String[] {null}),
- Arrays.asList("<a>0</a>"),
- Arrays.asList("<a>0</a>"),
- Arrays.asList("<a>3</a>"),
- Arrays.asList("<b>2</b>"),
- Arrays.asList("<c>1</c>"),
+ Arrays.asList("<e1>1</e1>"),
+ Arrays.asList("<e1>0</e1>"),
+ Arrays.asList("<e1>0</e1>"),
+ Arrays.asList("<e1>3</e1>"),
+ Arrays.asList("<e1>2</e1>"),
+ Arrays.asList("<e1>1</e1>"),
};
FakeDataManager dataManager = new FakeDataManager();
@@ -7503,5 +7503,57 @@
helpProcess(plan, dataManager, expected);
}
+ @Test public void testXmlElementWithConcat() {
+ String sql = "SELECT xmlelement(e1, e2, xmlconcat(xmlelement(x), xmlelement(y, e3))) from pm1.g1 order by e1, e2"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<e1>1<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>0<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>3<x></x><y>true</y></e1>"),
+ Arrays.asList("<e1>2<x></x><y>false</y></e1>"),
+ Arrays.asList("<e1>1<x></x><y>true</y></e1>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testXmlElementWithForest() {
+ String sql = "SELECT xmlelement(x, xmlforest(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<x><e2>1</e2><val>1</val></x>"), //note e1 is not present, because it's null
+ Arrays.asList("<x><e1>a</e1><e2>0</e2><val>1</val></x>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testXmlElementWithAttributes() {
+ String sql = "SELECT xmlelement(x, xmlattributes(e1, e2, '1' as val)) from pm1.g1 order by e1, e2 limit 2"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<x e2=\"1\" val=\"1\"></x>"), //note e1 is not present, because it's null
+ Arrays.asList("<x e1=\"a\" e2=\"0\" val=\"1\"></x>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
private static final boolean DEBUG = false;
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestInstructions.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestInstructions.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestInstructions.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -29,9 +29,9 @@
import junit.framework.TestCase;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.BufferManagerFactory;
import com.metamatrix.common.types.DataTypeManager;
@@ -112,7 +112,7 @@
return new FakeMetadataFacade(store);
}
- private Command helpGetCommand(String sql, FakeMetadataFacade metadata) throws QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ private Command helpGetCommand(String sql, FakeMetadataFacade metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException {
// parse
QueryParser parser = new QueryParser();
Command command = parser.parseCommand(sql);
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestXMLProcessor.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestXMLProcessor.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/xml/TestXMLProcessor.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -39,10 +39,7 @@
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
-import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.BufferManagerFactory;
import com.metamatrix.common.buffer.TupleBuffer;
@@ -84,7 +81,6 @@
import com.metamatrix.query.unittest.FakeMetadataObject;
import com.metamatrix.query.unittest.FakeMetadataStore;
import com.metamatrix.query.util.CommandContext;
-import com.metamatrix.query.util.XMLFormatConstants;
/**
* Tests XML processing, which involves XMLPlanner making a ProcessorPlan
@@ -2927,7 +2923,7 @@
return dataMgr;
}
- public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ public static Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException {
QueryParser parser = new QueryParser();
Command command = parser.parseCommand(sql);
QueryResolver.resolveCommand(command, metadata);
Modified: trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestOrderByRewrite.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestOrderByRewrite.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestOrderByRewrite.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -32,9 +32,7 @@
import org.junit.Test;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.query.parser.QueryParser;
import com.metamatrix.query.resolver.QueryResolver;
import com.metamatrix.query.sql.LanguageObject;
@@ -53,7 +51,7 @@
*/
public class TestOrderByRewrite {
- private static Command getCommand(String sql) throws QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ private static Command getCommand(String sql) throws MetaMatrixComponentException, MetaMatrixProcessingException {
Command command = QueryParser.getQueryParser().parseCommand(sql);
QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
Modified: trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/rewriter/TestQueryRewriter.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -37,16 +37,18 @@
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
+import com.metamatrix.api.exception.query.ExpressionEvaluationException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryResolverException;
import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.common.buffer.BufferManagerFactory;
import com.metamatrix.common.types.DataTypeManager;
import com.metamatrix.common.util.TimestampWithTimezone;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.parser.QueryParser;
import com.metamatrix.query.resolver.QueryResolver;
+import com.metamatrix.query.resolver.util.ResolverVisitor;
import com.metamatrix.query.sql.lang.Command;
import com.metamatrix.query.sql.lang.CompareCriteria;
import com.metamatrix.query.sql.lang.CompoundCriteria;
@@ -62,6 +64,7 @@
import com.metamatrix.query.sql.proc.CreateUpdateProcedureCommand;
import com.metamatrix.query.sql.symbol.Constant;
import com.metamatrix.query.sql.symbol.ElementSymbol;
+import com.metamatrix.query.sql.symbol.Expression;
import com.metamatrix.query.sql.symbol.ExpressionSymbol;
import com.metamatrix.query.sql.symbol.GroupSymbol;
import com.metamatrix.query.sql.symbol.Reference;
@@ -73,7 +76,8 @@
import com.metamatrix.query.unittest.FakeMetadataObject;
import com.metamatrix.query.util.CommandContext;
import com.metamatrix.query.util.ContextProperties;
-
+
+@SuppressWarnings("nls")
public class TestQueryRewriter {
private static final String TRUE_STR = "1 = 1"; //$NON-NLS-1$
@@ -102,7 +106,7 @@
}
}
- private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryResolverException, QueryMetadataException, MetaMatrixComponentException, QueryValidatorException {
+ private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, MetaMatrixComponentException, MetaMatrixProcessingException {
FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
Criteria expectedCrit = parseCriteria(expected, metadata);
if (rewrite) {
@@ -120,22 +124,35 @@
try {
actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
assertEquals("Did not rewrite correctly: ", expectedCrit, actual); //$NON-NLS-1$
- } catch(QueryValidatorException e) {
+ } catch(MetaMatrixException e) {
throw new RuntimeException(e);
}
return actual;
- }
+ }
+
+ private Expression helpTestRewriteExpression(String original, String expected, QueryMetadataInterface metadata) throws MetaMatrixComponentException, MetaMatrixProcessingException {
+ 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 QueryParserException, QueryResolverException, MetaMatrixComponentException, QueryValidatorException {
+ private String getRewritenProcedure(String procedure, String userUpdateStr, String procedureType) throws MetaMatrixComponentException, MetaMatrixProcessingException {
QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
return getRewritenProcedure(userUpdateStr, metadata);
}
private String getRewritenProcedure(String userUpdateStr,
- QueryMetadataInterface metadata) throws QueryParserException,
- QueryResolverException, MetaMatrixComponentException,
- QueryMetadataException, QueryValidatorException {
+ QueryMetadataInterface metadata) throws MetaMatrixComponentException,
+ QueryMetadataException, MetaMatrixProcessingException {
ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
QueryResolver.resolveCommand(userCommand, metadata);
CreateUpdateProcedureCommand proc = (CreateUpdateProcedureCommand)QueryResolver.expandCommand(userCommand, metadata, null);
@@ -399,7 +416,7 @@
try {
QueryRewriter.rewriteCriteria(origCrit, null, null, null);
fail("Expected failure"); //$NON-NLS-1$
- } catch(QueryValidatorException e) {
+ } catch(MetaMatrixException 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$
}
}
@@ -1250,7 +1267,7 @@
// 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=QueryValidatorException.class) public void testRewriteProcedure21() throws Exception {
+ @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$
@@ -1515,9 +1532,9 @@
try {
QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
fail("Expected QueryValidatorException due to divide by 0"); //$NON-NLS-1$
- } catch(QueryValidatorException e) {
+ } catch(MetaMatrixException e) {
// looks like message is being wrapped with another exception with same message
- assertEquals("Error Code:ERR.015.001.0003 Message: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$
+ 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$
}
}
@@ -1529,8 +1546,8 @@
try {
QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
fail("Expected QueryValidatorException due to invalid string"); //$NON-NLS-1$
- } catch(QueryValidatorException e) {
- assertEquals("Error Code:ERR.015.009.0004 Message:Unable to convert 'x' of type [string] to the expected type [integer].", e.getMessage()); //$NON-NLS-1$
+ } catch(MetaMatrixException 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$
}
}
@@ -1953,7 +1970,7 @@
new Class[] { DataTypeManager.DefaultDataClasses.STRING});
}
- private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws QueryValidatorException, QueryParserException, QueryResolverException, MetaMatrixComponentException {
+ private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws MetaMatrixComponentException, MetaMatrixProcessingException {
SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
QueryResolver.resolveCommand(union, FakeMetadataFactory.example1Cached());
@@ -2248,4 +2265,11 @@
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 = "convert(xmlelement(name a, xmlattributes('b' as c)), string)"; //$NON-NLS-1$
+ QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+ helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
+ }
+
}
Modified: trunk/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/com/metamatrix/query/validator/TestValidator.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -1957,5 +1957,9 @@
@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[] {"'1'"}, exampleMetadata2()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
}
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -37,6 +37,7 @@
import org.teiid.dqp.internal.datamgr.impl.FakeTransactionService;
import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryParserException;
import com.metamatrix.api.exception.query.QueryPlannerException;
import com.metamatrix.api.exception.query.QueryResolverException;
@@ -206,17 +207,13 @@
}
static public PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values, SessionAwareCache<PreparedPlan> prepPlanCache)
- throws MetaMatrixComponentException, QueryParserException,
- QueryResolverException, QueryValidatorException,
- QueryPlannerException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
return helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), prepPlanCache, SESSION_ID, false, false, FakeMetadataFactory.example1VDB());
}
static public PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
SessionAwareCache<PreparedPlan> prepPlanCache, int conn)
- throws MetaMatrixComponentException, QueryParserException,
- QueryResolverException, QueryValidatorException,
- QueryPlannerException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
return helpGetProcessorPlan(preparedSql, values,
new DefaultCapabilitiesFinder(), FakeMetadataFactory
.example1Cached(), prepPlanCache, conn, false, false, FakeMetadataFactory.example1VDB());
@@ -224,9 +221,7 @@
static PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
CapabilitiesFinder capFinder, QueryMetadataInterface metadata, SessionAwareCache<PreparedPlan> prepPlanCache, int conn, boolean callableStatement, boolean limitResults, VDBMetaData vdb)
- throws MetaMatrixComponentException, QueryParserException,
- QueryResolverException, QueryValidatorException,
- QueryPlannerException {
+ throws MetaMatrixComponentException, MetaMatrixProcessingException {
//Create Request
RequestMessage request = new RequestMessage(preparedSql);
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java 2010-05-05 17:03:24 UTC (rev 2099)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java 2010-05-06 17:17:44 UTC (rev 2100)
@@ -34,10 +34,7 @@
import org.teiid.dqp.internal.datamgr.impl.FakeTransactionService;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.api.exception.query.QueryParserException;
-import com.metamatrix.api.exception.query.QueryPlannerException;
-import com.metamatrix.api.exception.query.QueryResolverException;
-import com.metamatrix.api.exception.query.QueryValidatorException;
+import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.dqp.service.AutoGenDataService;
import com.metamatrix.query.analysis.AnalysisRecord;
@@ -128,11 +125,8 @@
assertEquals("1", request.context.getEnvironmentProperties().get(ContextProperties.SESSION_ID)); //$NON-NLS-1$
}
- private Request helpProcessMessage(RequestMessage message, SessionAwareCache<PreparedPlan> cache, DQPWorkContext workContext) throws QueryValidatorException,
- QueryParserException,
- QueryResolverException,
- MetaMatrixComponentException,
- QueryPlannerException {
+ private Request helpProcessMessage(RequestMessage message, SessionAwareCache<PreparedPlan> cache, DQPWorkContext workContext) throws MetaMatrixComponentException,
+ MetaMatrixProcessingException {
Request request = null;
if (cache != null) {
request = new PreparedStatementRequest(cache);
13 years, 11 months
teiid SVN: r2099 - trunk/adminshell/src/main/java/org/teiid/adminshell.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-05 13:03:24 -0400 (Wed, 05 May 2010)
New Revision: 2099
Modified:
trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
Log:
TEIID-1085 fix to remove the connection
Modified: trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
===================================================================
--- trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-05 15:23:21 UTC (rev 2098)
+++ trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-05 17:03:24 UTC (rev 2099)
@@ -41,7 +41,6 @@
import org.teiid.adminapi.AdminFactory;
import org.teiid.adminapi.AdminProcessingException;
import org.teiid.adminapi.ConnectionFactory;
-import org.teiid.adminapi.ConnectionPoolStatistics;
import org.teiid.adminapi.ProcessObject;
import org.teiid.adminapi.PropertyDefinition;
import org.teiid.adminapi.Request;
@@ -442,8 +441,8 @@
if (internalAdmin != null) {
internalAdmin.close();
internalAdmin = null;
- currentName = null;
connections.remove(currentName);
+ currentName = null;
}
}
13 years, 11 months
teiid SVN: r2098 - trunk/test-integration/db/src/main/java/org/teiid/test/client.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2010-05-05 11:23:21 -0400 (Wed, 05 May 2010)
New Revision: 2098
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/client/TestResultsSummary.java
Log:
Teiid-773 - changes to write out all the errors across all scenarios to a summary file
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/client/TestResultsSummary.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/client/TestResultsSummary.java 2010-05-04 19:00:28 UTC (rev 2097)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/client/TestResultsSummary.java 2010-05-05 15:23:21 UTC (rev 2098)
@@ -33,6 +33,7 @@
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
@@ -47,7 +48,8 @@
public class TestResultsSummary {
- private static final String OVERALL_SUMMARY_FILE = "Summary.txt";
+ private static final String OVERALL_SUMMARY_FILE = "Summary_totals.txt";
+ private static final String OVERALL_SUMMARY_ERROR_FILE = "Summary_errors.txt";
private static final String PROP_SUMMARY_PRT_DIR = "summarydir";
private static final SimpleDateFormat FILE_NAME_DATE_FORMATER = new SimpleDateFormat(
"yyyyMMdd_HHmmss"); //$NON-NLS-1$
@@ -101,11 +103,14 @@
return new PrintStream(os);
}
- private static Writer getOverallSummaryStream(String outputDir) throws IOException {
- return createOverallSummaryFile(outputDir);
-
- }
+// private static Writer getOverallSummaryStream(String outputDir) throws IOException {
+// return createOverallSummaryFile(outputDir);
+//
+// }
+
+
+
/**
* Overloaded to overwrite the already existing files
*/
@@ -157,7 +162,7 @@
return summaryFile;
}
- private static Writer createOverallSummaryFile(String outputDir)
+ private static Writer getOverallSummaryStream(String outputDir)
throws IOException {
boolean exists = false;
File summaryFile = new File(outputDir, OVERALL_SUMMARY_FILE); //$NON-NLS-1$
@@ -190,7 +195,7 @@
overallsummary.write("================== \n"); //$NON-NLS-1$
overallsummary
- .write("Scenario \t\t" + "Pass" + "\t" + "Fail" + "\t" + "Total \n"); //$NON-NLS-1$
+ .write("Scenario \t\t\t" + "Pass" + "\t" + "Fail" + "\t" + "Total \n"); //$NON-NLS-1$
overallsummary.flush();
@@ -200,7 +205,52 @@
}
+
+
+ private static Writer getOverallSummaryErrorsStream(String outputDir)
+ throws IOException {
+ boolean exists = false;
+ File summaryFile = new File(outputDir, OVERALL_SUMMARY_ERROR_FILE); //$NON-NLS-1$
+ exists = summaryFile.exists();
+ FileWriter fstream = new FileWriter(summaryFile,true);
+ BufferedWriter out = new BufferedWriter(fstream);
+ if (!exists) {
+
+ try {
+ summaryFile.createNewFile();
+ } catch (IOException e) {
+ System.err
+ .println("Failed to create overall summary error file at: " + summaryFile.getAbsolutePath()); //$NON-NLS-1$
+ throw new IOException(
+ "Failed to create overall summary error file at: " + summaryFile.getAbsolutePath() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ printOverallSummaryErrorHeadings(out);
+ }
+
+
+ return out;
+ }
+
+ private static void printOverallSummaryErrorHeadings(Writer overallsummary) {
+
+ try {
+ overallsummary.write("================== \n"); //$NON-NLS-1$
+ overallsummary.write("Test Summary Errors \n"); //$NON-NLS-1$
+ overallsummary.write("================== \n"); //$NON-NLS-1$
+
+ overallsummary
+ .write("Scenario \t" + "Error \n"); //$NON-NLS-1$
+
+ overallsummary.flush();
+
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+
+ }
+
+
private void printQueryTestResults(PrintStream outputStream,
Date testStartTS, Date endTS, Date length, int numberOfClients,
SimpleDateFormat formatter, Collection results) {
@@ -458,11 +508,13 @@
PrintStream outputStream = null;
Writer overallsummary = null;
+ Writer overallsummaryerrors = null;
try {
outputStream = getSummaryStream(summarydir,
"Summary_" + querysetname + "_" + scenario_name, true); //$NON-NLS-1$
overallsummary = getOverallSummaryStream(summarydir);
+ overallsummaryerrors = getOverallSummaryErrorsStream(summarydir);
} catch (IOException e) {
e.printStackTrace();
// logError("Unable to get output stream for file: " + outputFileName); //$NON-NLS-1$
@@ -484,10 +536,9 @@
if (!this.query_sets.isEmpty()) {
// sort so that like failed queries are show together
Collections.sort(this.query_sets);
-
+
for (Iterator<String> it = this.query_sets.iterator(); it.hasNext();) {
outputStream.println(it.next()); //$NON-NLS-1$ //$NON-NLS-2$
-
}
}
@@ -497,20 +548,20 @@
+ total_fail + "\t" + total_queries + "\t" + total_seconds
/ 1000);
- overallsummary.write(scenario_name + " \t" + total_pass + "\t" + total_fail + "\t" + total_queries + "\n");
+
try {
+ overallsummary.write( pad(scenario_name, 30, ' ') + " \t" + total_pass + "\t" + total_fail + "\t" + total_queries + "\n");
overallsummary.flush();
- overallsummary.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- } finally { // always close the file
- try {
- overallsummary.close();
- } catch (IOException ioe2) {
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ } finally { // always close the file
+ try {
+ overallsummary.close();
+ } catch (IOException ioe2) {
// just ignore it
- }
- } //
+ }
+ } //
// outputStream
// .println("Number of Queries: " + total_queries); //$NON-NLS-1$ //$NON-NLS-2$
@@ -524,14 +575,34 @@
Collections.sort(this.failed_queries);
outputStream.println("\n\n=================="); //$NON-NLS-1$
- outputStream.println("Failed Queries"); //$NON-NLS-1$
+ outputStream.println("Failed Queries"); //$NON-NLS-1$
+
+ overallsummaryerrors.write("\n" + scenario_name + "\n");
+
for (Iterator<String> it = this.failed_queries.iterator(); it
.hasNext();) {
- outputStream.println("\t - " + it.next()); //$NON-NLS-1$ //$NON-NLS-2$
+ String error = it.next();
+ outputStream.println("\t - " + error); //$NON-NLS-1$ //$NON-NLS-2$
+ // write all errors to the summary file
+ overallsummaryerrors.write("\t\t" + error + "\n");
+
}
+
+ try {
+ overallsummaryerrors.flush();
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ } finally { // always close the file
+ try {
+ overallsummaryerrors.close();
+ } catch (IOException ioe2) {
+ // just ignore it
+ }
+ } //
+
outputStream.println("=================="); //$NON-NLS-1$
}
@@ -539,6 +610,21 @@
outputStream.close();
}
+
+ private static String pad(String src, int padTo, char padChar) {
+ int numPad = padTo - src.length();
+ if (numPad > 0) {
+ StringBuffer sb = new StringBuffer();
+ char[] pad = new char[numPad] ;
+ Arrays.fill(pad, padChar);
+ sb.append(src);
+ sb.append(pad);
+ return sb.toString();
+ }
+
+ return src;
+
+ }
private static String generateFileName(String configName, long timestamp,
int runNumber) {
13 years, 11 months