teiid SVN: r4067 - in trunk/engine/src: main/javacc/org/teiid/query/parser and 2 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2012-05-07 14:26:07 -0400 (Mon, 07 May 2012)
New Revision: 4067
Modified:
trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java
trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
Log:
TEIID-2032, TEIID-2033: Adding OPTIONS on KEYS
Modified: trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2012-05-07 18:23:09 UTC (rev 4066)
+++ trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2012-05-07 18:26:07 UTC (rev 4067)
@@ -359,19 +359,29 @@
setCommonProperties(c, props);
String v = props.remove("CASE_SENSITIVE"); //$NON-NLS-1$
- c.setCaseSensitive(isTrue(v));
+ if (v != null) {
+ c.setCaseSensitive(isTrue(v));
+ }
v = props.remove("SELECTABLE"); //$NON-NLS-1$
- c.setSelectable(isTrue(v));
+ if (v != null) {
+ c.setSelectable(isTrue(v));
+ }
v = props.remove("UPDATABLE"); //$NON-NLS-1$
- c.setUpdatable(isTrue(v));
+ if (v != null) {
+ c.setUpdatable(isTrue(v));
+ }
v = props.remove("SIGNED"); //$NON-NLS-1$
- c.setSigned(isTrue(v));
+ if (v != null) {
+ c.setSigned(isTrue(v));
+ }
v = props.remove("CURRENCY"); //$NON-NLS-1$
- c.setSigned(isTrue(v));
+ if (v != null) {
+ c.setSigned(isTrue(v));
+ }
v = props.remove("FIXED_LENGTH"); //$NON-NLS-1$
c.setFixedLength(isTrue(v));
@@ -382,10 +392,14 @@
}
v = props.remove("MIN_VALUE"); //$NON-NLS-1$
- c.setMinimumValue(v);
+ if (v != null) {
+ c.setMinimumValue(v);
+ }
v = props.remove("MAX_VALUE"); //$NON-NLS-1$
- c.setMaximumValue(v);
+ if (v != null) {
+ c.setMaximumValue(v);
+ }
v = props.remove("CHAR_OCTET_LENGTH"); //$NON-NLS-1$
if (v != null) {
@@ -393,7 +407,9 @@
}
v = props.remove("NATIVE_TYPE"); //$NON-NLS-1$
- c.setNativeType(v);
+ if (v != null) {
+ c.setNativeType(v);
+ }
v = props.remove("RADIX"); //$NON-NLS-1$
if (v != null) {
@@ -411,15 +427,21 @@
}
}
- private void setCommonProperties(AbstractMetadataRecord c, Map<String, String> props) {
+ void setCommonProperties(AbstractMetadataRecord c, Map<String, String> props) {
String v = props.remove("UUID"); //$NON-NLS-1$
- c.setUUID(v);
+ if (v != null) {
+ c.setUUID(v);
+ }
v = props.remove("ANNOTATION"); //$NON-NLS-1$
- c.setAnnotation(v);
+ if (v != null) {
+ c.setAnnotation(v);
+ }
v = props.remove("NAMEINSOURCE"); //$NON-NLS-1$
- c.setNameInSource(v);
+ if (v != null) {
+ c.setNameInSource(v);
+ }
}
void setTableOptions(Table table) {
@@ -427,7 +449,9 @@
setCommonProperties(table, props);
String value = props.remove("MATERIALIZED"); //$NON-NLS-1$
- table.setMaterialized(isTrue(value));
+ if (value != null) {
+ table.setMaterialized(isTrue(value));
+ }
value = props.remove("MATERIALIZED_TABLE"); //$NON-NLS-1$
if (value != null) {
@@ -437,7 +461,9 @@
}
value = props.remove("UPDATABLE"); //$NON-NLS-1$
- table.setSupportsUpdate(isTrue(value));
+ if (value != null) {
+ table.setSupportsUpdate(isTrue(value));
+ }
value = props.remove("CARDINALITY"); //$NON-NLS-1$
if (value != null) {
Modified: trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
===================================================================
--- trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2012-05-07 18:23:09 UTC (rev 4066)
+++ trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2012-05-07 18:26:07 UTC (rev 4067)
@@ -4271,6 +4271,7 @@
KeyRecord pk = null;
Column column = null;
List<String> pkColumnNames = null;
+ KeyRecord key = null;
}
{
<FOREIGN> nonReserved("KEY")
@@ -4285,17 +4286,23 @@
[pkColumnNames = getColumnNames()]
{
try{
- factory.addForiegnKey("FK"+table.getForeignKeys().size(), columnNames, pkColumnNames, viewName, table);
+ key = factory.addForiegnKey("FK"+table.getForeignKeys().size(), columnNames, pkColumnNames, viewName, table);
} catch (TranslatorException e){
throw new ParseException(e.getMessage());
}
}
+ [optionsClause(key, factory)
+ {
+ setCommonProperties(key, key.getProperties());
+ }
+ ]
}
void primaryKeys(MetadataFactory factory, Table table) :
{
List<String> columnNames = null;
Column column = null;
+ KeyRecord key = null;
}
{
<PRIMARY> nonReserved("KEY")
@@ -4308,11 +4315,16 @@
throw new ParseException(QueryPlugin.Util.getString("SQLParser.pk_exists", table.getName()));
}
try{
- factory.addPrimaryKey("PK", columnNames, table);
+ key = factory.addPrimaryKey("PK", columnNames, table);
} catch(TranslatorException e){
throw new ParseException(e.getMessage());
}
}
+ [optionsClause(key, factory)
+ {
+ setCommonProperties(key, key.getProperties());
+ }
+ ]
}
void constraints(MetadataFactory factory, Table table) :
@@ -4321,6 +4333,7 @@
Column column = null;
List<String> columnNames = null;
String type = null;
+ KeyRecord key = null;
}
{
( <UNIQUE> { type = "UNIQUE"; } | type = nonReserved("INDEX","ACCESSPATTERN"))
@@ -4331,18 +4344,23 @@
}
try{
if (type.equalsIgnoreCase("INDEX")) {
- factory.addIndex("INDEX"+table.getIndexes().size(), true, columnNames, table);
+ key = factory.addIndex("INDEX"+table.getIndexes().size(), true, columnNames, table);
}
if (type.equalsIgnoreCase("UNIQUE")) {
- factory.addIndex("UNIQUE"+table.getUniqueKeys().size(), false, columnNames, table);
+ key = factory.addIndex("UNIQUE"+table.getUniqueKeys().size(), false, columnNames, table);
}
if (type.equalsIgnoreCase("ACCESSPATTERN")) {
- factory.addAccessPattern("AP"+table.getAccessPatterns().size(), columnNames, table);
+ key = factory.addAccessPattern("AP"+table.getAccessPatterns().size(), columnNames, table);
}
}catch(TranslatorException e){
throw new ParseException(e.getMessage());
}
}
+ [optionsClause(key, factory)
+ {
+ setCommonProperties(key, key.getProperties());
+ }
+ ]
}
ArrayList<String> getColumnNames() :
Modified: trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java 2012-05-07 18:23:09 UTC (rev 4066)
+++ trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java 2012-05-07 18:26:07 UTC (rev 4067)
@@ -22,6 +22,8 @@
*/
import static org.junit.Assert.*;
+import java.io.File;
+import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -31,8 +33,9 @@
import org.teiid.adminapi.impl.ModelMetaData;
import org.teiid.adminapi.impl.VDBMetaData;
import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.metadata.BaseColumn.NullType;
import org.teiid.metadata.*;
-import org.teiid.metadata.BaseColumn.NullType;
import org.teiid.query.metadata.MetadataValidator;
import org.teiid.query.validator.ValidatorReport;
@@ -140,6 +143,18 @@
}
@Test
+ public void testOptionsKey() throws Exception {
+ String ddl = "CREATE FOREIGN TABLE G1( e1 integer, e2 varchar, e3 date CONSTRAINT UNIQUE (e1) OPTIONS (CUSTOM_PROP 'VALUE'))";
+ Schema s = helpParse(ddl, "model");
+ Map<String, Table> tableMap = s.getTables();
+
+ assertTrue("Table not found", tableMap.containsKey("G1"));
+ Table table = tableMap.get("G1");
+ KeyRecord record = table.getAllKeys().iterator().next();
+ assertEquals("VALUE", record.getProperty("CUSTOM_PROP", false));
+ }
+
+ @Test
public void testConstraints() throws Exception {
String ddl = "CREATE FOREIGN TABLE G1( e1 integer, e2 varchar, e3 date " +
" CONSTRAINT PRIMARY KEY (e1, e2), INDEX(e2, e3), ACCESSPATTERN(e1), UNIQUE(e1)," +
@@ -604,6 +619,12 @@
return mf;
}
+ public MetadataFactory buildMetadataFactory(File ddlFile, String model) throws IOException, ParseException {
+ MetadataFactory mf = new MetadataFactory(null, 1, model, getDataTypes(), new Properties(), null);
+ parser.parseDDL(mf, ObjectConverterUtil.convertFileToString(ddlFile));
+ return mf;
+ }
+
//TODO: could elevate type logic out of metadata
public static Map<String, Datatype> getDataTypes() {
Map<String, Datatype> datatypes = new HashMap<String, Datatype>();
Modified: trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java 2012-05-07 18:23:09 UTC (rev 4066)
+++ trunk/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java 2012-05-07 18:26:07 UTC (rev 4067)
@@ -22,6 +22,7 @@
package org.teiid.query.unittest;
+import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -41,8 +42,8 @@
import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
import org.teiid.core.types.DataTypeManager.DefaultDataTypes;
import org.teiid.dqp.internal.process.DQPWorkContext;
-import org.teiid.metadata.*;
import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.metadata.*;
import org.teiid.metadata.Column.SearchType;
import org.teiid.metadata.ProcedureParameter.Type;
import org.teiid.metadata.Table.TriggerEvent;
@@ -50,18 +51,12 @@
import org.teiid.query.function.SystemFunctionManager;
import org.teiid.query.function.UDFSource;
import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingNode;
-import org.teiid.query.mapping.xml.MappingOutputter;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.mapping.xml.MappingVisitor;
-import org.teiid.query.mapping.xml.Navigator;
+import org.teiid.query.mapping.xml.*;
import org.teiid.query.metadata.CompositeMetadataStore;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.query.optimizer.FakeFunctionMetadataSource;
+import org.teiid.query.parser.TestDDLParser;
import org.teiid.query.sql.lang.SPParameter;
@SuppressWarnings("nls")
@@ -2651,5 +2646,9 @@
return createTransformationMetadata(metadataStore, "example4");
}
-
+
+ public static TransformationMetadata fromDDL(File ddlFile, String vdbName, String modelName) throws Exception {
+ MetadataFactory mf = new TestDDLParser().buildMetadataFactory(ddlFile, modelName);
+ return createTransformationMetadata(mf.asMetadataStore(), vdbName);
+ }
}
12 years, 8 months
teiid SVN: r4066 - branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/util.
by teiid-commits@lists.jboss.org
Author: tejones
Date: 2012-05-07 14:23:09 -0400 (Mon, 07 May 2012)
New Revision: 4066
Modified:
branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
Log:
TEIID-1996: Added new operation to get query plan for an in-flight session/request.
Modified: branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java
===================================================================
--- branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java 2012-05-07 17:53:08 UTC (rev 4065)
+++ branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/util/PluginConstants.java 2012-05-07 18:23:09 UTC (rev 4066)
@@ -77,6 +77,7 @@
public final static String GET_BUFFER_USAGE = "userBufferSpace"; //$NON-NLS-1$
public final static String GET_CACHE_STATS = "getCacheStatistics"; //$NON-NLS-1$
public final static String DEPLOY_VDB_BY_URL = "deployVdbByUrl"; //$NON-NLS-1$
+ public final static String VIEW_QUERY_PLAN = "getPlan"; //$NON-NLS-1$
}
public static interface Metrics {
12 years, 8 months
teiid SVN: r4065 - in branches/7.7.x/connectors: connector-infinispan and 21 other directories.
by teiid-commits@lists.jboss.org
Author: van.halbert
Date: 2012-05-07 13:53:08 -0400 (Mon, 07 May 2012)
New Revision: 4065
Added:
branches/7.7.x/connectors/connector-infinispan/
branches/7.7.x/connectors/connector-infinispan/pom.xml
branches/7.7.x/connectors/connector-infinispan/src/
branches/7.7.x/connectors/connector-infinispan/src/assembly/
branches/7.7.x/connectors/connector-infinispan/src/assembly/kit.xml
branches/7.7.x/connectors/connector-infinispan/src/main/
branches/7.7.x/connectors/connector-infinispan/src/main/ear/
branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/
branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/application.xml
branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/jboss-app.xml
branches/7.7.x/connectors/connector-infinispan/src/main/ear/infinispan-ds.xml
branches/7.7.x/connectors/connector-infinispan/src/main/java/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnection.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnectionFactory.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnection.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnectionFactory.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicResourceAdapter.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionContext.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionRequestInfoWrapper.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ReflectionHelper.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnection.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnectionFactory.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanConnectionImpl.java
branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanManagedConnectionFactory.java
branches/7.7.x/connectors/connector-infinispan/src/main/rar/
branches/7.7.x/connectors/connector-infinispan/src/main/rar/META-INF/
branches/7.7.x/connectors/connector-infinispan/src/main/rar/META-INF/ra.xml
branches/7.7.x/connectors/connector-infinispan/src/main/resources/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/infinispan/
branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/infinispan/i18n.properties
Log:
TEIID-2015 deploy Infinispan as an .ear to an AS 5 server which will support calling Infinispan remotely
Added: branches/7.7.x/connectors/connector-infinispan/pom.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/pom.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/pom.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,149 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.7.1</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-infinispan</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Infinispan Connector</name>
+ <description>This connector reads data from a Infinispan cache</description>
+ <properties>
+ <version.infinispan>5.1.2.FINAL</version.infinispan>
+ <version.hibernate.search>4.1.0.CR1</version.hibernate.search>
+ </properties>
+ <dependencies>
+
+ <dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>translator-object</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <version>1.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-core</artifactId>
+ <version>${version.infinispan}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-client-hotrod</artifactId>
+ <version>${version.infinispan}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.logging</groupId>
+ <artifactId>jboss-logging</artifactId>
+ <version>3.1.1.GA</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.jboss.logmanager</groupId>
+ <artifactId>jboss-logmanager</artifactId>
+ <version>1.2.2.GA</version>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <scope>test</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>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <finalName>infinispan</finalName>
+ <descriptors>
+ <descriptor>src/assembly/kit.xml</descriptor>
+ </descriptors>
+ <outputDirectory>target/distribution</outputDirectory>
+ <workDirectory>target/assembly/work</workDirectory>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-assembly</id>
+ <phase>package</phase>
+ <goals>
+ <goal>attached</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <!-- plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-ear-plugin</artifactId>
+ <version>2.7</version>
+ <configuration>
+ <defaultJavaBundleDir>lib</defaultJavaBundleDir>
+ <modules>
+ <rarModule>
+ <bundleDir>/connector-infinispan.rar</bundleDir>
+ </rarModule>
+ <javaModule>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-core</artifactId>
+ <includeInApplicationXml>true</includeInApplicationXml>
+ </javaModule>
+ <javaModule>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-client-hotrod</artifactId>
+ <includeInApplicationXml>true</includeInApplicationXml>
+ </javaModule>
+
+ </modules>
+
+ <jboss>
+ <data-sources>
+ <data-source>src/kit/infinispan-ds.xml</data-source>
+ </data-sources>
+
+ <loader-repository>
+ org.teiid.resource.adapter:loader=infinispan-jca.ear
+ <loader-repository-config>
+ java2ParentDelegation=false
+ </loader-repository-config>
+ </loader-repository>
+
+ </jboss>
+ </configuration>
+ </plugin -->
+ </plugins>
+ </build>
+</project>
Added: branches/7.7.x/connectors/connector-infinispan/src/assembly/kit.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/assembly/kit.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/assembly/kit.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,63 @@
+<!--This script builds a kit for the ctc-client -->
+<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+
+
+<!--
+ This packages the files into a directory that is then grabbed by the jbossas pom kitting process
+ in order to build a complete set of artifacts to be deployed to a JBoss AS server
+ -->
+
+ <id>jca.ear</id>
+
+ <formats>
+ <format>dir</format>
+ </formats>
+
+ <includeBaseDirectory>false</includeBaseDirectory>
+
+ <baseDirectory>/</baseDirectory>
+
+ <dependencySets>
+
+ <dependencySet>
+ <outputDirectory>connector-infinispan.rar</outputDirectory>
+ <useTransitiveDependencies>true</useTransitiveDependencies>
+
+ <includes>
+
+ <include>org.jboss.teiid.connectors:connector-infinispan</include>
+ <include>org.infinispan:infinispan-core</include>
+ <include>org.infinispan:infinispan-client-hotrod</include>
+
+ <include>commons-pool:commons-pool</include>
+ <include>org.jboss.logging:jboss-logging</include>
+ <include>org.jboss.logmanager:jboss-logmanager</include>
+ <include>org.jboss.marshalling:jboss-marshalling</include>
+ <include>org.jboss.marshalling:jboss-marshalling-river</include>
+
+
+ </includes>
+
+ </dependencySet>
+
+ </dependencySets>
+
+ <fileSets>
+
+ <fileSet>
+ <directory>src/main/ear/</directory>
+ <outputDirectory>/</outputDirectory>
+
+ </fileSet>
+
+ <fileSet>
+ <directory>src/main/rar/</directory>
+ <outputDirectory>connector-infinispan.rar</outputDirectory>
+
+ </fileSet>
+
+ </fileSets>
+
+</assembly>
\ No newline at end of file
Added: branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/application.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/application.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/application.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,12 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE application PUBLIC
+ "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
+ "http://java.sun.com/dtd/application_1_3.dtd">
+
+<application>
+ <display-name>Infinispan</display-name>
+ <module>
+ <connector>connector-infinispan.rar</connector>
+ </module>
+
+</application>
Added: branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/jboss-app.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/jboss-app.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/ear/META-INF/jboss-app.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,16 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE jboss-app
+ PUBLIC "-//JBoss//DTD J2EE Application 1.3V2//EN"
+ "http://www.jboss.org/j2ee/dtd/jboss-app_3_2.dtd">
+<jboss-app>
+ <loader-repository>
+ org.teiid.resource.adapter:loader=infinispan-jca.ear
+ <loader-repository-config>
+ java2ParentDelegation=false
+ </loader-repository-config>
+ </loader-repository>
+
+ <module>
+ <service>infinispan-ds.xml</service>
+ </module>
+</jboss-app>
Added: branches/7.7.x/connectors/connector-infinispan/src/main/ear/infinispan-ds.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/ear/infinispan-ds.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/ear/infinispan-ds.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<connection-factories>
+
+ <no-tx-connection-factory>
+ <!-- The jndi name of the DataSource -->
+ <jndi-name>InfinispanDS</jndi-name>
+
+ <!-- The resource archive file that defines JCA connection for Coherence -->
+ <rar-name>infinispan-jca.ear#connector-infinispan.rar</rar-name>
+ <!-- connection interface; (do not change this) -->
+ <connection-definition>javax.resource.cci.ConnectionFactory</connection-definition>
+
+ <!-- (OPTIONAL) Infinispan Server List -->
+ <!-- config-property name="RemoteInfinispanServerList">host:port[;host:port...]</config-property-->
+<min-pool-size>5</min-pool-size>
+ <max-pool-size>20</max-pool-size>
+
+ </no-tx-connection-factory>
+
+</connection-factories>
\ No newline at end of file
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnection.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnection.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnection.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.resource.adapter.custom.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;
+import javax.resource.spi.ManagedConnection;
+import javax.transaction.xa.XAResource;
+
+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$
+ }
+
+ public XAResource getXAResource() throws ResourceException {
+ return null;
+ }
+
+ /**
+ * Tests the connection to see if it is still valid.
+ * @return
+ */
+ public boolean isAlive() {
+ return true;
+ }
+
+ /**
+ * Called by the {@link ManagedConnection} to indicate the physical connection
+ * should be cleaned up for reuse.
+ */
+ public void cleanUp() {
+
+ }
+
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnectionFactory.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnectionFactory.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicConnectionFactory.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,42 @@
+package org.teiid.resource.adapter.custom.spi;
+
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.resource.ResourceException;
+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 abstract BasicConnection getConnection() throws ResourceException;
+
+ @Override
+ public BasicConnection 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;
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnection.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnection.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnection.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.adapter.custom.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;
+
+
+public class BasicManagedConnection implements ManagedConnection {
+ protected PrintWriter log;
+ protected final Collection<ConnectionEventListener> listeners = new ArrayList<ConnectionEventListener>();
+ private BasicConnection physicalConnection;
+ private final Set<WrappedConnection> handles = new HashSet<WrappedConnection>();
+
+ public BasicManagedConnection(BasicConnection 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();
+ }
+ if (this.physicalConnection != null) {
+ this.physicalConnection.cleanUp();
+ }
+ 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 {
+ 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 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) {
+
+ 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 ResourceException {
+ if (this.physicalConnection == null)
+ throw new ResourceException("Connection has been destroyed!!!"); //$NON-NLS-1$
+ return this.physicalConnection;
+ }
+
+ public boolean isValid() {
+ if (this.physicalConnection == null) {
+ return false;
+ }
+ return this.physicalConnection.isAlive();
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnectionFactory.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnectionFactory.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicManagedConnectionFactory.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,130 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.custom.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;
+
+
+
+public abstract class BasicManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation, ValidatingManagedConnectionFactory {
+
+ private static final long serialVersionUID = -7302713800883776790L;
+ private PrintWriter log;
+ private BasicResourceAdapter ra;
+ private BasicConnectionFactory cf;
+
+ @Override
+ public abstract BasicConnectionFactory createConnectionFactory() throws ResourceException;
+
+ @Override
+ public Object createConnectionFactory(ConnectionManager cm) throws ResourceException {
+ this.cf = createConnectionFactory();
+ return this.cf;
+ // return new WrappedConnectionFactory(this.cf, cm, this);
+ }
+
+ @Override
+ public ManagedConnection createManagedConnection(Subject arg0, ConnectionRequestInfo arg1) throws ResourceException {
+// Assertion.isNotNull(this.cf);
+ ConnectionContext.setSubject(arg0);
+
+ BasicConnection connection = null;
+ if (arg1 instanceof ConnectionRequestInfoWrapper) {
+ connection = this.cf.getConnection(((ConnectionRequestInfoWrapper)arg1).cs);
+ }
+ else {
+ connection = this.cf.getConnection();
+ }
+ ConnectionContext.setSubject(null);
+ return new BasicManagedConnection(connection);
+ }
+
+ @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 ResourceException {
+ try {
+ if (className == null) {
+ if (defaultClass == null) {
+ throw new ResourceException("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 (IllegalAccessException e) {
+ throw new ResourceException(e);
+ } catch(InstantiationException e) {
+ throw new ResourceException(e);
+ } catch (Exception e) {
+ throw new ResourceException(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;
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicResourceAdapter.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicResourceAdapter.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/BasicResourceAdapter.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.adapter.custom.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();
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionContext.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionContext.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionContext.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.custom.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);
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionRequestInfoWrapper.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionRequestInfoWrapper.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ConnectionRequestInfoWrapper.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.custom.spi;
+
+import javax.resource.cci.ConnectionSpec;
+import javax.resource.spi.ConnectionRequestInfo;
+
+class ConnectionRequestInfoWrapper implements ConnectionRequestInfo {
+ ConnectionSpec cs;
+
+ public ConnectionRequestInfoWrapper(ConnectionSpec cs) {
+ this.cs = cs;
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ReflectionHelper.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ReflectionHelper.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/ReflectionHelper.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,329 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.custom.spi;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+
+public class ReflectionHelper {
+
+ private Class<?> targetClass;
+ private Map<String, LinkedList<Method>> methodMap = null; // used for the brute-force method finder
+
+ /**
+ * Construct a ReflectionHelper instance that cache's some information about
+ * the target class. The target class is the Class object upon which the
+ * methods will be found.
+ * @param targetClass the target class
+ * @throws IllegalArgumentException if the target class is null
+ */
+ public ReflectionHelper( Class<?> targetClass ) {
+ if ( targetClass == null ) {
+ throw new IllegalArgumentException("ReflectionHelper.errorConstructing"); //$NON-NLS-1$
+ }
+ this.targetClass = targetClass;
+ }
+
+ /**
+ * Find the best method on the target class that matches the signature specified
+ * with the specified name and the list of arguments. This method first
+ * attempts to find the method with the specified arguments; if no such
+ * method is found, a NoSuchMethodException is thrown.
+ * <P>
+ * This method is unable to find methods with signatures that include both
+ * primitive arguments <i>and</i> arguments that are instances of <code>Number</code>
+ * or its subclasses.
+ * @param methodName the name of the method that is to be invoked.
+ * @param arguments the array of Object instances that correspond
+ * to the arguments passed to the method.
+ * @return the Method object that references the method that satisfies
+ * the requirements, or null if no satisfactory method could be found.
+ * @throws NoSuchMethodException if a matching method is not found.
+ * @throws SecurityException if access to the information is denied.
+ */
+ public Method findBestMethodOnTarget( String methodName, Object[] arguments ) throws NoSuchMethodException, SecurityException {
+ if (arguments == null) {
+ return findBestMethodWithSignature(methodName, Collections.EMPTY_LIST);
+ }
+ int size = arguments.length;
+ List<Class<?>> argumentClasses = new ArrayList<Class<?>>(size);
+ for (int i=0; i!=size; ++i) {
+ if ( arguments[i] != null ) {
+ Class<?> clazz = arguments[i].getClass();
+ argumentClasses.add( clazz );
+ } else {
+ argumentClasses.add(null);
+ }
+ }
+ return findBestMethodWithSignature(methodName,argumentClasses);
+ }
+
+ /**
+ * Find the best method on the target class that matches the signature specified
+ * with the specified name and the list of argument classes. This method first
+ * attempts to find the method with the specified argument classes; if no such
+ * method is found, a NoSuchMethodException is thrown.
+ * @param methodName the name of the method that is to be invoked.
+ * @param argumentsClasses the list of Class instances that correspond
+ * to the classes for each argument passed to the method.
+ * @return the Method object that references the method that satisfies
+ * the requirements, or null if no satisfactory method could be found.
+ * @throws NoSuchMethodException if a matching method is not found.
+ * @throws SecurityException if access to the information is denied.
+ */
+ public Method findBestMethodWithSignature( String methodName, Object[] argumentsClasses ) throws NoSuchMethodException, SecurityException {
+ List argumentClassesList = Arrays.asList(argumentsClasses);
+ return findBestMethodWithSignature(methodName,argumentClassesList);
+ }
+
+ /**
+ * Find the best method on the target class that matches the signature specified
+ * with the specified name and the list of argument classes. This method first
+ * attempts to find the method with the specified argument classes; if no such
+ * method is found, a NoSuchMethodException is thrown.
+ * @param methodName the name of the method that is to be invoked.
+ * @param argumentsClasses the list of Class instances that correspond
+ * to the classes for each argument passed to the method.
+ * @return the Method object that references the method that satisfies
+ * the requirements, or null if no satisfactory method could be found.
+ * @throws NoSuchMethodException if a matching method is not found.
+ * @throws SecurityException if access to the information is denied.
+ */
+ public Method findBestMethodWithSignature( String methodName, List<Class<?>> argumentsClasses ) throws NoSuchMethodException, SecurityException {
+ // Attempt to find the method
+ Method result = null;
+ Class[] classArgs = new Class[argumentsClasses.size()];
+
+ // -------------------------------------------------------------------------------
+ // First try to find the method with EXACTLY the argument classes as specified ...
+ // -------------------------------------------------------------------------------
+ try {
+ argumentsClasses.toArray(classArgs);
+ result = this.targetClass.getMethod(methodName,classArgs); // this may throw an exception if not found
+ return result;
+ } catch ( NoSuchMethodException e ) {
+ // No method found, so continue ...
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // Then try to find a method with the argument classes converted to a primitive, if possible ...
+ // ---------------------------------------------------------------------------------------------
+ List<Class<?>> argumentsClassList = convertArgumentClassesToPrimitives(argumentsClasses);
+ argumentsClassList.toArray(classArgs);
+ try {
+ result = this.targetClass.getMethod(methodName,classArgs); // this may throw an exception if not found
+ return result;
+ } catch ( NoSuchMethodException e ) {
+ // No method found, so continue ...
+ }
+
+ // ---------------------------------------------------------------------------------------------
+ // Still haven't found anything. So far, the "getMethod" logic only finds methods that EXACTLY
+ // match the argument classes (i.e., not methods declared with superclasses or interfaces of
+ // the arguments). There is no canned algorithm in Java to do this, so we have to brute-force it.
+ // ---------------------------------------------------------------------------------------------
+ if ( this.methodMap == null ) {
+ this.methodMap = new HashMap<String, LinkedList<Method>>();
+ Method[] methods = this.targetClass.getMethods();
+ for ( int i=0; i!=methods.length; ++i ) {
+ Method method = methods[i];
+ LinkedList<Method> methodsWithSameName = this.methodMap.get(method.getName());
+ if ( methodsWithSameName == null ) {
+ methodsWithSameName = new LinkedList<Method>();
+ this.methodMap.put(method.getName(),methodsWithSameName);
+ }
+ methodsWithSameName.addFirst(method); // add lower methods first
+ }
+ }
+
+ LinkedList<Method> methodsWithSameName = this.methodMap.get(methodName);
+ if ( methodsWithSameName == null ) {
+ throw new NoSuchMethodException(methodName);
+ }
+ for (Method method : methodsWithSameName) {
+ Class[] args = method.getParameterTypes();
+ boolean allMatch = argsMatch(argumentsClasses, argumentsClassList, args);
+ if ( allMatch ) {
+ if (result != null) {
+ throw new NoSuchMethodException(methodName + " Args: " + argumentsClasses + " has multiple possible signatures."); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ result = method;
+ }
+ }
+
+ if (result != null) {
+ return result;
+ }
+
+ throw new NoSuchMethodException(methodName + " Args: " + argumentsClasses); //$NON-NLS-1$
+ }
+
+ private static boolean argsMatch(List<Class<?>> argumentsClasses,
+ List<Class<?>> argumentsClassList, Class[] args) {
+ if ( args.length != argumentsClasses.size() ) {
+ return false;
+ }
+ for ( int i=0; i<args.length; ++i ) {
+ Class<?> primitiveClazz = argumentsClassList.get(i);
+ Class<?> objectClazz = argumentsClasses.get(i);
+ if ( objectClazz != null ) {
+ // Check for possible matches with (converted) primitive types
+ // as well as the original Object type
+ if ( ! args[i].equals(primitiveClazz) && ! args[i].isAssignableFrom(objectClazz) ) {
+ return false; // found one that doesn't match
+ }
+ } else {
+ // a null is assignable for everything except a primitive
+ if ( args[i].isPrimitive() ) {
+ return false; // found one that doesn't match
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Convert any argument classes to primitives.
+ * @param arguments the list of argument classes.
+ * @return the list of Class instances in which any classes that could be represented
+ * by primitives (e.g., Boolean) were replaced with the primitive classes (e.g., Boolean.TYPE).
+ */
+ private static List<Class<?>> convertArgumentClassesToPrimitives( List<Class<?>> arguments ) {
+ List<Class<?>> result = new ArrayList<Class<?>>(arguments.size());
+ for (Class<?> clazz : arguments) {
+ if ( clazz == Boolean.class ) clazz = Boolean.TYPE;
+ else if ( clazz == Character.class ) clazz = Character.TYPE;
+ else if ( clazz == Byte.class ) clazz = Byte.TYPE;
+ else if ( clazz == Short.class ) clazz = Short.TYPE;
+ else if ( clazz == Integer.class ) clazz = Integer.TYPE;
+ else if ( clazz == Long.class ) clazz = Long.TYPE;
+ else if ( clazz == Float.class ) clazz = Float.TYPE;
+ else if ( clazz == Double.class ) clazz = Double.TYPE;
+ else if ( clazz == Void.class ) clazz = Void.TYPE;
+ result.add( clazz );
+ }
+
+ return result;
+ }
+
+ /**
+ * Helper method to load a class.
+ * @param className is the class to instantiate
+ * @param classLoader the class loader to use; may be null if the current
+ * class loader is to be used
+ * @return Class is the instance of the class
+ * @throws ClassNotFoundException
+ */
+ private static final Class<?> loadClass(final String className, final ClassLoader classLoader) throws ClassNotFoundException {
+ Class<?> cls = null;
+ if ( classLoader == null ) {
+ cls = Class.forName(className.trim());
+ } else {
+ cls = Class.forName(className.trim(),true,classLoader);
+ }
+ return cls;
+ }
+
+ /**
+ * Helper method to create an instance of the class using the appropriate
+ * constructor based on the ctorObjs passed.
+ * @param className is the class to instantiate
+ * @param ctorObjs are the objects to pass to the constructor; optional, nullable
+ * @param classLoader the class loader to use; may be null if the current
+ * class loader is to be used
+ * @return Object is the instance of the class
+ * @throws Exception if an error occurs instantiating the class
+ */
+
+ public static final Object create(String className, Collection<?> ctorObjs,
+ final ClassLoader classLoader) throws Exception {
+ try {
+ int size = (ctorObjs == null ? 0 : ctorObjs.size());
+ Class[] names = new Class[size];
+ Object[] objArray = new Object[size];
+ int i = 0;
+
+ if (size > 0) {
+ for (Iterator<?> it=ctorObjs.iterator(); it.hasNext(); ) {
+ Object obj = it.next();
+ if (obj != null) {
+ names[i] = obj.getClass();
+ objArray[i] = obj;
+ }
+ i++;
+ }
+ }
+ return create(className, objArray, names, classLoader);
+ } catch (Exception e) {
+ throw new Exception(e);
+ }
+ }
+
+ public static final Object create(String className, Object[] ctorObjs, Class<?>[] argTypes,
+ final ClassLoader classLoader) throws Exception {
+ Class<?> cls;
+ try {
+ cls = loadClass(className,classLoader);
+ } catch(Exception e) {
+ throw new Exception(e);
+ }
+ Constructor<?> ctor = null;
+ try {
+ ctor = cls.getDeclaredConstructor(argTypes);
+ } catch (NoSuchMethodException e) {
+
+ }
+
+ if (ctor == null && argTypes != null && argTypes.length > 0) {
+ List<Class<?>> argumentsClasses = Arrays.asList(argTypes);
+ List<Class<?>> argumentsClassList = convertArgumentClassesToPrimitives(argumentsClasses);
+ for (Constructor<?> possible : cls.getDeclaredConstructors()) {
+ if (argsMatch(argumentsClasses, argumentsClassList, possible.getParameterTypes())) {
+ ctor = possible;
+ break;
+ }
+ }
+ }
+
+ if (ctor == null) {
+ throw new Exception(className + " Args: " + Arrays.toString(argTypes)); //$NON-NLS-1$
+ }
+
+ try {
+ return ctor.newInstance(ctorObjs);
+ } catch (Exception e) {
+ throw new Exception(e);
+ }
+ }
+
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnection.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnection.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnection.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,78 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.custom.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();
+ }
+
+ public Connection unwrap() throws ResourceException {
+ return this.mc.getConnection();
+ }
+
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnectionFactory.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnectionFactory.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/custom/spi/WrappedConnectionFactory.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -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.custom.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 BasicConnectionFactory delegate;
+ private ConnectionManager cm;
+ private BasicManagedConnectionFactory mcf;
+ private Reference reference;
+
+ public WrappedConnectionFactory(BasicConnectionFactory 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, null);
+ }
+
+
+ @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 (Connection)cm.allocateConnection(mcf, new ConnectionRequestInfoWrapper(arg0));
+ }
+
+ @Override
+ public ResourceAdapterMetaData getMetaData() throws ResourceException {
+ return this.delegate.getMetaData();
+ }
+
+ @Override
+ public RecordFactory getRecordFactory() throws ResourceException {
+ return this.delegate.getRecordFactory();
+ }
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanConnectionImpl.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanConnectionImpl.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanConnectionImpl.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,127 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.infinispan;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.resource.ResourceException;
+
+import org.infinispan.client.hotrod.RemoteCache;
+import org.teiid.resource.adapter.custom.spi.BasicConnection;
+import org.teiid.translator.object.ObjectCacheConnection;
+
+
+/**
+ * Represents an implementation of the connection to an Infinispan cache.
+ */
+public class InfinispanConnectionImpl extends BasicConnection implements ObjectCacheConnection {
+
+ private InfinispanManagedConnectionFactory config;
+
+ public InfinispanConnectionImpl(InfinispanManagedConnectionFactory config) throws ResourceException {
+ this.config = config;
+ }
+
+
+ /**
+ * Close the connection, if a connection requires closing.
+ * (non-Javadoc)
+ */
+ @Override
+ public void close() {
+ config = null;
+ }
+
+ /**
+ * 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)
+ */
+ public boolean isAlive() {
+ return (config == null ? false : config.getRemoteCacheManager().isStarted());
+ }
+
+ public List<Object> get(List<Object> args, String cacheName, Class<?> rootNodeType) throws Exception {
+
+ RemoteCache<Object, Object> cache = config.getRemoteCacheManager().getCache(cacheName);
+
+ List<Object> results = null;
+ if (args == null || args.size() == 0) {
+ Map<Object, Object> c = cache.getBulk();
+ results = new ArrayList<Object>();
+ for (Iterator it = c.keySet().iterator(); it.hasNext();) {
+ Object v = cache.get(it.next());
+ if (v != null && v.getClass().equals(rootNodeType)) {
+ addValue(v, results);
+ }
+ }
+
+ } else {
+ results = new ArrayList<Object>(args.size());
+ for (Iterator<Object> it=args.iterator(); it.hasNext();) {
+ Object arg = it.next();
+ Object v = cache.get(arg);
+ if (v != null && v.getClass().equals(rootNodeType)) {
+ addValue(v, results); }
+ }
+ }
+
+ return results;
+
+ }
+
+ private void addValue(Object value, List<Object> results) {
+ if (value.getClass().isArray()) {
+ List<Object> listRows = Arrays.asList((Object[]) value);
+ results.addAll(listRows);
+ return;
+ }
+
+ if (value instanceof Collection) {
+ results.addAll((Collection) value);
+ return;
+ }
+
+ if (value instanceof Map) {
+ Map<?,Object> mapRows = (Map) value;
+ results.addAll(mapRows.values());
+ return;
+ }
+
+ results.add(value);
+
+ }
+
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanManagedConnectionFactory.java
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanManagedConnectionFactory.java (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/java/org/teiid/resource/adapter/infinispan/InfinispanManagedConnectionFactory.java 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,94 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.infinispan;
+
+import javax.resource.ResourceException;
+
+import org.infinispan.client.hotrod.RemoteCacheManager;
+import org.teiid.resource.adapter.custom.spi.BasicConnectionFactory;
+import org.teiid.resource.adapter.custom.spi.BasicManagedConnectionFactory;
+
+public class InfinispanManagedConnectionFactory extends BasicManagedConnectionFactory {
+
+ private String remoteServerList;
+ private RemoteCacheManager cacheContainer;
+ private Object lock = new Object();
+
+ @Override
+ public BasicConnectionFactory createConnectionFactory() throws ResourceException {
+
+ synchronized(lock) {
+
+ this.cacheContainer = getOrCreateCacheContainer();
+ if (this.cacheContainer == null) {
+ throw new ResourceException("Unable to create Infinispan CacheContainer" );
+ }
+
+ }
+
+ return new BasicConnectionFactory() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public InfinispanConnectionImpl getConnection() throws ResourceException {
+ return new InfinispanConnectionImpl(InfinispanManagedConnectionFactory.this);
+ }
+ };
+ }
+
+
+ public String getRemoteServerList() {
+ return remoteServerList;
+ }
+
+ /**
+ * Set the list of remote servers that make up the Infinispan cluster. The servers must be Infinispan HotRod servers. The list
+ * must be in the appropriate format of <code>host:port[;host:port...]</code> that would be used when defining an Infinispan
+ * {@link RemoteCacheManager} instance. If the value is missing, <code>localhost:11311</code> is assumed.
+ *
+ * @param remoteInfinispanServerList the server list in appropriate <code>server:port;server2:port2</code> format.
+ */
+ public synchronized void setRemoteInfinispanServerList( String remoteInfinispanServerList ) {
+ if (this.remoteServerList == remoteInfinispanServerList || this.remoteServerList != null
+ && this.remoteServerList.equals(remoteInfinispanServerList)) return; // unchanged
+ this.remoteServerList = remoteInfinispanServerList;
+ }
+
+
+ protected RemoteCacheManager getRemoteCacheManager() {
+ return this.cacheContainer;
+ }
+ private RemoteCacheManager getOrCreateCacheContainer() {
+ if (this.cacheContainer != null) {
+ return this.cacheContainer;
+ }
+ if (getRemoteServerList() == null || getRemoteServerList().equals("")) {
+ return new RemoteCacheManager();
+ }
+ return new RemoteCacheManager(getRemoteServerList());
+
+ }
+
+
+
+}
Added: branches/7.7.x/connectors/connector-infinispan/src/main/rar/META-INF/ra.xml
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/rar/META-INF/ra.xml (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/rar/META-INF/ra.xml 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<connector version="1.5">
+
+ <vendor-name>Red Hat Middleware LLC</vendor-name>
+ <eis-type>Teiid Infinispan Connector</eis-type>
+ <resourceadapter-version>1.0</resourceadapter-version>
+ <license>
+ <description>
+ JBoss, Home of Professional Open Source.
+ Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ as indicated by the @author tags. See the copyright.txt file in the
+ distribution for a full listing of individual contributors.
+
+ This is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as
+ published by the Free Software Foundation; either version 2.1 of
+ the License, or (at your option) any later version.
+
+ This software is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this software; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ </description>
+ <license-required>true</license-required>
+ </license>
+ <resourceadapter>
+ <resourceadapter-class>org.teiid.resource.adapter.custom.spi.BasicResourceAdapter</resourceadapter-class>
+
+ <outbound-resourceadapter>
+ <connection-definition>
+ <managedconnectionfactory-class>org.teiid.resource.adapter.infinispan.InfinispanManagedConnectionFactory</managedconnectionfactory-class>
+
+ <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
+ <connectionfactory-impl-class>org.teiid.resource.adapter.custom.spi.WrappedConnectionFactory</connectionfactory-impl-class>
+ <connection-interface>javax.resource.cci.Connection</connection-interface>
+ <connection-impl-class>org.teiid.resource.adapter.custom.spi.WrappedConnection</connection-impl-class>
+
+ <!-- config-property>
+ <description>{$display:"Infinispan Server List",$description:"Infinispan Server List (host:port[;host:port...])",$required:"true"}</description>
+ <config-property-name>RemoteServerList</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>localhost:11311</config-property-value>
+ </config-property-->
+
+ </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: branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/infinispan/i18n.properties
===================================================================
--- branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/infinispan/i18n.properties (rev 0)
+++ branches/7.7.x/connectors/connector-infinispan/src/main/resources/org/teiid/resource/adapter/infinispan/i18n.properties 2012-05-07 17:53:08 UTC (rev 4065)
@@ -0,0 +1,21 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
12 years, 8 months
teiid SVN: r4064 - trunk/jboss-integration/src/main/java/org/teiid/jboss.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2012-05-07 13:52:05 -0400 (Mon, 07 May 2012)
New Revision: 4064
Modified:
trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDependencyDeployer.java
Log:
TEIID-2029: Adding the ability to specify multiple modules using "lib" property in the vdb.xml file, as well as ability to support JAR based deployments as modules. Also corrected this feature such that, user can add dependencies through both "lib" property and addition into VDB archive's "lib" folder.
Modified: trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDependencyDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDependencyDeployer.java 2012-05-07 17:50:58 UTC (rev 4063)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDependencyDeployer.java 2012-05-07 17:52:05 UTC (rev 4064)
@@ -23,19 +23,12 @@
import java.io.Closeable;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.List;
+import java.util.StringTokenizer;
-import org.jboss.as.server.deployment.Attachments;
-import org.jboss.as.server.deployment.DeploymentPhaseContext;
-import org.jboss.as.server.deployment.DeploymentUnit;
-import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
-import org.jboss.as.server.deployment.DeploymentUnitProcessor;
-import org.jboss.as.server.deployment.module.ModuleDependency;
-import org.jboss.as.server.deployment.module.ModuleRootMarker;
-import org.jboss.as.server.deployment.module.ModuleSpecification;
-import org.jboss.as.server.deployment.module.MountHandle;
-import org.jboss.as.server.deployment.module.ResourceRoot;
-import org.jboss.as.server.deployment.module.TempFileProviderService;
+import org.jboss.as.server.deployment.*;
+import org.jboss.as.server.deployment.module.*;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
@@ -58,20 +51,35 @@
return;
}
- String moduleName = null;
- if (TeiidAttachments.isDynamicVDB(deploymentUnit)) {
- final VDBMetaData deployment = deploymentUnit.getAttachment(TeiidAttachments.VDB_METADATA);
- ModuleLoader ml = Module.getCallerModuleLoader();
- moduleName = deployment.getPropertyValue("lib"); //$NON-NLS-1$
- if (moduleName != null && ml != null) {
- try {
- ml.loadModule(ModuleIdentifier.create(moduleName));
- } catch (ModuleLoadException e) {
- throw new DeploymentUnitProcessingException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50088, moduleName, deployment.getName(), deployment.getVersion(), e));
- }
- }
- }
- else {
+
+ final VDBMetaData deployment = deploymentUnit.getAttachment(TeiidAttachments.VDB_METADATA);
+ ArrayList<ModuleDependency> localDependencies = new ArrayList<ModuleDependency>();
+ ArrayList<ModuleDependency> userDependencies = new ArrayList<ModuleDependency>();
+ String moduleNames = deployment.getPropertyValue("lib"); //$NON-NLS-1$
+ if (moduleNames != null) {
+ StringTokenizer modules = new StringTokenizer(moduleNames);
+ while (modules.hasMoreTokens()) {
+ String moduleName = modules.nextToken().trim();
+ ModuleIdentifier lib = ModuleIdentifier.create(moduleName);
+ ModuleLoader moduleLoader = Module.getCallerModuleLoader();
+
+ try {
+ moduleLoader.loadModule(lib);
+ localDependencies.add(new ModuleDependency(moduleLoader, ModuleIdentifier.create(moduleName), false, false, false, false));
+ } catch (ModuleLoadException e) {
+ // this is to handle JAR based deployments which take on name like "deployment.<jar-name>"
+ moduleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
+ try {
+ moduleLoader.loadModule(lib);
+ userDependencies.add(new ModuleDependency(moduleLoader, ModuleIdentifier.create(moduleName), false, false, false, true));
+ } catch (ModuleLoadException e1) {
+ throw new DeploymentUnitProcessingException(IntegrationPlugin.Util.gs(IntegrationPlugin.Event.TEIID50088, moduleName, deployment.getName(), deployment.getVersion(), e1));
+ }
+ }
+ }
+ }
+
+ if (!TeiidAttachments.isDynamicVDB(deploymentUnit)) {
try {
final ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot();
@@ -105,9 +113,12 @@
moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, ModuleIdentifier.create("org.jboss.teiid.api"), false, false, false, false)); //$NON-NLS-1$
moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, ModuleIdentifier.create("org.jboss.teiid.common-core"), false, false, false, false)); //$NON-NLS-1$
moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, ModuleIdentifier.create("javax.api"), false, false, false, false)); //$NON-NLS-1$
- if (moduleName != null) {
- moduleSpecification.addLocalDependency(new ModuleDependency(moduleLoader, ModuleIdentifier.create(moduleName), false, false, false, false));
- }
+ if (!localDependencies.isEmpty()) {
+ moduleSpecification.addLocalDependencies(localDependencies);
+ }
+ if (!userDependencies.isEmpty()) {
+ moduleSpecification.addUserDependencies(userDependencies);
+ }
} catch (ModuleLoadException e) {
throw new DeploymentUnitProcessingException(IntegrationPlugin.Event.TEIID50018.name(), e);
}
12 years, 8 months
teiid SVN: r4063 - in branches/7.7.x/console/src/main: java/org/teiid/rhq/plugin and 1 other directories.
by teiid-commits@lists.jboss.org
Author: tejones
Date: 2012-05-07 13:50:58 -0400 (Mon, 07 May 2012)
New Revision: 4063
Modified:
branches/7.7.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
branches/7.7.x/console/src/main/resources/META-INF/rhq-plugin.xml
Log:
TEIID-1996: Added new operation to get query plan for an in-flight session/request.
Modified: branches/7.7.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java
===================================================================
--- branches/7.7.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java 2012-05-07 17:49:58 UTC (rev 4062)
+++ branches/7.7.x/console/src/main/java/org/teiid/rhq/admin/DQPManagementView.java 2012-05-07 17:50:58 UTC (rev 4063)
@@ -188,6 +188,7 @@
ExecutedResult operationResult, final String operationName,
final Map<String, Object> valueMap) throws Exception {
Collection<RequestMetadata> resultObject = new ArrayList<RequestMetadata>();
+ String value = new String();
Collection<SessionMetadata> activeSessionsCollection = new ArrayList<SessionMetadata>();
Collection<TransactionMetadata> transactionsCollection = new ArrayList<TransactionMetadata>();
@@ -210,6 +211,15 @@
MetaValue transactionMetaValue = getTransactions(connection);
getTransactionCollectionValue(transactionMetaValue,transactionsCollection);
operationResult.setContent(createReportResultList(fieldNameList, resultObject.iterator()));
+ } else if (operationName.equals(Platform.Operations.VIEW_QUERY_PLAN)) {
+ Long requestID = (Long) valueMap.get(Operation.Value.REQUEST_ID);
+ String sessionID = (String) valueMap.get(Operation.Value.SESSION_ID);
+ MetaValue[] args = new MetaValue[] {
+ SimpleValueSupport.wrap(sessionID),
+ SimpleValueSupport.wrap(requestID) };
+ MetaValue planMetaValue = getPlan(connection, args);
+ value = ProfileServiceUtil.stringValue(planMetaValue);
+ operationResult.setContent(value);
} else if (operationName.equals(Platform.Operations.KILL_TRANSACTION)) {
String transactionID = (String) valueMap.get(Operation.Value.TRANSACTION_ID);
MetaValue[] args = new MetaValue[] { SimpleValueSupport.wrap(transactionID) };
@@ -470,7 +480,24 @@
return transactionsCollection;
}
+
+ protected MetaValue getPlan(ProfileServiceConnection connection, MetaValue[] args) {
+ MetaValue planString = null;
+
+ try {
+ planString = executeManagedOperation(connection,
+ getRuntimeEngineDeployer(connection, mc),
+ Platform.Operations.VIEW_QUERY_PLAN, args);
+ } catch (Exception e) {
+ final String msg = "Exception executing operation: " + Platform.Operations.VIEW_QUERY_PLAN; //$NON-NLS-1$
+ LOG.error(msg, e);
+ }
+
+ return planString;
+
+ }
+
public MetaValue getSessions(ProfileServiceConnection connection) {
MetaValue sessionCollection = null;
Modified: branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
===================================================================
--- branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2012-05-07 17:49:58 UTC (rev 4062)
+++ branches/7.7.x/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2012-05-07 17:50:58 UTC (rev 4063)
@@ -94,10 +94,10 @@
protected void setOperationArguments(String name,
Configuration configuration, Map<String, Object> valueMap) {
// Parameter logic for System Operations
- if (name.equals(Platform.Operations.KILL_REQUEST)) {
+ if (name.equals(Platform.Operations.KILL_REQUEST) || name.equals(Platform.Operations.VIEW_QUERY_PLAN)) {
valueMap.put(Operation.Value.REQUEST_ID, configuration.getSimple(Operation.Value.REQUEST_ID).getLongValue());
valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getStringValue());
- } else if (name.equals(Platform.Operations.KILL_REQUEST)) {
+ } else if (name.equals(Platform.Operations.KILL_TRANSACTION)) {
valueMap.put(Operation.Value.TRANSACTION_ID, configuration.getSimple(Operation.Value.TRANSACTION_ID).getStringValue());
} else if (name.equals(Platform.Operations.KILL_SESSION)) {
valueMap.put(Operation.Value.SESSION_ID, configuration.getSimple(Operation.Value.SESSION_ID).getStringValue());
Modified: branches/7.7.x/console/src/main/resources/META-INF/rhq-plugin.xml
===================================================================
--- branches/7.7.x/console/src/main/resources/META-INF/rhq-plugin.xml 2012-05-07 17:49:58 UTC (rev 4062)
+++ branches/7.7.x/console/src/main/resources/META-INF/rhq-plugin.xml 2012-05-07 17:50:58 UTC (rev 4063)
@@ -164,15 +164,6 @@
</operation>
- <operation name="terminateSession" displayName="Terminate Session"
- description="Terminate a specified session">
- <parameters>
- <c:simple-property displayName="SessionID" name="sessionID"
- type="string" required="true" description="The ID of the session to terminate" />
- </parameters>
- </operation>
-
-
<operation name="getRequests" displayName="View current requests"
description="Get current requests executing against this Teiid instance">
<results>
@@ -212,6 +203,21 @@
type="long" required="true" description="The ID of the request to cancel" />
</parameters>
</operation>
+
+ <operation name="getPlan" displayName="View query plan"
+ description="Retrieves the query plan for an in-flight request">
+ <parameters>
+ <c:simple-property displayName="Session ID" name="sessionID"
+ type="string" required="true"
+ description="The ID of the session that the request to cancel is associated with" />
+ <c:simple-property displayName="Request ID" name="requestID"
+ type="long" required="true" description="The ID of the request to retrieve the query plan for" />
+ </parameters>
+ <results>
+ <c:simple-property displayName="Query Plan"
+ name="operationResults" type="longString" description="The query execution plan for the specified session/request." />
+ </results>
+ </operation>
<operation name="getTransactions" displayName="View current transactions"
description="Get current transactions executing against this VDB">
@@ -244,6 +250,14 @@
description="The ID of the transaction to terminate" />
</parameters>
</operation>
+
+ <operation name="terminateSession" displayName="Terminate Session"
+ description="Terminate a specified session">
+ <parameters>
+ <c:simple-property displayName="SessionID" name="sessionID"
+ type="string" required="true" description="The ID of the session to terminate" />
+ </parameters>
+ </operation>
<metric displayName="Query Count" defaultOn="true" displayType="detail"
category="throughput" property="queryCount"
12 years, 8 months
teiid SVN: r4062 - in branches/7.7.x/connectors/translator-object: src/main/java/org/teiid/translator/object and 10 other directories.
by teiid-commits@lists.jboss.org
Author: van.halbert
Date: 2012-05-07 13:49:58 -0400 (Mon, 07 May 2012)
New Revision: 4062
Added:
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectCacheConnection.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMetadataProcessor.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanObjectVisitor.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanProxy.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanRemoteExecutionFactory.java
branches/7.7.x/connectors/translator-object/src/main/resources/META-INF/
branches/7.7.x/connectors/translator-object/src/main/resources/META-INF/jboss-beans.xml
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/TradesCacheSource.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/VDBUtility.java
Removed:
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/TradesCacheSource.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/VDBUtility.java
Modified:
branches/7.7.x/connectors/translator-object/Notes.txt
branches/7.7.x/connectors/translator-object/pom.xml
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecution.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecutionFactory.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMethodManager.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectProjections.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectSourceProxy.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectTranslator.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheExecutionFactory.java
branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheProxy.java
branches/7.7.x/connectors/translator-object/src/main/resources/org/teiid/translator/object/i18n.properties
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecution.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecutionFactory.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectMethodManager.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectProjections.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectTranslator.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheIntegration.java
branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheVisitor.java
branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade.vdb
branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade_Object.xmi
Log:
TEIID-1992, 2014, 2015 ExecutionFactory supports importing metadata from non-annotated classes and support calling Infinispan
Modified: branches/7.7.x/connectors/translator-object/Notes.txt
===================================================================
--- branches/7.7.x/connectors/translator-object/Notes.txt 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/Notes.txt 2012-05-07 17:49:58 UTC (rev 4062)
@@ -12,10 +12,11 @@
1. There is no current support for 2 or more classes named the same (but different packages) in the same model.
The table name will be the name of the class, not the full classname.
+2. Default, columns that are of type object are NOT Selectable or Searchable. Its assumed that if object types like
+ Map, Collection, or Array, there needs to be a related child table that has a foreign key defined.
-
Modeling -
- JavaBean convention is used. The column name (or nameinsource if used) are used in finding the get/is method.
@@ -44,15 +45,21 @@
- Searchability=UNSEARCHABLE
- Selectable=false
- Updateable=false
- c. create the foreign key relationship between parent child, where the NameInSource for the FK being the method
- to access child objects.
+ c. create the foreign key relationship between parent child, where the NameInSource for the FK being the method
+ (minus the "get") to access child objects. Example: method - getLegs NIS - Legs
d. the attribute on an object that is the container object, should not be modeled as an attribute in the table.
This is because its not directly queryable. It should have a related child table, which has a foreign key
(see b and c above).
+
+
+- Reverse Engineering the Class Metadata by performing JDBC Import
+ - create a dynamic.vdb so that, in designer, you can do JDBC import using a Teiid connection, in order to reverse engineer
+ the class metadata.
+ - NOTE: The Native Type (i.e., the return type for the "Get" method) does not come thru in the metadata. The Datdatype and
+ the Native are set the same.
-
TODO:
- when importing metadata, make the Object types (of return types, collections, etc) non-selectable, because they need
Modified: branches/7.7.x/connectors/translator-object/pom.xml
===================================================================
--- branches/7.7.x/connectors/translator-object/pom.xml 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/pom.xml 2012-05-07 17:49:58 UTC (rev 4062)
@@ -13,7 +13,7 @@
<properties>
<version.infinispan>5.1.2.FINAL</version.infinispan>
<version.hibernate.search>4.1.0.CR1</version.hibernate.search>
- </properties>
+ </properties>
<dependencies>
<dependency>
@@ -43,20 +43,39 @@
<type>test-jar</type>
<scope>provided</scope>
</dependency>
-
+
+ <!-- dependency>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <artifactId>connector-infinispan</artifactId>
+ <classifier>lib</classifier>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency-->
+
+ <dependency>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-core</artifactId>
+ <version>${version.infinispan}</version>
+ </dependency>
+
+ <!-- dependency>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-core</artifactId>
+ <version>${version.infinispan}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.infinispan</groupId>
+ <artifactId>infinispan-client-hotrod</artifactId>
+ <version>${version.infinispan}</version>
+ </dependency-->
+
<!--
<dependency>
<groupId>org.infinispan</groupId>
- <artifactId>infinispan-core</artifactId>
- <version>${version.infinispan}</version>
- </dependency>
-
- <dependency>
- <groupId>org.infinispan</groupId>
<artifactId>infinispan-query</artifactId>
<version>${version.infinispan}</version>
</dependency>
- -->
+ -->
<dependency>
<groupId>org.hibernate</groupId>
Added: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectCacheConnection.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectCacheConnection.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectCacheConnection.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,14 @@
+package org.teiid.translator.object;
+
+import java.util.List;
+
+/**
+ * This is the interface the connection is exposed as.
+ * @author vhalbert
+ *
+ */
+public interface ObjectCacheConnection {
+
+ List<Object> get(List<Object> args, String cacheName, Class<?> rootNodeType) throws Exception ;
+
+}
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecution.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecution.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecution.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -44,13 +44,17 @@
private Select query;
private ObjectSourceProxy proxy;
private ObjectMethodManager methodManager;
+ private ObjectExecutionFactory config;
+ private ObjectProjections op;
private Iterator<List<Object>> resultsIt = null;
- public ObjectExecution(Command query, RuntimeMetadata metadata, ObjectSourceProxy connproxy, ObjectMethodManager methodManager) {
+ public ObjectExecution(Command query, RuntimeMetadata metadata, ObjectSourceProxy proxy, ObjectMethodManager methodManager, ObjectExecutionFactory factory) {
this.query = (Select) query;
- this.proxy = connproxy;
+ this.op = new ObjectProjections(this.query);
+ this.proxy = proxy;
this.methodManager = methodManager;
+ this.config = factory;
}
@Override
@@ -63,8 +67,6 @@
List<List<Object>> results = null;
if (objects != null && objects.size() > 0) {
LogManager.logDetail(LogConstants.CTX_CONNECTOR, "ObjectExecution number of objects from proxy is : " + objects.size()); //$NON-NLS-1$
-
- ObjectProjections op = new ObjectProjections(query);
results = ObjectTranslator.translateObjects(objects, op, methodManager);
@@ -85,7 +87,7 @@
LogManager.logDetail(LogConstants.CTX_CONNECTOR, "ObjectExecution calling proxy : " + this.proxy.getClass().getName()); //$NON-NLS-1$
- return this.proxy.get(query);
+ return this.proxy.get(query, config.getCacheName(), op.rootNodeClassName);
}
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecutionFactory.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecutionFactory.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectExecutionFactory.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -23,16 +23,21 @@
package org.teiid.translator.object;
import java.io.File;
-import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Enumeration;
import java.util.List;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import javax.resource.cci.ConnectionFactory;
+
+import org.teiid.core.util.StringUtil;
import org.teiid.language.QueryExpression;
import org.teiid.language.Select;
-import org.teiid.logging.LogConstants;
-import org.teiid.logging.LogManager;
import org.teiid.metadata.MetadataFactory;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.translator.ExecutionContext;
@@ -52,7 +57,7 @@
*
*/
-public abstract class ObjectExecutionFactory extends ExecutionFactory<Object, Object> {
+public abstract class ObjectExecutionFactory extends ExecutionFactory<ConnectionFactory, ObjectCacheConnection > {
public static final int MAX_SET_SIZE = 100;
/*
@@ -63,6 +68,9 @@
private boolean columnNameFirstLetterUpperCase = true;
private String packageNamesOfCachedObjects = null;
+ private String classNamesOfCachedObjects = null;
+ private String cacheName = null;
+ private String objectRelationShips = null;
public ObjectExecutionFactory() {
super();
@@ -82,13 +90,16 @@
@Override
public void start() throws TranslatorException {
+ super.start();
createObjectMethodManager();
+
}
@Override
- public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection)
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, ObjectCacheConnection connection)
throws TranslatorException {
- return new ObjectExecution((Select)command, metadata, createProxy(connection), objectMethods);
+ return new ObjectExecution((Select)command, metadata, createProxy(connection), objectMethods, this);
+
}
public List getSupportedFunctions() {
@@ -99,8 +110,50 @@
return true;
}
-
+
/**
+ * Get the cacheName that will be used by this factory instance to access the named cache.
+ * However, if not specified a default configuration will be created.
+ * @return
+ * @see #setCacheName(String)
+ */
+ @TranslatorProperty(display="CacheName", advanced=true)
+ public String getCacheName() {
+ return this.cacheName;
+ }
+
+ /**
+ * Set the cacheName that will be used to find the named cache.
+ * @param cacheName
+ * @see #getCacheName()
+ */
+
+ public void setCacheName(String cacheName) {
+ this.cacheName = cacheName;
+ }
+
+ /**
+ * Get the object relationships.
+ * @return
+ * @see #setObjectRelationships(String)
+ */
+ @TranslatorProperty(display="ObjectRelationShips", advanced=true)
+ public String getObjectRelationships() {
+ return this.objectRelationShips;
+ }
+
+ /**
+ * Set the object relationships so that the metadata relationships can be built. Specify the
+ * relationships using the format: <simple classname>.<getMethod>:<simple classname>
+ * @param cacheName
+ * @see #getObjectRelationships()
+ */
+
+ public void setObjectRelationships(String objectRelationships) {
+ this.objectRelationShips = objectRelationships;
+ }
+
+ /**
* <p>
* Returns a comma separated list of package names for the cached objects.
* </p>
@@ -120,6 +173,25 @@
public void setPackageNamesOfCachedObjects(String packageNamesOfCachedObjects) {
this.packageNamesOfCachedObjects = packageNamesOfCachedObjects;
}
+
+ /**
+ * Call to get a comma separated list of class names to use.
+ * @return
+ */
+ @TranslatorProperty(display="ClassNamesOfCachedObjects (CSV)", advanced=true)
+ public String getClassNamesOfCachedObjects() {
+ return this.classNamesOfCachedObjects;
+ }
+
+ /**
+ * <p>
+ * Call to set class names for the cached objects
+ * </p>
+ * @param String commo separated list of package names
+ */
+ public void setClassNamesOfCachedObjects(String classNamesOfCachedObjects) {
+ this.classNamesOfCachedObjects = classNamesOfCachedObjects;
+ }
/**
@@ -164,9 +236,11 @@
@Override
- public void getMetadata(MetadataFactory metadataFactory, Object conn)
+ public void getMetadata(MetadataFactory metadataFactory, ObjectCacheConnection conn)
throws TranslatorException {
-
+ createObjectMethodManager();
+ ObjectMetadataProcessor processor = new ObjectMetadataProcessor(metadataFactory, this);
+ processor.processMetadata();
}
@@ -182,58 +256,138 @@
* @return IObjectConnectionProxy
* @throws TranslatorException
*/
- protected abstract ObjectSourceProxy createProxy(Object connection) throws TranslatorException ;
+ protected abstract ObjectSourceProxy createProxy(ObjectCacheConnection connection) throws TranslatorException ;
protected void createObjectMethodManager() throws TranslatorException {
- if (objectMethods == null) {
- objectMethods = ObjectMethodManager.initialize(getClassesForPackage(this.packageNamesOfCachedObjects),
- isColumnNameFirstLetterUpperCase(), this.getClass().getClassLoader());
- }
+ if (objectMethods == null) {
+
+ List<String> classes = new ArrayList<String>();
+ if (this.classNamesOfCachedObjects != null) {
+ classes = StringUtil.split(this.classNamesOfCachedObjects, ",");
+
+ } else if (this.packageNamesOfCachedObjects != null && this.packageNamesOfCachedObjects.trim().length() > 0) {
+ List<String> packageNames = StringUtil.split(this.packageNamesOfCachedObjects, ",");
+
+ for (String packageName : packageNames) {
+ classes.addAll(getClassesInPackage(packageName, null));
+ }
+ }
+
+ objectMethods = ObjectMethodManager.initialize( classes, isColumnNameFirstLetterUpperCase(), this.getClass().getClassLoader());
+ }
}
-
- protected List<String> getClassesForPackage(String pkgname) throws TranslatorException {
- if (pkgname == null) return Collections.EMPTY_LIST;
- ArrayList<String> classes = new ArrayList<String>();
- // Get a File object for the package
- File directory = null;
- String fullPath;
- String relPath = pkgname.replace('.', '/');
- URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
- if (resource == null) {
- throw new TranslatorException(ObjectPlugin.Util
- .getString(
- "ObjectExecutionFactory.noResourceFound", new Object[] { relPath })); //$NON-NLS-1$
- }
- fullPath = resource.getFile();
+ /**
+ * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
+ * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files
+ *
+ * @param packageName The base package
+ * @param regexFilter an optional class name pattern.
+ * @return The classes
+ */
+ protected List<String> getClassesInPackage(String packageName, String regexFilter) throws TranslatorException{
+ if (packageName == null) return Collections.EMPTY_LIST;
- try {
- directory = new File(resource.toURI());
- } catch (URISyntaxException e) {
- throw new TranslatorException(ObjectPlugin.Util
- .getString(
- "ObjectExecutionFactory.invalidResource", new Object[] { pkgname, resource })); //$NON-NLS-1$
-
- } catch (IllegalArgumentException e) {
- directory = null;
- }
+ Pattern regex = null;
+ if (regexFilter != null)
+ regex = Pattern.compile(regexFilter);
- if (directory != null && directory.exists()) {
- // Get the list of the files contained in the package
- String[] files = directory.list();
- for (int i = 0; i < files.length; i++) {
- // we are only interested in .class files
- if (files[i].endsWith(".class") && !files[i].contains("$") ) {
- // removes the .class extension
- String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
- classes.add(className);
-
- LogManager.logDetail(LogConstants.CTX_CONNECTOR, "ClassDiscovery", className); //$NON-NLS-1$
+ try {
+ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+ assert classLoader != null;
+ String path = packageName.replace('.', '/');
+ Enumeration<URL> resources = classLoader.getResources(path);
+ List<String> dirs = new ArrayList<String>();
+ while (resources.hasMoreElements()) {
+ URL resource = resources.nextElement();
+ dirs.add(resource.getFile());
+ }
+ if (dirs.isEmpty()) {
+ classLoader = this.getClass().getClassLoader();
+ assert classLoader != null;
+ resources = classLoader.getResources(path);
+ while (resources.hasMoreElements()) {
+ URL resource = resources.nextElement();
+ dirs.add(resource.getFile());
+ }
+ if (dirs.isEmpty()) {
+ throw new TranslatorException(ObjectPlugin.Util
+ .getString(
+ "ObjectExecutionFactory.noResourceFound", new Object[] { packageName })); //$NON-NLS-1$
+ }
+
+ }
- }
- }
- }
- return classes;
+ TreeSet<String> classes = new TreeSet<String>();
+ for (String directory : dirs) {
+ classes.addAll(findClasses(directory, packageName, regex));
+ }
+ ArrayList<String> classNames = new ArrayList<String>();
+// ArrayList<Class> classList = new ArrayList<Class>();
+ for (String clazz : classes) {
+ classNames.add(clazz);
+ }
+// return classList.toArray(new Class[classes.size()]);
+//
+
+ return classNames;
+
+ } catch (TranslatorException te) {
+ throw te;
+ } catch (Exception e) {
+ e.printStackTrace();
+ throw new TranslatorException(e);
+ }
}
+ /**
+ * Recursive method used to find all classes in a given path (directory or zip file url). Directories
+ * are searched recursively. (zip files are
+ * Adapted from http://snippets.dzone.com/posts/show/4831 and extended to support use of JAR files
+ *
+ * @param path The base directory or url from which to search.
+ * @param packageName The package name for classes found inside the base directory
+ * @param regex an optional class name pattern. e.g. .*Test
+ * @return The classes
+ */
+ private static TreeSet<String> findClasses(String path, String packageName, Pattern regex) throws Exception {
+ TreeSet<String> classes = new TreeSet<String>();
+ if (path.startsWith("file:") && path.contains("!")) {
+
+ } else if (path.indexOf(".jar") > -1) {
+ int idx = path.indexOf(".jar") + 4;
+ path = "file:" + path.substring(0, idx) + "!" + path.substring(idx + 1) ;
+ }
+ if (path.startsWith("file:") && path.contains("!")) {
+ String[] split = path.split("!");
+ URL jar = new URL(split[0]);
+ ZipInputStream zip = new ZipInputStream(jar.openStream());
+ ZipEntry entry;
+ while ((entry = zip.getNextEntry()) != null) {
+ if (entry.getName().endsWith(".class")) {
+ String className = entry.getName().replaceAll("[$].*", "").replaceAll("[.]class", "").replace('/', '.');
+ if (className.startsWith(packageName) && (regex == null || regex.matcher(className).matches()))
+ classes.add(className);
+ }
+ }
+ }
+ File dir = new File(path);
+ if (!dir.exists()) {
+ return classes;
+ }
+ File[] files = dir.listFiles();
+ for (File file : files) {
+ if (file.isDirectory()) {
+ assert !file.getName().contains(".");
+ classes.addAll(findClasses(file.getAbsolutePath(), packageName + "." + file.getName(), regex));
+ } else if (file.getName().endsWith(".class")) {
+ String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
+ if (regex == null || regex.matcher(className).matches())
+ classes.add(className);
+ }
+ }
+ return classes;
+ }
+
+
}
Added: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMetadataProcessor.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMetadataProcessor.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMetadataProcessor.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,220 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.object;
+
+import java.lang.reflect.Method;
+import java.sql.Types;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.Table;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+
+
+/**
+ * Reads from {@link ObjectMethodManager} and creates metadata through the {@link MetadataFactory}.
+ */
+public class ObjectMetadataProcessor {
+
+
+ private boolean widenUnsingedTypes = true;
+ private Set<String> unsignedTypes = new HashSet<String>();
+ private MetadataFactory metadataFactory;
+ private ObjectExecutionFactory connectorEnv;
+
+ private Map<String, Table> tableMap = new HashMap<String, Table>();
+// private List<Relationship> relationships = new ArrayList<Relationship>();
+
+
+ public ObjectMetadataProcessor(MetadataFactory metadataFactory, ObjectExecutionFactory env) {
+ this.metadataFactory = metadataFactory;
+ this.connectorEnv = env;
+ }
+
+ public void processMetadata() throws TranslatorException {
+
+ ObjectMethodManager mgr = connectorEnv.getObjectMethodManager();
+
+ Iterator<String> cnIt = mgr.keySet().iterator();
+ while (cnIt.hasNext()) {
+ String className = (String) cnIt.next();
+
+ ObjectMethodManager.ClassMethods cm = mgr.getClassMethods(className);
+
+ addTable(cm);
+
+
+ }
+
+// addRelationships();
+ }
+
+
+ private void addTable(ObjectMethodManager.ClassMethods cm) throws TranslatorException {
+
+ if (cm == null || !cm.hasMethods()) {
+
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, ObjectPlugin.Util
+ .getString(
+ "ObjectExecutionFactory.missingClassMethods", new Object[] { cm.getClassIdentifier().getName() })); //$NON-NLS-1$
+
+ }
+
+ String className = cm.getClassName();
+ String tableName = getTableName(className);
+
+ Table table = metadataFactory.addTable(tableName);
+ table.setNameInSource(className);
+ table.setSupportsUpdate(false);
+ table.setAnnotation("Class: "+ className);
+
+ tableMap.put(tableName, table);
+// getRelationships(objectMetadata);
+
+ addColumns(cm, table);
+
+
+ }
+
+
+ private String getTableName(String className) {
+ String tableName = null;
+ int idx = className.lastIndexOf(".");
+ if (idx > 0) {
+ tableName = className.substring(idx + 1);
+ } else {
+ tableName = className;
+ }
+ return tableName;
+
+ }
+
+ private void addColumns(ObjectMethodManager.ClassMethods cm, Table table) throws TranslatorException {
+ Map<String, Method> methods = cm.getGetters();
+
+ Column column = null;
+ Iterator<String> mIts = methods.keySet().iterator();
+ while (mIts.hasNext()) {
+ String methodName = mIts.next();
+ Method m = methods.get(methodName);
+
+ methodName=methodName.substring( methodName.indexOf("get") + 3);
+
+ String runtimeType = getRuntimeType(m.getReturnType());
+
+ column = metadataFactory.addColumn(methodName, runtimeType, table);
+ String simpleName = m.getReturnType().getSimpleName();
+ column.setNativeType(simpleName);
+
+// String columnName = columns.getString(4);
+// int type = columns.getInt(5);
+// String typeName = columns.getString(6);
+// int columnSize = columns.getInt(7);
+// String runtimeType = getRuntimeType(type, typeName, columnSize);
+// //note that the resultset is already ordered by position, so we can rely on just adding columns in order
+// Column column = metadataFactory.addColumn(columnName, runtimeType, tableInfo.table);
+// column.setNameInSource(quoteName(columnName));
+// column.setPrecision(columnSize);
+// column.setLength(columnSize);
+// column.setNativeType(typeName);
+// column.setRadix(columns.getInt(10));
+// column.setNullType(NullType.values()[columns.getShort(11)]);
+// column.setUpdatable(true);
+// String remarks = columns.getString(12);
+// column.setAnnotation(remarks);
+// String defaultValue = columns.getString(13);
+// column.setDefaultValue(defaultValue);
+
+
+ if (runtimeType.equalsIgnoreCase("blob") || runtimeType.equalsIgnoreCase("clob") || runtimeType.equalsIgnoreCase("object")) {
+ column.setSearchType(SearchType.Unsearchable);
+ column.setSelectable(false);
+ }
+
+ if (runtimeType.equalsIgnoreCase("string")) {
+ column.setLength(4000);
+ }
+
+ }
+
+ methods = cm.getIses();
+
+ mIts = methods.keySet().iterator();
+ while (mIts.hasNext()) {
+ String methodName = mIts.next();
+ Method m = methods.get(methodName);
+
+ methodName=methodName.substring( methodName.indexOf("is") + 2);
+
+ String simpleName = m.getReturnType().getSimpleName();
+ String runtimeType = getRuntimeType(m.getReturnType());
+
+ column = metadataFactory.addColumn(methodName, runtimeType, table);
+
+ column.setNativeType(simpleName);
+
+ }
+ }
+
+
+ private String getRuntimeType(Class attributeType) {
+
+ Class datatypeClass = DataTypeManager.getDataTypeClass(attributeType.getSimpleName());
+
+ int sqlType = TypeFacility.getSQLTypeFromRuntimeType(datatypeClass);
+
+ sqlType = checkForUnsigned(sqlType, attributeType.getSimpleName());
+
+ return TypeFacility.getDataTypeNameFromSQLType( sqlType );
+ }
+
+
+
+ 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;
+ }
+
+}
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMethodManager.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMethodManager.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectMethodManager.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -26,7 +26,6 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -56,10 +55,17 @@
this.clz = clzz;
}
- String getClassName() {
+ public Class getClassIdentifier() {
+ return this.clz;
+ }
+ public String getClassName() {
return this.clz.getName();
}
+ public boolean hasMethods() {
+ return (!getters.isEmpty() || !is.isEmpty() || !setters.isEmpty());
+ }
+
public Map<String, Method> getGetters() {
return getters;
}
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectProjections.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectProjections.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectProjections.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -27,9 +27,12 @@
// this is the number of children deep this query is requesting information
protected int childrenDepth = -1; //
+ // this is the path of method calls to traverse the children
protected List<String> childrenNodes = null;
protected List<String> exceptionMessages = new ArrayList<String>(2);
+
+ protected String rootNodeClassName = null;
public ObjectProjections(Select query) {
@@ -50,26 +53,20 @@
@SuppressWarnings("unchecked")
private void parse(Select query) {
+ columns = getSelectableColumns(query);
+ columnNamesToUse = new String[columns.length];
+ nameNodes = new ArrayList[columns.length];
+ nodeDepth = new int[columns.length];
- Iterator<DerivedColumn> selectSymbolItr = query.getDerivedColumns().iterator();
-
- int s = query.getDerivedColumns().size();
- columns = new Column[s];
- columnNamesToUse = new String[s];
- nameNodes = new ArrayList[s];
- nodeDepth = new int[s];
-
String maxDepthColumnNameToUse = null;
- int i=0;
- while(selectSymbolItr.hasNext()) {
- columns[i] = getColumnFromSymbol(selectSymbolItr.next());
+ for (int i=0; i<columns.length; ++i) {
columnNamesToUse[i] = getColumnNameToUse(columns[i]);
nameNodes[i] = StringUtil.getTokens(columnNamesToUse[i], ".");
nodeDepth[i] = nameNodes[i].size() - 1; // if one node name, then depth is zero, and incremented from there
- // only when there are multiple node names will a container be involved
+ // only when there are multiple node names will a container/child be involved
if (nodeDepth[i] > 0) {
if (childrenDepth == -1) {
childrenDepth = nodeDepth[i];
@@ -91,11 +88,35 @@
}
}
- i++;
}
}
+ private Column[] getSelectableColumns(Select query) {
+ Column[] interimColumns = new Column[query.getDerivedColumns().size()];
+
+ Iterator<DerivedColumn> selectSymbolItr = query.getDerivedColumns().iterator();
+ int i=0;
+ while(selectSymbolItr.hasNext()) {
+ Column c = getColumnFromSymbol(selectSymbolItr.next());
+ if (!c.isSelectable()) continue;
+
+ interimColumns[i] = c;
+ ++i;
+ }
+
+ // if all columns are included, then return, no need to rebuild the array
+ if (interimColumns.length == i+1) {
+ return interimColumns;
+ }
+
+ Column[] columns = new Column[i];
+ for (int x=0; x<i; ++x) {
+ columns[x] = interimColumns[x];
+ }
+ return columns;
+
+ }
private void addException(String columnNameToUse1,
String columnNameToUse2, String table) {
@@ -154,6 +175,14 @@
return (parentNodeName != null ? parentNodeName + "." : "") + nis;
}
+ protected void setRootClassName(Table t) {
+ if (this.rootNodeClassName != null) return;
+
+ if (t.getNameInSource() != null) {
+ this.rootNodeClassName = t.getNameInSource();
+ }
+ }
+
protected String getNameInSourceFromColumn(Column c) {
String name = c.getNameInSource();
@@ -167,6 +196,8 @@
protected String getForeignKeyNodeName(Table t) {
if (t == null) return null;
+ setRootClassName(t);
+
if (t.getForeignKeys() != null && !t.getForeignKeys().isEmpty()) {
ForeignKey fk = (ForeignKey) t.getForeignKeys().get(0);
String fk_nis = fk.getNameInSource();
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectSourceProxy.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectSourceProxy.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectSourceProxy.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -28,15 +28,10 @@
/**
* <p>
- * ObjectSourceProxy interface is how the translator will ask for objects from the cache based on
- * the {@link Command}. The visitor will provide a parsed query such that the
- * the proxy implementor can use the criteria to perform vendor specific logic to obtain
- * objects from the cache.
+ * ObjectSourceProxy interface is implemented for a specific Object data source. That
+ * implementation will be responsible for adding its query logic for translating the
+ * {@link Command} into vendor specific syntax for querying the cache.
* </p>
- * <p>
- * The specific proxy implementation will be instantiated by {@link ObjectExecutionFactory}.
- * Passing in the connection object and ObjectExecutionFactory.
- * </P
*
* @author vhalbert
*
@@ -45,14 +40,17 @@
public interface ObjectSourceProxy {
/**
- * Called by {@link ObjectExecution}, passing in the sql <code>command</code>, to obtain the objects from
- * the cache based. The implementor will need to parse the command and interpret the criteria according
+ * Called by {@link ObjectExecution}, passing in the sql {@link Command command}, the cache to be
+ * queries and the <code>rootClassName</code> to identify the object type to be obtained from
+ * the cachee. The implementor will need to parse the command and interpret the criteria according
* to data source query syntax.
* @param command is the SELECT command to query the data source
+ * @param cacheName is the name of the cache to query
+ * @param rootClassName is the class type of the object in the cache
* @return List of objects found in the cache.
* @throws TranslatorException is thrown if there are issues querying the data source
*/
- List<Object> get(Command command) throws TranslatorException;
+ List<Object> get(Command command, String cacheName, String rootClassName) throws TranslatorException;
/**
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectTranslator.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectTranslator.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/ObjectTranslator.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -29,6 +29,10 @@
import java.util.List;
import java.util.Map;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
+import org.teiid.core.types.DataTypeManager.DefaultTypeCodes;
+import org.teiid.core.types.TransformationException;
import org.teiid.translator.TranslatorException;
/**
@@ -250,31 +254,65 @@
}
private static Object getValue(Object cachedObject, int columnIdx, int methodIdx, ObjectProjections projections, ObjectMethodManager objectManager) throws TranslatorException {
+ Object value = null;
-
// only the last parsed name can be where the boolean call can be made
// example: x.y.z z will be where "is" is called
// or x x could be where "is" is called
Class<?> clzType = projections.columns[columnIdx].getJavaType();
+
+ if (cachedObject.getClass().equals(clzType)) {
+ return cachedObject;
+ }
+ Class dataTypeClass = DataTypeManager.getDataTypeClass(cachedObject.getClass().getName());
- Object value = null;
-
- if (clzType != null && clzType == Boolean.class) {
- final String methodName = objectManager.formatMethodName(
- ObjectMethodManager.IS, projections.nameNodes[columnIdx].get(methodIdx) );
-
- value = objectManager.getIsValue(
- methodName, cachedObject);
+ // if the class is not a native type, but the POJO object, then
+ // call the method on the class to get the value
+ if (dataTypeClass == DefaultDataClasses.OBJECT) {
+ if (clzType != null && clzType == Boolean.class) {
+ final String methodName = objectManager.formatMethodName(
+ ObjectMethodManager.IS, projections.nameNodes[columnIdx].get(methodIdx) );
+
+ value = objectManager.getIsValue(
+ methodName, cachedObject);
+ } else {
+ final String methodName = objectManager.formatMethodName(
+ ObjectMethodManager.GET, projections.nameNodes[columnIdx].get(methodIdx) );
+
+ value = objectManager.getGetValue(
+ methodName, cachedObject);
+
+ }
} else {
- final String methodName = objectManager.formatMethodName(
- ObjectMethodManager.GET, projections.nameNodes[columnIdx].get(methodIdx) );
-
- value = objectManager.getGetValue(
- methodName, cachedObject);
-
- }
+ int datatype = DataTypeManager.getTypeCode(cachedObject.getClass());
+
+ switch (datatype) {
+ case DefaultTypeCodes.OBJECT:
+ case DefaultTypeCodes.CLOB:
+ case DefaultTypeCodes.BLOB:
+
+ break;
+
+ default:
+
+ try {
+ if (DataTypeManager.isTransformable(cachedObject.getClass(), clzType)) {
+ value = DataTypeManager.getTransform(cachedObject.getClass(), clzType).transform(cachedObject);
+ } else {
+ return cachedObject;
+ }
+ } catch (TransformationException e) {
+ // TODO Auto-generated catch block
+ throw new TranslatorException(e);
+ }
+
+ break;
+ }
+ }
+
+
return value;
}
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheExecutionFactory.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheExecutionFactory.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheExecutionFactory.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -25,16 +25,20 @@
import java.util.Collections;
import java.util.Map;
+import javax.resource.cci.ConnectionFactory;
+
+import org.teiid.translator.ExecutionFactory;
import org.teiid.translator.Translator;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.TranslatorProperty;
+import org.teiid.translator.object.ObjectCacheConnection;
import org.teiid.translator.object.ObjectExecutionFactory;
import org.teiid.translator.object.ObjectMethodManager;
import org.teiid.translator.object.ObjectSourceProxy;
import org.teiid.translator.object.util.ObjectMethodUtil;
@Translator(name="mapCacheExample", description="The Example Map Cache Factory")
-public class MapCacheExecutionFactory extends ObjectExecutionFactory {
+public class MapCacheExecutionFactory extends ObjectExecutionFactory {
private static final String LOADCACHE_METHOD_NAME = "loadCache";
private String cacheLoaderClassName = null;
@@ -98,7 +102,7 @@
}
@Override
- protected ObjectSourceProxy createProxy(Object connection)
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
throws TranslatorException {
return new MapCacheProxy(connection, this);
Modified: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheProxy.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheProxy.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/example/MapCacheProxy.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -22,6 +22,7 @@
package org.teiid.translator.object.example;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -31,12 +32,12 @@
public class MapCacheProxy implements ObjectSourceProxy {
private MapCacheObjectVisitor visitor = new MapCacheObjectVisitor();
- private Object connection;
+// private Object connection;
private MapCacheExecutionFactory factory;
public MapCacheProxy(Object connection, MapCacheExecutionFactory factory) {
- this.connection = connection;
+// this.connection = connection;
this.factory = factory;
}
@@ -47,7 +48,7 @@
@Override
- public List<Object> get(Command command) throws TranslatorException {
+ public List<Object> get(Command command, String cache, String rootClassName) throws TranslatorException {
visitor.visitNode(command);
List<Object> results = null;
@@ -55,17 +56,21 @@
results = new ArrayList<Object>(1);
results.add(getCache().get(visitor.value));
return results;
-
+ } else if (visitor.in) {
+ results = new ArrayList(visitor.parms.size());
+ for (Iterator it=visitor.parms.iterator(); it.hasNext();) {
+ results.add(getCache().get(it.next()));
+ }
+ return results;
+
} else {
results = new ArrayList<Object>();
results.addAll(getCache().values());
- return results;
-
+ return results;
}
}
-
@Override
public void close() {
Added: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanObjectVisitor.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanObjectVisitor.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanObjectVisitor.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,348 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.object.infinispan;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.language.AggregateFunction;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.In;
+import org.teiid.language.Like;
+import org.teiid.language.Literal;
+import org.teiid.language.ScalarSubquery;
+import org.teiid.language.SearchedCase;
+import org.teiid.language.visitor.HierarchyVisitor;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Table;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.object.ObjectPlugin;
+
+
+/**
+ * This is an example of extending ObjectVisitor, providing query access to a local Map object cache
+ */
+public class InfinispanObjectVisitor extends HierarchyVisitor {
+
+ protected TranslatorException exception;
+ public String tableName;
+ public String columnName;
+ public Object value;
+ public Class<?> classType;
+ public List<Object> parms;
+ public Operator op;
+
+ public boolean like = false;
+ public boolean compare = false;
+ public boolean in = false;
+
+ /**
+ *
+ */
+ public InfinispanObjectVisitor() {
+ super();
+ }
+
+
+
+ public List<Object> getKeyCriteria() {
+ // TODO Auto-generated method stub
+ if (parms != null) return parms;
+
+ if (value == null) return Collections.EMPTY_LIST;
+
+ List result = new ArrayList(1);
+ result.add(value);
+ return result;
+ }
+
+
+
+
+ public void addCompareCriteria(String tableName,
+ String columnName, Object value, Operator op,
+ Class<?> type) throws TranslatorException {
+ this.tableName = tableName;
+ this.columnName = columnName;
+ this.op = op;
+ this.value = value;
+ this.compare = true;
+ this.classType = type;
+ }
+
+ public void addLikeCriteria(String tableName,
+ String columnName, Object value)
+ throws TranslatorException {
+ this.tableName = tableName;
+ this.columnName = columnName;
+ this.value = value;
+ this.like = true;
+ }
+
+ public void addInCriteria(String tableName, String columnName,
+ List<Object> parms, Class<?> type)
+ throws TranslatorException {
+ this.tableName = tableName;
+ this.columnName = columnName;
+ this.parms = parms;
+ this.in = true;
+ this.classType = type;
+ }
+
+ public TranslatorException getException() {
+ return this.exception;
+ }
+
+
+ public void visit(Comparison obj) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing Comparison criteria."); //$NON-NLS-1$
+ try {
+
+ Comparison.Operator op = ((Comparison) obj).getOperator();
+
+ Expression lhs = ((Comparison) obj).getLeftExpression();
+ Expression rhs = ((Comparison) obj).getRightExpression();
+
+ // comparison between the ojbects is not usable, because the nameInSource and its parent(s)
+ // will be how the child objects are obtained
+ if (lhs instanceof ColumnReference && rhs instanceof ColumnReference) {
+ return;
+ }
+
+
+ String lhsString = getExpressionString(lhs);
+ String rhsString = getExpressionString(rhs);
+ if(lhsString == null || rhsString == null) {
+ final String msg = ObjectPlugin.Util.getString("ObjectVisitor.missingComparisonExpression"); //$NON-NLS-1$
+ exception = new TranslatorException(msg);
+ }
+
+ if (rhs instanceof Literal || lhs instanceof Literal) {
+ if(rhs instanceof Literal) {
+ Literal literal = (Literal) rhs;
+ String tableName = getTableNameFromColumnObject(lhs);
+ addCompareCriteria(tableName, lhsString, literal.getValue(), op, literal.getType());
+
+ } else {
+ Literal literal = (Literal) lhs;
+ String tableName = getTableNameFromColumnObject(rhs);
+ addCompareCriteria(tableName, rhsString, literal.getValue(), op, literal.getType());
+
+
+ }
+ }
+ }catch (TranslatorException t) {
+ exception = t;
+ }
+ }
+
+
+ public void visit(Like obj) {
+
+ 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 "*".
+ try {
+
+ Comparison.Operator op = Operator.EQ;
+ Expression lhs = ((Like) obj).getLeftExpression();
+ Expression rhs = ((Like) obj).getRightExpression();
+
+ String tableName = getTableNameFromColumnObject(lhs);
+ if (tableName == null) {
+ tableName = getTableNameFromColumnObject(rhs);
+ }
+
+ String lhsString = getExpressionString(lhs);
+ String rhsString = getExpressionString(rhs);
+
+ addLikeCriteria(tableName, lhsString, rhsString);
+
+ }catch (TranslatorException t) {
+ exception = t;
+ }
+ }
+
+
+ public void visit(In obj) {
+ LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing IN criteria."); //$NON-NLS-1$
+// isNegated = ((In) criteria).isNegated();
+ try {
+
+ Expression lhs = ((In)obj).getLeftExpression();
+
+ String tableName = getTableNameFromColumnObject(lhs);
+ String colName = getExpressionString(lhs);
+
+ List<Expression> rhsList = ((In)obj).getRightExpressions();
+
+ Class type = lhs.getType();
+ List parms = new ArrayList(rhsList.size());
+ Iterator iter = rhsList.iterator();
+ while(iter.hasNext()) {
+
+ Expression expr = (Expression) iter.next();
+ type = addParmFromExpression(expr, parms);
+
+ }
+ addInCriteria(tableName, colName, parms, type);
+
+ }catch (TranslatorException t) {
+ exception = t;
+ }
+
+ }
+
+ protected String getTableNameFromColumnObject(Object e) {
+ Column col = null;
+ if(e instanceof ColumnReference) {
+ col = ((ColumnReference)e).getMetadataObject();
+ } else if (e instanceof Column) {
+ col = (Column) e;
+ }
+
+ Object p = col.getParent();
+ if (p instanceof Table) {
+ Table t = (Table)p;
+ return t.getName();
+ }
+
+ return null;
+
+ }
+
+ protected Class addParmFromExpression(Expression expr, List parms ) {
+ Class type = null;
+ if(expr instanceof Literal) {
+ Long longparm = null;
+ Literal literal = (Literal) expr;
+
+ parms.add(literal);
+
+ type = literal.getType();
+
+ } else {
+ this.exception = new TranslatorException("ObjectVisitor.Unsupported_expression" + expr); //$NON-NLS-1$
+ }
+
+ return type;
+
+ }
+
+
+ // 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 TranslatorException {
+ 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 = getNameInSourceFromColumn(mdIDElement);
+// 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();
+// }
+
+ expressionName = ((Literal)e).getValue().toString();
+// } catch (ClassNotFoundException cce) {
+// final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.timestampClassNotFoundError"); //$NON-NLS-1$
+// throw new TranslatorException(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 = ObjectPlugin.Util.getString("ObjectVisitor.unsupportedElementError" , e.toString()); //$NON-NLS-1$
+ throw new TranslatorException(msg);
+ }
+ expressionName = escapeReservedChars(expressionName);
+ return expressionName;
+ }
+
+ protected String getNameInSourceFromColumn(Column c) {
+ String name = c.getNameInSource();
+ if(name == null || name.equals("")) { //$NON-NLS-1$
+ return c.getName();
+ }
+ return name;
+ }
+
+ protected static String escapeReservedChars(final 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();
+ }
+
+}
Added: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanProxy.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanProxy.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanProxy.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,86 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.object.infinispan;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.core.BundleUtil;
+import org.teiid.language.Command;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.object.ObjectCacheConnection;
+import org.teiid.translator.object.ObjectSourceProxy;
+
+/**
+ * Represents an implementation for the connection to an Infinispan local cache data source.
+ */
+public class InfinispanProxy implements ObjectSourceProxy {
+
+ public static final BundleUtil UTIL = BundleUtil.getBundleUtil(InfinispanProxy.class);
+
+ private InfinispanObjectVisitor visitor = new InfinispanObjectVisitor();
+ private InfinispanRemoteExecutionFactory factory;
+ private ObjectCacheConnection connection;
+
+ public InfinispanProxy(ObjectCacheConnection connection, InfinispanRemoteExecutionFactory factory) {
+ this.factory = factory;
+ this.connection = connection;
+ }
+
+
+ @Override
+ public void close() {
+ this.visitor = null;
+ this.factory = null;
+ }
+
+
+ @Override
+ public List<Object> get(Command command, String cache, String rootClassName) throws TranslatorException {
+ visitor.visitNode(command);
+
+ Class<?> rootClass = null;
+ if (this.factory.getObjectMethodManager().getClassMethods(rootClassName) == null) {
+ rootClass = this.factory.getObjectMethodManager().loadClassByName(rootClassName, null);
+ } else {
+ rootClass = this.factory.getObjectMethodManager().getClassMethods(rootClassName).getClassIdentifier();
+ }
+ try {
+ return connection.get(visitor.getKeyCriteria(), cache, rootClass);
+ } catch (Exception e) {
+ throw new TranslatorException(e.getMessage());
+ }
+
+ }
+
+ public String formatColumnName(String columnName) {
+ if (factory.isColumnNameFirstLetterUpperCase()) return columnName;
+
+ return columnName.substring(0, 1).toLowerCase() + columnName.substring(1);
+ }
+
+}
Added: branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanRemoteExecutionFactory.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanRemoteExecutionFactory.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/java/org/teiid/translator/object/infinispan/InfinispanRemoteExecutionFactory.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,30 @@
+package org.teiid.translator.object.infinispan;
+
+
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.object.ObjectCacheConnection;
+import org.teiid.translator.object.ObjectExecutionFactory;
+import org.teiid.translator.object.ObjectSourceProxy;
+
+@Translator(name="infinispanRemote", description="The Execution Factory for Remote Infinispan Cache")
+public class InfinispanRemoteExecutionFactory extends ObjectExecutionFactory {
+
+ public InfinispanRemoteExecutionFactory() {
+ super();
+ }
+
+ @Override
+ public void start() throws TranslatorException {
+ super.start();
+
+ }
+
+
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
+ throws TranslatorException {
+ return new InfinispanProxy(connection, this);
+ }
+
+
+}
Added: branches/7.7.x/connectors/translator-object/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/main/resources/META-INF/jboss-beans.xml 2012-05-07 17:49:58 UTC (rev 4062)
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="translator-infinispanRemote-template" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="translator-infinispanRemote"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="translator-infinispanRemote" 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.translator.object.infinispan.InfinispanRemoteExecutionFactory</parameter>
+ <parameter class="java.lang.String">translator-infinispanRemote</parameter>
+ <parameter class="java.lang.String">infinispanRemote</parameter>
+ </constructor>
+ </bean>
+
+ <bean name="translator-mapCacheExample-template" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="translator-mapCacheExample"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="translator-mapCacheExample" 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.translator.object.example.MapCacheExecutionFactory</parameter>
+ <parameter class="java.lang.String">translator-mapCacheExample</parameter>
+ <parameter class="java.lang.String">mapCacheExample</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Modified: branches/7.7.x/connectors/translator-object/src/main/resources/org/teiid/translator/object/i18n.properties
===================================================================
--- branches/7.7.x/connectors/translator-object/src/main/resources/org/teiid/translator/object/i18n.properties 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/main/resources/org/teiid/translator/object/i18n.properties 2012-05-07 17:49:58 UTC (rev 4062)
@@ -20,14 +20,14 @@
# 02110-1301 USA.
#
-ObjectExecutionFactory.noResourceFound=Unable to discover class, no resource found for {0}
+ObjectExecutionFactory.noResourceFound=Unable to discover class, no resource found for package {0}
ObjectExecutionFactory.invalidResource={0} ( {1} ) does not appear to be a valid URL / URI.
+ObjectExecutionFactory.missingClassMethods=Missing class methods for className {0}, ensure class has 'getMethod' or 'isMethod' defined
ObjectMethodManager.noMethodFound=Method {0} was not found for class {1}
ObjectMethodManager.objectClassNotFound=Class {0} not found to load
ObjectProjections.unsupportedMultipleContainers=Query Error: multiple collections found between columns {0} and {1} (table: {2})
-ObjectVisitor.missingComparisonExpression=Missing either left or right expression in comparison
-ObjectVisitor.Unsupported_expressionr=Unsupported element {0}
-
+InfinispanRemoteExecutionFactory.cacheNameNotSet=CacheName property has not been set
+InfinispanRemoteExecutionFactory.cacheDoesNotExist=The cache {0} does not exist in the RemoteInfinispanCache
\ No newline at end of file
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecution.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecution.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecution.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -32,17 +32,49 @@
import org.teiid.language.Select;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.TranslatorException;
-import org.teiid.translator.object.testdata.TradesCacheSource;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.util.TradesCacheSource;
+import org.teiid.translator.object.util.VDBUtility;
@SuppressWarnings("nls")
public class TestObjectExecution {
private static TradesCacheSource source;
+ private static ObjectExecutionFactory factory;
+ private static ExecutionContext context;
+
@BeforeClass
public static void beforeEach() throws Exception {
source = TradesCacheSource.loadCache();
+
+ context = Mockito.mock(ExecutionContext.class);
+
+ factory = new ObjectExecutionFactory() {
+
+ @Override
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
+ throws TranslatorException {
+
+ return new ObjectSourceProxy() {
+
+ @Override
+ public List<Object> get(Command command, String cacheName, String className) throws TranslatorException {
+ return source.getAll();
+ }
+
+ @Override
+ public void close() {
+
+ }
+
+ };
+ }
+
+ };
+
+ factory.start();
+
+
}
@@ -98,34 +130,7 @@
private ObjectExecution createExecution(String sql) throws Exception {
Select command = (Select)VDBUtility.TRANSLATION_UTILITY.parseCommand(sql); //$NON-NLS-1$
-
- ExecutionContext context = Mockito.mock(ExecutionContext.class);
-
- final ObjectExecutionFactory factory = new ObjectExecutionFactory() {
-
- @Override
- protected ObjectSourceProxy createProxy(Object connection)
- throws TranslatorException {
-
- return new ObjectSourceProxy() {
-
- @Override
- public List<Object> get(Command command) throws TranslatorException {
- return source.getAll();
- }
-
- @Override
- public void close() {
-
- }
-
- };
- }
-
- };
- factory.start();
-
ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, null);
return exec;
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecutionFactory.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecutionFactory.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectExecutionFactory.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -21,21 +21,27 @@
*/
package org.teiid.translator.object;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertEquals;
-import java.io.File;
+import java.util.*;
+
+
import org.junit.Test;
import org.mockito.Mockito;
-import org.teiid.core.util.UnitTestUtil;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
import org.teiid.language.Select;
+import org.teiid.metadata.Datatype;
+import org.teiid.metadata.MetadataFactory;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.TranslatorException;
-import org.teiid.translator.object.ObjectExecution;
-import org.teiid.translator.object.ObjectExecutionFactory;
-import org.teiid.translator.object.ObjectSourceProxy;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.util.VDBUtility;
@SuppressWarnings("nls")
public class TestObjectExecutionFactory {
@@ -51,7 +57,7 @@
ObjectExecutionFactory factory = new ObjectExecutionFactory() {
@Override
- protected ObjectSourceProxy createProxy(Object connection)
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
throws TranslatorException {
return proxy;
@@ -72,12 +78,7 @@
}
@Test public void testFactoryLoadingJarClassNames() throws Exception {
-
- // File testjar = new File(UnitTestUtil.getTestScratchPath() + "/../" + "translator-object-7.7.1-tests.jar");
-// File testjar = new File("target/" + "translator-object-7.7.1-tests.jar");
-
-// assertEquals("Testjar doesn't exist " + testjar.getAbsolutePath(), true, testjar.exists());
-
+
Select command = Mockito.mock(Select.class);
@@ -88,7 +89,7 @@
ObjectExecutionFactory factory = new ObjectExecutionFactory() {
@Override
- protected ObjectSourceProxy createProxy(Object connection)
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
throws TranslatorException {
return proxy;
@@ -97,7 +98,6 @@
};
factory.setColumnNameFirstLetterUpperCase(false);
-
factory.setPackageNamesOfCachedObjects("org.teiid.translator.object.testdata");
factory.start();
@@ -110,6 +110,38 @@
}
+ @Test public void testGetMetadata() throws Exception {
+
+ Collection dts = VDBMetadataFactory.getSystem().getDatatypes();
+ Map<String, Datatype> mapTypes = new HashMap<String, Datatype>();
+ for (Iterator it= dts.iterator(); it.hasNext();) {
+ Datatype dt = (Datatype) it.next();
+ mapTypes.put(dt.getName() , dt);
+ }
+
+ MetadataFactory mfactory = new MetadataFactory("testModel", mapTypes, new Properties());
+
+ final ObjectSourceProxy proxy = Mockito.mock(ObjectSourceProxy.class);
+
+ ObjectExecutionFactory factory = new ObjectExecutionFactory() {
-
+ @Override
+ protected ObjectSourceProxy createProxy(ObjectCacheConnection connection)
+ throws TranslatorException {
+
+ return proxy;
+ }
+
+ };
+
+ factory.setColumnNameFirstLetterUpperCase(false);
+
+ factory.setPackageNamesOfCachedObjects("org.teiid.translator.object.testdata");
+
+ factory.start();
+
+ factory.getMetadata(mfactory, null);
+
+ }
+
}
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectMethodManager.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectMethodManager.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectMethodManager.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -25,10 +25,12 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import java.util.ArrayList;
+import java.util.List;
+
import javax.transaction.Transaction;
import org.junit.Test;
-import org.teiid.translator.object.ObjectMethodManager;
import org.teiid.translator.object.testdata.Leg;
import org.teiid.translator.object.testdata.Trade;
@@ -80,5 +82,28 @@
// assertNotNull(omm.findGetterMethod(Transaction.class, "getLineItem"));
}
+
+ @Test public void testInitializationLoadingListOfClasses() throws Exception {
+
+ List<String> classNames = new ArrayList(3);
+ classNames.add(Trade.class.getName());
+ classNames.add(Leg.class.getName());
+ classNames.add(Transaction.class.getName());
+
+
+
+ ObjectMethodManager omm = ObjectMethodManager.initialize(classNames,
+ true, this.getClass().getClassLoader());
+
+ // should not fail
+ assertEquals(omm.size(), 3);
+ assertNotNull(omm.getClassMethods(Trade.class.getName()));
+ assertNotNull(omm.getClassMethods(Leg.class.getName()));
+ assertNotNull(omm.getClassMethods(Transaction.class.getName()));
+ assertNotNull(omm.findGetterMethod(Trade.class, "getName"));
+ assertNotNull(omm.findGetterMethod(Leg.class, "getName"));
+// assertNotNull(omm.findGetterMethod(Transaction.class, "getLineItem"));
+
+ }
}
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectProjections.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectProjections.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectProjections.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -25,7 +25,8 @@
import org.junit.Test;
import org.teiid.language.Select;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.testdata.Trade;
+import org.teiid.translator.object.util.VDBUtility;
@SuppressWarnings("nls")
public class TestObjectProjections {
@@ -36,7 +37,7 @@
ObjectProjections op = new ObjectProjections(command);
- validateArrays(4, op);
+ validateResults(4, 0, op);
}
@@ -45,7 +46,7 @@
Select command = (Select)VDBUtility.TRANSLATION_UTILITY.parseCommand("select T.TradeId, T.Name as TradeName, L.Name as LegName From Trade_Object.Trade as T, Trade_Object.Leg as L Where T.TradeId = L.TradeId"); //$NON-NLS-1$
ObjectProjections op = new ObjectProjections(command);
- validateArrays(3, op);
+ validateResults(3, 1, op);
}
@Test public void testQueryGetAllTransactions() throws Exception {
@@ -54,17 +55,27 @@
" From Trade_Object.Trade as T, Trade_Object.Leg as L, Trade_Object.Transaction as N " +
" Where T.TradeId = L.TradeId and L.LegId = N.LegId"); //$NON-NLS-1$
ObjectProjections op = new ObjectProjections(command);
- validateArrays(4, op);
+ validateResults(4, 2, op);
}
- private void validateArrays(int size, ObjectProjections op) throws Exception {
+ private void validateResults(int size, int depth, ObjectProjections op) throws Exception {
op.throwExceptionIfFound();
+ assertEquals(Trade.class.getName(), op.rootNodeClassName);
assertEquals(size, op.getColumnNamesToUse().length);
assertEquals(size, op.getColumns().length);
+ int d = (op.childrenDepth > -1 ? op.childrenDepth : 0 );
+
+ assertEquals(depth, d);
+
+ //if children, then there should always be one more child node than the depth
+ assertEquals(depth, (op.childrenNodes == null ? 0 : op.childrenNodes.size() - 1) );
+ assertEquals(size, op.nameNodes.length);
+ assertEquals(size, op.nodeDepth.length);
+
// confirm the arrays match
for (int i = 0; i < op.getColumns().length; i++) {
assertEquals(op.getColumnNamesToUse()[i], op.getColumnNameToUse(op.getColumns()[i]));
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectTranslator.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectTranslator.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/TestObjectTranslator.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -28,8 +28,8 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.teiid.language.Select;
-import org.teiid.translator.object.testdata.TradesCacheSource;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.util.TradesCacheSource;
+import org.teiid.translator.object.util.VDBUtility;
@SuppressWarnings("nls")
public class TestObjectTranslator {
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheIntegration.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheIntegration.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheIntegration.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -31,10 +31,12 @@
import org.teiid.language.Select;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.object.BaseObjectTest;
+import org.teiid.translator.object.ObjectCacheConnection;
import org.teiid.translator.object.ObjectExecution;
import org.teiid.translator.object.example.MapCacheExecutionFactory;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.util.VDBUtility;
+
@SuppressWarnings("nls")
public class TestMapCacheIntegration extends BaseObjectTest {
@@ -44,12 +46,14 @@
Select command = (Select)VDBUtility.TRANSLATION_UTILITY.parseCommand("select T.TradeId, T.Name as TradeName, L.Name as LegName From Trade_Object.Trade as T, Trade_Object.Leg as L Where T.TradeId = L.TradeId"); //$NON-NLS-1$
ExecutionContext context = Mockito.mock(ExecutionContext.class);
+
+ ObjectCacheConnection connection = Mockito.mock(ObjectCacheConnection.class);
MapCacheExecutionFactory factory = new MapCacheExecutionFactory();
- factory.setCacheLoaderClassName("org.teiid.translator.object.testdata.TradesCacheSource");
+ factory.setCacheLoaderClassName("org.teiid.translator.object.util.TradesCacheSource");
factory.start();
- ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, new Object());
+ ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, connection);
exec.execute();
@@ -77,12 +81,13 @@
Select command = (Select)VDBUtility.TRANSLATION_UTILITY.parseCommand("select * From Trade_Object.Trade"); //$NON-NLS-1$
ExecutionContext context = Mockito.mock(ExecutionContext.class);
-
+ ObjectCacheConnection connection = Mockito.mock(ObjectCacheConnection.class);
+
MapCacheExecutionFactory factory = new MapCacheExecutionFactory();
factory.setCacheLoaderClassName("org.teiid.translator.object.testdata.TradesCacheSource");
factory.start();
- ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, new Object());
+ ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, connection);
exec.execute();
@@ -110,12 +115,13 @@
Select command = (Select)VDBUtility.TRANSLATION_UTILITY.parseCommand("select * From Trade_Object.Transaction"); //$NON-NLS-1$
ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ ObjectCacheConnection connection = Mockito.mock(ObjectCacheConnection.class);
MapCacheExecutionFactory factory = new MapCacheExecutionFactory();
factory.setCacheLoaderClassName("org.teiid.translator.object.testdata.TradesCacheSource");
factory.start();
- ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, new Object());
+ ObjectExecution exec = (ObjectExecution) factory.createExecution(command, context, VDBUtility.RUNTIME_METADATA, connection);
exec.execute();
Modified: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheVisitor.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheVisitor.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/example/TestMapCacheVisitor.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -35,7 +35,7 @@
import org.teiid.translator.TranslatorException;
import org.teiid.translator.object.ObjectProjections;
import org.teiid.translator.object.testdata.Trade;
-import org.teiid.translator.object.testdata.VDBUtility;
+import org.teiid.translator.object.util.VDBUtility;
@SuppressWarnings("nls")
Deleted: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/TradesCacheSource.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/TradesCacheSource.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/TradesCacheSource.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -1,107 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.translator.object.testdata;
-
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-
-/**
- * Sample cache of objects
- *
- * @author vhalbert
- *
- */
-@SuppressWarnings("rawtypes")
-public class TradesCacheSource extends HashMap <Object, Object> {
-
- /**
- *
- */
- private static final long serialVersionUID = -727553658250070494L;
-
-
- public static final String TRADE_CLASS_NAME = Trade.class.getName();
- public static final String LEG_CLASS_NAME = Leg.class.getName();
- public static final String TRANSACTION_CLASS_NAME = Transaction.class.getName();
-
-
- public static final int NUMLEGS = 10;
- public static final int NUMTRADES = 3;
- public static final int NUMTRANSACTIONS = 5;
-
-
- public static void loadCache(Map<Object, Object> cache) {
- for (int i = 1; i <= NUMTRADES; i++) {
-
- Map legsMap = new HashMap();
- double d = 0;
- for (int j = 1; j <= NUMLEGS; j++) {
-
- Leg leg = new Leg(j, "LegName " + j, d * j * 3.14, Calendar.getInstance());
-
- List trans = new ArrayList(NUMTRANSACTIONS);
- for (int x = 1; x <= NUMTRANSACTIONS; x++) {
- Transaction t = new Transaction();
- t.setLineItem("Leg " + j + ", transaction line item " + x);
- trans.add(t);
- }
-
- leg.setTransations(trans);
- leg.setNotational(i * 7 / 3.14);
-
- legsMap.put(j, leg);
- }
-
- Trade trade = new Trade(i, "TradeName " + i, legsMap, new Date());
-
- // even trades set settled to true
- if ( i % 2 == 0) {
- trade.setSettled(true);
- }
-
- cache.put(i, trade);
-
- }
- }
-
- public static TradesCacheSource loadCache() {
- TradesCacheSource tcs = new TradesCacheSource();
- loadCache(tcs);
- return tcs;
- }
-
- public List<Object> getAll() {
- return new ArrayList<Object>(this.values());
- }
-
- public List<Object> get(int key) {
- List<Object> objs = new ArrayList<Object>(1);
- objs.add(this.get(key));
- return objs;
- }
-}
Deleted: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/VDBUtility.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/VDBUtility.java 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/testdata/VDBUtility.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -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 org.teiid.translator.object.testdata;
-
-import java.io.File;
-
-import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.metadata.RuntimeMetadata;
-
-
-public class VDBUtility {
-
- public static TranslationUtility TRANSLATION_UTILITY = null;
-
- public static RuntimeMetadata RUNTIME_METADATA = null;
-
- static {
- File f = new File(UnitTestUtil.getTestDataPath() + "/ObjectProject/Trade.vdb");
- System.out.println("TestDataPath " + f.getAbsolutePath());
- try {
- TRANSLATION_UTILITY = new TranslationUtility(f.toURI().toURL());
- } catch (Throwable e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- throw new RuntimeException(e);
- }
-
- RUNTIME_METADATA = VDBUtility.TRANSLATION_UTILITY.createRuntimeMetadata();
- }
-
-
-}
Added: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/TradesCacheSource.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/TradesCacheSource.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/TradesCacheSource.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -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.object.util;
+
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.translator.object.testdata.Leg;
+import org.teiid.translator.object.testdata.Trade;
+import org.teiid.translator.object.testdata.Transaction;
+
+
+/**
+ * Sample cache of objects
+ *
+ * @author vhalbert
+ *
+ */
+@SuppressWarnings("rawtypes")
+public class TradesCacheSource extends HashMap <Object, Object> {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -727553658250070494L;
+
+
+ public static final String TRADE_CLASS_NAME = Trade.class.getName();
+ public static final String LEG_CLASS_NAME = Leg.class.getName();
+ public static final String TRANSACTION_CLASS_NAME = Transaction.class.getName();
+
+
+ public static final int NUMLEGS = 10;
+ public static final int NUMTRADES = 3;
+ public static final int NUMTRANSACTIONS = 5;
+
+
+ public static void loadCache(Map<Object, Object> cache) {
+ for (int i = 1; i <= NUMTRADES; i++) {
+
+ Map legsMap = new HashMap();
+ double d = 0;
+ for (int j = 1; j <= NUMLEGS; j++) {
+
+ Leg leg = new Leg(j, "LegName " + j, d * j * 3.14, Calendar.getInstance());
+
+ List trans = new ArrayList(NUMTRANSACTIONS);
+ for (int x = 1; x <= NUMTRANSACTIONS; x++) {
+ Transaction t = new Transaction();
+ t.setLineItem("Leg " + j + ", transaction line item " + x);
+ trans.add(t);
+ }
+
+ leg.setTransations(trans);
+ leg.setNotational(i * 7 / 3.14);
+
+ legsMap.put(j, leg);
+ }
+
+ Trade trade = new Trade(i, "TradeName " + i, legsMap, new Date());
+
+ // even trades set settled to true
+ if ( i % 2 == 0) {
+ trade.setSettled(true);
+ }
+
+ cache.put(i, trade);
+
+ }
+ }
+
+ public static TradesCacheSource loadCache() {
+ TradesCacheSource tcs = new TradesCacheSource();
+ loadCache(tcs);
+ return tcs;
+ }
+
+ public List<Object> getAll() {
+ return new ArrayList<Object>(this.values());
+ }
+
+ public List<Object> get(int key) {
+ List<Object> objs = new ArrayList<Object>(1);
+ objs.add(this.get(key));
+ return objs;
+ }
+}
Added: branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/VDBUtility.java
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/VDBUtility.java (rev 0)
+++ branches/7.7.x/connectors/translator-object/src/test/java/org/teiid/translator/object/util/VDBUtility.java 2012-05-07 17:49:58 UTC (rev 4062)
@@ -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.object.util;
+
+import java.io.File;
+
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.metadata.RuntimeMetadata;
+
+
+public class VDBUtility {
+
+ public static TranslationUtility TRANSLATION_UTILITY = null;
+
+ public static RuntimeMetadata RUNTIME_METADATA = null;
+
+ static {
+ File f = new File(UnitTestUtil.getTestDataPath() + "/ObjectProject/Trade.vdb");
+ System.out.println("TestDataPath " + f.getAbsolutePath());
+ try {
+ TRANSLATION_UTILITY = new TranslationUtility(f.toURI().toURL());
+ } catch (Throwable e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+
+ RUNTIME_METADATA = VDBUtility.TRANSLATION_UTILITY.createRuntimeMetadata();
+ }
+
+
+}
Modified: branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade.vdb
===================================================================
(Binary files differ)
Modified: branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade_Object.xmi
===================================================================
--- branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade_Object.xmi 2012-05-07 17:48:51 UTC (rev 4061)
+++ branches/7.7.x/connectors/translator-object/src/test/resources/ObjectProject/Trade_Object.xmi 2012-05-07 17:49:58 UTC (rev 4062)
@@ -11,7 +11,7 @@
<diagramEntity xmi:uuid="mmuuid:38199303-f03d-43ea-b506-a3d7e0be856b" modelObject="mmuuid/6c111154-eb05-4aca-ae33-d5a7d0c67e46"/>
</diagram>
</diagram:DiagramContainer>
- <relational:BaseTable xmi:uuid="mmuuid:5b23705c-0091-412a-9e79-c61ed02bd618" name="Trade" nameInSource=""Trade"">
+ <relational:BaseTable xmi:uuid="mmuuid:5b23705c-0091-412a-9e79-c61ed02bd618" name="Trade" nameInSource="org.teiid.translator.object.testdata.Trade">
<columns xmi:uuid="mmuuid:1a601c6c-979c-4a8a-9128-ac1c9cf853a8" name="TradeDate" nameInSource="TradeDate" nativeType="java.util.Date" fixedLength="true" nullable="NULLABLE_UNKNOWN" defaultValue="NULL" caseSensitive="false" searchability="ALL_EXCEPT_LIKE">
<type href="http://www.w3.org/2001/XMLSchema#date"/>
</columns>
12 years, 8 months
teiid SVN: r4061 - in trunk: engine/src/main/java/org/teiid/dqp/internal/process and 2 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2012-05-07 13:48:51 -0400 (Mon, 07 May 2012)
New Revision: 4061
Modified:
trunk/api/src/main/java/org/teiid/CommandContext.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java
trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDeployer.java
Log:
TEIID-2030: Make the the VDB classloader available though command context for use by the translators
Modified: trunk/api/src/main/java/org/teiid/CommandContext.java
===================================================================
--- trunk/api/src/main/java/org/teiid/CommandContext.java 2012-05-07 14:27:22 UTC (rev 4060)
+++ trunk/api/src/main/java/org/teiid/CommandContext.java 2012-05-07 17:48:51 UTC (rev 4061)
@@ -150,5 +150,11 @@
* @return
*/
long getReuseCount();
+
+ /**
+ * Get class loader for VDB.
+ * @return
+ */
+ ClassLoader getVDBClassLoader();
}
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 2012-05-07 14:27:22 UTC (rev 4060)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/Request.java 2012-05-07 17:48:51 UTC (rev 4061)
@@ -250,6 +250,7 @@
this.context.setDQPWorkContext(this.workContext);
this.context.setTransactionService(this.transactionService);
this.context.setTransactionContext(this.transactionContext);
+ this.context.setVDBClassLoader(workContext.getVDB().getAttachment(ClassLoader.class));
}
@Override
Modified: trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java 2012-05-07 14:27:22 UTC (rev 4060)
+++ trunk/engine/src/main/java/org/teiid/query/util/CommandContext.java 2012-05-07 17:48:51 UTC (rev 4061)
@@ -150,6 +150,7 @@
private LRUCache<String, DecimalFormat> decimalFormatCache;
private LRUCache<String, SimpleDateFormat> dateFormatCache;
private AtomicLong reuseCount = new AtomicLong();
+ private ClassLoader classLoader;
}
private GlobalState globalState = new GlobalState();
@@ -755,6 +756,14 @@
@Override
public long getReuseCount() {
return globalState.reuseCount.get();
+ }
+
+ @Override
+ public ClassLoader getVDBClassLoader() {
+ return this.globalState.classLoader;
}
+ public void setVDBClassLoader(ClassLoader classLoader) {
+ this.globalState.classLoader = classLoader;
+ }
}
Modified: trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDeployer.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDeployer.java 2012-05-07 14:27:22 UTC (rev 4060)
+++ trunk/jboss-integration/src/main/java/org/teiid/jboss/VDBDeployer.java 2012-05-07 17:48:51 UTC (rev 4061)
@@ -126,8 +126,11 @@
}
}
}
- }
+ }
+ // add VDB module's classloader as an attachment
+ deployment.addAttchment(ClassLoader.class, deploymentUnit.getAttachment(Attachments.MODULE).getClassLoader());
+
// check if this is a VDB with index files, if there are then build the TransformationMetadata
UDFMetaData udf = deploymentUnit.removeAttachment(TeiidAttachments.UDF_METADATA);
if (udf != null) {
12 years, 8 months
teiid SVN: r4060 - in branches/7.4.x: engine/src/main/java/org/teiid/dqp/internal/datamgr and 1 other directories.
by teiid-commits@lists.jboss.org
Author: jolee
Date: 2012-05-07 10:27:22 -0400 (Mon, 07 May 2012)
New Revision: 4060
Modified:
branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java
branches/7.4.x/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
branches/7.4.x/metadata/src/main/java/org/teiid/metadata/index/RecordFactory.java
Log:
TEIID-2020: Running Sybase procedure with jconnect driver in Teiid fails
Modified: branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java
===================================================================
--- branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java 2012-05-07 14:27:07 UTC (rev 4059)
+++ branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java 2012-05-07 14:27:22 UTC (rev 4060)
@@ -38,6 +38,7 @@
import org.teiid.translator.TranslatorException;
import org.teiid.translator.Execution;
import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.jdbc.sybase.SybaseExecutionFactory;
/**
@@ -135,7 +136,10 @@
}
protected void setSizeContraints(Statement statement) {
- try {
+ try {
+ if (statement instanceof CallableStatement && this.executionFactory instanceof SybaseExecutionFactory) {
+ return;
+ }
statement.setFetchSize(fetchSize);
} catch (SQLException e) {
if (LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL)) {
Modified: branches/7.4.x/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
===================================================================
--- branches/7.4.x/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java 2012-05-07 14:27:07 UTC (rev 4059)
+++ branches/7.4.x/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java 2012-05-07 14:27:22 UTC (rev 4060)
@@ -210,6 +210,9 @@
// Translate the command
Command command = this.requestMsg.getCommand();
this.expectedColumns = command.getProjectedSymbols().size();
+ if (command instanceof StoredProcedure) {
+ this.expectedColumns = ((StoredProcedure)command).getResultSetColumns().size();
+ }
LanguageBridgeFactory factory = new LanguageBridgeFactory(queryMetadata);
this.translatedCommand = factory.translate(command);
Modified: branches/7.4.x/metadata/src/main/java/org/teiid/metadata/index/RecordFactory.java
===================================================================
--- branches/7.4.x/metadata/src/main/java/org/teiid/metadata/index/RecordFactory.java 2012-05-07 14:27:07 UTC (rev 4059)
+++ branches/7.4.x/metadata/src/main/java/org/teiid/metadata/index/RecordFactory.java 2012-05-07 14:27:22 UTC (rev 4060)
@@ -811,6 +811,8 @@
case MetadataConstants.PARAMETER_TYPES.RETURN_VALUE:
type = ProcedureParameter.Type.ReturnValue;
break;
+ default:
+ throw new IllegalArgumentException("Invalid parameter type, please ensure all parameter types are valid in Designer.");
}
paramRd.setType(type);
12 years, 8 months
teiid SVN: r4059 - in branches/7.4.x/connectors/translator-jdbc/src: main/java/org/teiid/translator/jdbc/oracle and 1 other directories.
by teiid-commits@lists.jboss.org
Author: jolee
Date: 2012-05-07 10:27:07 -0400 (Mon, 07 May 2012)
New Revision: 4059
Modified:
branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java
branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
branches/7.4.x/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
Log:
TEIID-2005 Source query for Oracle sequence adds an alias, which will return "sequence doesn't exist" errors (modified for backport)
TEIID-832 (modified to only support TEIID-2005 changes) added support for calling oracle stored procedures returning cursor/resultsets
Modified: branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java
===================================================================
--- branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java 2012-05-05 23:32:41 UTC (rev 4058)
+++ branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java 2012-05-07 14:27:07 UTC (rev 4059)
@@ -31,10 +31,10 @@
import org.teiid.language.Argument;
import org.teiid.language.Call;
import org.teiid.language.Command;
-import org.teiid.translator.TranslatorException;
import org.teiid.translator.DataNotAvailableException;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.TranslatorException;
/**
*/
@@ -87,7 +87,10 @@
List<Object> result = new ArrayList<Object>();
int paramIndex = 1;
if (proc.getReturnType() != null) {
- addParameterValue(result, paramIndex++, proc.getReturnType());
+ if (proc.getReturnParameter() != null) {
+ addParameterValue(result, paramIndex, proc.getReturnType());
+ }
+ paramIndex++;
}
for (Argument parameter : proc.getArguments()) {
switch (parameter.getDirection()) {
Modified: branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
===================================================================
--- branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java 2012-05-05 23:32:41 UTC (rev 4058)
+++ branches/7.4.x/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java 2012-05-07 14:27:07 UTC (rev 4059)
@@ -1,535 +1,669 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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 static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
-
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import org.teiid.language.ColumnReference;
-import org.teiid.language.Command;
-import org.teiid.language.DerivedColumn;
-import org.teiid.language.Expression;
-import org.teiid.language.ExpressionValueSource;
-import org.teiid.language.Function;
-import org.teiid.language.Insert;
-import org.teiid.language.Limit;
-import org.teiid.language.Literal;
-import org.teiid.language.NamedTable;
-import org.teiid.language.QueryExpression;
-import org.teiid.language.Select;
-import org.teiid.language.SQLConstants.Tokens;
-import org.teiid.language.SetQuery.Operation;
-import org.teiid.language.visitor.CollectorVisitor;
-import org.teiid.metadata.Column;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.SourceSystemFunctions;
-import org.teiid.translator.Translator;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.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.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.LocateFunctionModifier;
-
-
-@Translator(name="oracle", description="A translator for Oracle 9i Database or later")
-public class OracleExecutionFactory extends JDBCExecutionFactory {
-
- private static final String TIME_FORMAT = "HH24:MI:SS"; //$NON-NLS-1$
- private static final String DATE_FORMAT = "YYYY-MM-DD"; //$NON-NLS-1$
- private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; //$NON-NLS-1$
- private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".FF"; //$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$
- /*
- * 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 static final String ORACLE_SDO = "Oracle-SDO"; //$NON-NLS-1$
-
+package org.teiid.translator.jdbc.oracle;
+
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
+import java.sql.CallableStatement;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.teiid.language.*;
+import org.teiid.language.SQLConstants.Tokens;
+import org.teiid.language.SetQuery.Operation;
+import org.teiid.language.visitor.CollectorVisitor;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.Column;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.SourceSystemFunctions;
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TranslatorProperty;
+import org.teiid.translator.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.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.JDBCPlugin;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.TranslatedCommand;
+
+
+@Translator(name="oracle", description="A translator for Oracle 9i Database or later")
+public class OracleExecutionFactory extends JDBCExecutionFactory {
+
+ private static final String TIME_FORMAT = "HH24:MI:SS"; //$NON-NLS-1$
+ private static final String DATE_FORMAT = "YYYY-MM-DD"; //$NON-NLS-1$
+ private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; //$NON-NLS-1$
+ private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".FF"; //$NON-NLS-1$
+
+ public final static String HINT_PREFIX = "/*+"; //$NON-NLS-1$
+ public static final String HINT_SUFFIX = "*/"; //$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$
+ /*
+ * 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 static final String ORACLE_SDO = "Oracle-SDO"; //$NON-NLS-1$
+
+ /*
+ * Handling for cursor return values
+ */
+ static final class RefCursorType {}
+ static int CURSOR_TYPE = -10;
+
+ /*
+ * handling for char bindings
+ */
+ static final class FixedCharType {}
+ static int FIXED_CHAR_TYPE = 999;
+
+ private boolean oracleSuppliedDriver = true;
+
public void start() throws TranslatorException {
- super.start();
+ super.start();
- 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(OracleExecutionFactory.RELATE, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleExecutionFactory.NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleExecutionFactory.FILTER, new OracleSpatialFunctionModifier());
- registerFunctionModifier(OracleExecutionFactory.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", DATE_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIME_FORMAT)); //$NON-NLS-1$
- 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 = TIMESTAMP_FORMAT;
- if (ex instanceof ColumnReference && "date".equalsIgnoreCase(((ColumnReference)ex).getMetadataObject().getNativeType())) { //$NON-NLS-1$
- format = DATETIME_FORMAT;
- } else if (!(ex instanceof Literal) && !(ex instanceof Function)) {
- //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", DATE_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_date", TIME_FORMAT)); //$NON-NLS-1$
- convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT)); //$NON-NLS-1$
- 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);
-
- addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, STRING, STRING);
- addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, OBJECT, STRING);
- addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, OBJECT, STRING);
- addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, STRING, STRING);
- addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, STRING, OBJECT, STRING, INTEGER);
- addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, OBJECT, STRING, INTEGER);
- addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, STRING, STRING, INTEGER);
- addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR_DISTANCE, INTEGER, INTEGER);
- addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, OBJECT, STRING);
- addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, STRING, OBJECT, STRING);
- addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, STRING, STRING);
- addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, STRING, STRING);
- addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, OBJECT, STRING);
- addPushDownFunction(ORACLE_SDO, FILTER, STRING, STRING, OBJECT, STRING);
- }
-
- public void handleInsertSequences(Insert insert) throws TranslatorException {
- /*
- * 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 TranslatorException("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 (TranslatorException 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;
- }
+ 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(OracleExecutionFactory.RELATE, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(OracleExecutionFactory.NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(OracleExecutionFactory.FILTER, new OracleSpatialFunctionModifier());
+ registerFunctionModifier(OracleExecutionFactory.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", DATE_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIME_FORMAT)); //$NON-NLS-1$
+ 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 = TIMESTAMP_FORMAT;
+ if (ex instanceof ColumnReference && "date".equalsIgnoreCase(((ColumnReference)ex).getMetadataObject().getNativeType())) { //$NON-NLS-1$
+ format = DATETIME_FORMAT;
+ } else if (!(ex instanceof Literal) && !(ex instanceof Function)) {
+ //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", DATE_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_date", TIME_FORMAT)); //$NON-NLS-1$
+ convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT)); //$NON-NLS-1$
+ 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);
+
+ addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, STRING, STRING);
+ addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, OBJECT, STRING);
+ addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, OBJECT, STRING);
+ addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, STRING, STRING);
+ addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, STRING, OBJECT, STRING, INTEGER);
+ addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, OBJECT, STRING, INTEGER);
+ addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, STRING, STRING, INTEGER);
+ addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR_DISTANCE, INTEGER, INTEGER);
+ addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, OBJECT, STRING);
+ addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, STRING, OBJECT, STRING);
+ addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, STRING, STRING);
+ addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, STRING, STRING);
+ addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, OBJECT, STRING);
+ addPushDownFunction(ORACLE_SDO, FILTER, STRING, STRING, OBJECT, STRING);
+ }
+
+ public void handleInsertSequences(Insert insert) throws TranslatorException {
+ /*
+ * 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 TranslatorException("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 (TranslatorException 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(OracleExecutionFactory.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.language.visitor.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 NullOrder getDefaultNullOrder() {
- return NullOrder.HIGH;
- }
-
- @Override
- public boolean supportsOrderByNullOrdering() {
- return true;
- }
-
- @Override
- 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(RELATE);
- supportedFunctions.add(NEAREST_NEIGHBOR);
- supportedFunctions.add(NEAREST_NEIGHBOR_DISTANCE);
- supportedFunctions.add(WITHIN_DISTANCE);
- supportedFunctions.add(FILTER);
- return supportedFunctions;
- }
-
- @Override
- public String translateLiteralTimestamp(Timestamp timestampValue) {
- if (timestampValue.getNanos() == 0) {
- String val = formatDateValue(timestampValue);
- val = val.substring(0, val.length() - 2);
- return "to_date('" + val + "', '" + DATETIME_FORMAT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
- return super.translateLiteralTimestamp(timestampValue);
- }
-
- @Override
- public boolean supportsInlineViews() {
- return true;
- }
-
- @Override
- public boolean supportsFunctionsInGroupBy() {
- return true;
- }
- @Override
- public boolean supportsRowLimit() {
- return true;
- }
- @Override
- public boolean supportsRowOffset() {
- return true;
- }
-
- @Override
- public boolean supportsExcept() {
- return true;
- }
-
- @Override
- public boolean supportsIntersect() {
- return true;
- }
-
- @Override
- public boolean supportsAggregatesEnhancedNumeric() {
- return true;
- }
-
+ @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 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(RELATE);
+ supportedFunctions.add(NEAREST_NEIGHBOR);
+ supportedFunctions.add(NEAREST_NEIGHBOR_DISTANCE);
+ supportedFunctions.add(WITHIN_DISTANCE);
+ supportedFunctions.add(FILTER);
+ return supportedFunctions;
+ }
+
+ @Override
+ public String getSourceComment(ExecutionContext context, Command command) {
+ String comment = super.getSourceComment(context, command);
+
+ boolean usingPayloadComment = false;
+ if (context != null) {
+ // Check for db hints
+ Object payload = context.getExecutionPayload();
+ if (payload instanceof String) {
+ String payloadString = (String)payload;
+ if (payloadString.startsWith(HINT_PREFIX)) {
+ int i = payloadString.indexOf(HINT_SUFFIX);
+ if (i > 0 && payloadString.substring(i + 2).trim().length() == 0) {
+ comment += payloadString + " "; //$NON-NLS-1$
+ usingPayloadComment = true;
+ } else {
+ String msg = JDBCPlugin.Util.getString("OraleExecutionFactory.invalid_hint", "Execution Payload", payloadString); //$NON-NLS-1$ //$NON-NLS-2$
+ context.addWarning(new TranslatorException(msg));
+ LogManager.logWarning(LogConstants.CTX_CONNECTOR, msg);
+ }
+ }
+ }
+ }
+
+
+ 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(OracleExecutionFactory.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.language.visitor.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;
+ }
+ if (paramType == FixedCharType.class) {
+ stmt.setObject(i, param, FIXED_CHAR_TYPE);
+ return;
+ }
+ super.bindValue(stmt, param, paramType, i);
+ }
+
+ @Override
+ public NullOrder getDefaultNullOrder() {
+ return NullOrder.HIGH;
+ }
+
+ @Override
+ public boolean supportsOrderByNullOrdering() {
+ return true;
+ }
+
+ @Override
+ public SQLConversionVisitor getSQLConversionVisitor() {
+ if (!oracleSuppliedDriver) {
+ return super.getSQLConversionVisitor();
+ }
+ return new SQLConversionVisitor(this) {
+
+ @Override
+ public void visit(Comparison obj) {
+ if (isChar(obj.getLeftExpression()) && obj.getRightExpression() instanceof Literal) {
+ Literal l = (Literal)obj.getRightExpression();
+ l.setType(FixedCharType.class);
+ }
+ super.visit(obj);
+ }
+
+ private boolean isChar(Expression obj) {
+ if (!(obj instanceof ColumnReference)) {
+ return false;
+ }
+ ColumnReference cr = (ColumnReference)obj;
+ return cr.getType() == TypeFacility.RUNTIME_TYPES.STRING && cr.getMetadataObject() != null && "CHAR".equalsIgnoreCase(cr.getMetadataObject().getNativeType()); //$NON-NLS-1$
+ }
+
+ public void visit(In obj) {
+ if (isChar(obj.getLeftExpression())) {
+ for (Expression exp : obj.getRightExpressions()) {
+ if (exp instanceof Literal) {
+ Literal l = (Literal)exp;
+ l.setType(FixedCharType.class);
+ }
+ }
+ }
+ super.visit(obj);
+ }
+
+ public void visit(NamedTable table) {
+ stripDualAlias(table);
+ super.visit(table);
+ }
+
+ private void stripDualAlias(NamedTable table) {
+ if (table.getCorrelationName() != null) {
+ String groupName = null;
+ AbstractMetadataRecord groupID = table.getMetadataObject();
+ if(groupID != null) {
+ groupName = getName(groupID);
+ } else {
+ groupName = table.getName();
+ }
+ if (DUAL.equalsIgnoreCase(groupName)) {
+ table.setCorrelationName(null);
+ }
+ }
+ }
+
+ @Override
+ public void visit(ColumnReference obj) {
+ if (obj.getTable() != null) {
+ stripDualAlias(obj.getTable());
+ }
+ super.visit(obj);
+ }
+
+ };
+ }
+
+ @Override
+ public String translateLiteralTimestamp(Timestamp timestampValue) {
+ if (timestampValue.getNanos() == 0) {
+ String val = formatDateValue(timestampValue);
+ val = val.substring(0, val.length() - 2);
+ return "to_date('" + val + "', '" + DATETIME_FORMAT + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+ return super.translateLiteralTimestamp(timestampValue);
+ }
+
+ @Override
+ public boolean supportsInlineViews() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsFunctionsInGroupBy() {
+ return true;
+ }
+ @Override
+ public boolean supportsRowLimit() {
+ return true;
+ }
+ @Override
+ public boolean supportsRowOffset() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExcept() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsIntersect() {
+ return true;
+ }
+
+ @Override
+ public boolean supportsAggregatesEnhancedNumeric() {
+ return true;
+ }
+
+ public void setOracleSuppliedDriver(boolean oracleNative) {
+ this.oracleSuppliedDriver = oracleNative;
+ }
+
+ @TranslatorProperty(display="Oracle Native Driver", description="True if the driver is an Oracle supplied driver",advanced=true)
+ public boolean isOracleSuppliedDriver() {
+ return oracleSuppliedDriver;
+ }
+
+ @Override
+ public List<?> translate(LanguageObject obj, ExecutionContext context) {
+ if (oracleSuppliedDriver && obj instanceof Call) {
+ Call call = (Call)obj;
+ if (call.getReturnType() == null && call.getMetadataObject() != null) {
+ //oracle returns the resultset as a parameter
+ call.setReturnType(RefCursorType.class);
+ }
+ }
+ return super.translate(obj, context);
+ }
+
+ @Override
+ protected void registerSpecificTypeOfOutParameter(
+ CallableStatement statement, Class<?> runtimeType, int index)
+ throws SQLException {
+ if (oracleSuppliedDriver && index == 1 && runtimeType == RefCursorType.class) {
+ statement.registerOutParameter(1, CURSOR_TYPE);
+ } else {
+ super.registerSpecificTypeOfOutParameter(statement, runtimeType, index);
+ }
+ }
+
+ @Override
+ public ResultSet executeStoredProcedure(CallableStatement statement,
+ TranslatedCommand command, Class<?> returnType) throws SQLException {
+ ResultSet rs = super.executeStoredProcedure(statement, command, returnType);
+ if (!oracleSuppliedDriver || returnType != RefCursorType.class) {
+ return rs;
+ }
+ return (ResultSet)statement.getObject(1);
+ }
+
}
Modified: branches/7.4.x/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- branches/7.4.x/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2012-05-05 23:32:41 UTC (rev 4058)
+++ branches/7.4.x/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java 2012-05-07 14:27:07 UTC (rev 4059)
@@ -24,10 +24,15 @@
import static org.junit.Assert.assertEquals;
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Mockito;
import org.teiid.cdk.CommandBuilder;
import org.teiid.cdk.api.TranslationUtility;
import org.teiid.core.types.DataTypeManager;
@@ -36,15 +41,20 @@
import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
import org.teiid.language.Command;
import org.teiid.metadata.Column;
+import org.teiid.metadata.ColumnSet;
import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
import org.teiid.metadata.Schema;
import org.teiid.metadata.Table;
import org.teiid.query.metadata.CompositeMetadataStore;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.sql.lang.SPParameter;
import org.teiid.query.unittest.RealMetadataFactory;
import org.teiid.translator.TranslatorException;
import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.jdbc.JDBCProcedureExecution;
import org.teiid.translator.jdbc.TranslatedCommand;
import org.teiid.translator.jdbc.TranslationHelper;
@@ -626,8 +636,8 @@
* @since 4.3
*/
@Test public void testDUAL() throws Exception {
- String input = "SELECT something FROM DUAL"; //$NON-NLS-1$
- String output = "SELECT something FROM DUAL"; //$NON-NLS-1$
+ String input = "SELECT something FROM DUAL as g0"; //$NON-NLS-1$
+ String output = "SELECT seq.nextval FROM DUAL"; //$NON-NLS-1$
helpTestVisitor(getOracleSpecificMetadata(),
input,
@@ -716,18 +726,21 @@
"DoubleNum", //$NON-NLS-1$
"ID", //$NON-NLS-1$
"timestampvalue", //$NON-NLS-1$
+ "description"
};
String[] elemTypes = new String[] {
DataTypeManager.DefaultDataTypes.DOUBLE,
DataTypeManager.DefaultDataTypes.INTEGER,
DataTypeManager.DefaultDataTypes.TIMESTAMP,
+ DataTypeManager.DefaultDataTypes.STRING
};
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$
-
+ cols.get(3).setNativeType("CHAR");
+ List<Column> dualCols = RealMetadataFactory.createElements(dual, new String[] {"something"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$
+ dualCols.get(0).setNameInSource("seq.nextval");
CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
return new TransformationMetadata(null, store, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
}
@@ -780,5 +793,32 @@
String expected = "SELECT (1 / tan(SmallA.DoubleNum)) FROM SmallA"; //$NON-NLS-1$
helpTestVisitor(RealMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
}
+
+ @Test public void testCallWithResultSet() throws Exception {
+ String input = "call spTest5(1)"; //$NON-NLS-1$
+ String output = "{ ?= call spTest5(?)}"; //$NON-NLS-1$
+ TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+ input, output,
+ TRANSLATOR);
+ }
+
+ @Test public void testProcedureExecution() throws Exception {
+ Command command = TranslationHelper.helpTranslate(TranslationHelper.BQT_VDB, "call spTest8(1)"); //$NON-NLS-1$
+ Connection connection = Mockito.mock(Connection.class);
+ CallableStatement cs = Mockito.mock(CallableStatement.class);
+ Mockito.stub(cs.getUpdateCount()).toReturn(-1);
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.stub(cs.getObject(1)).toReturn(rs);
+ Mockito.stub(cs.getInt(3)).toReturn(4);
+ Mockito.stub(connection.prepareCall("{ ?= call spTest8(?,?)}")).toReturn(cs); //$NON-NLS-1$
+ OracleExecutionFactory ef = new OracleExecutionFactory();
+
+ JDBCProcedureExecution procedureExecution = new JDBCProcedureExecution(command, connection, Mockito.mock(ExecutionContext.class), ef);
+ procedureExecution.execute();
+ assertEquals(Arrays.asList(4), procedureExecution.getOutputParameterValues());
+ Mockito.verify(cs, Mockito.times(1)).registerOutParameter(1, OracleExecutionFactory.CURSOR_TYPE);
+ Mockito.verify(cs, Mockito.times(1)).getObject(1);
+ }
+
}
12 years, 8 months
teiid SVN: r4058 - in trunk: build/kits/jboss-as7/docs/teiid and 5 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2012-05-05 19:32:41 -0400 (Sat, 05 May 2012)
New Revision: 4058
Modified:
trunk/api/src/main/java/org/teiid/metadata/Schema.java
trunk/build/kits/jboss-as7/docs/teiid/teiid-releasenotes.html
trunk/engine/src/main/java/org/teiid/query/parser/QueryParser.java
trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
trunk/engine/src/main/resources/org/teiid/query/i18n.properties
trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java
trunk/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java
Log:
TEIID-2031 allowing multiple functions of the same name
Modified: trunk/api/src/main/java/org/teiid/metadata/Schema.java
===================================================================
--- trunk/api/src/main/java/org/teiid/metadata/Schema.java 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/api/src/main/java/org/teiid/metadata/Schema.java 2012-05-05 23:32:41 UTC (rev 4058)
@@ -23,7 +23,6 @@
package org.teiid.metadata;
import java.io.IOException;
-import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
@@ -56,13 +55,10 @@
}
public void addFunction(FunctionMethod function) {
- addFunction(function.getName(), function);
- }
-
- public void addFunction(String uniqueName, FunctionMethod function) {
function.setParent(this);
- if (this.functions.put(uniqueName, function) != null) {
- throw new DuplicateRecordException(DataPlugin.Util.gs(DataPlugin.Event.TEIID60015, function.getName()));
+ //TODO: ensure that all uuids are unique
+ if (this.functions.put(function.getUUID(), function) != null) {
+ throw new DuplicateRecordException(DataPlugin.Util.gs(DataPlugin.Event.TEIID60015, function.getUUID()));
}
}
@@ -91,13 +87,18 @@
}
/**
- * Get the functions defined in this schema
+ * Get the functions defined in this schema in a map of uuid to {@link FunctionMethod}
* @return
*/
public Map<String, FunctionMethod> getFunctions() {
return functions;
}
+ /**
+ * Get a funciton by uuid
+ * @param funcName
+ * @return
+ */
public FunctionMethod getFunction(String funcName) {
return functions.get(funcName);
}
@@ -139,7 +140,7 @@
throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (this.functions == null) {
- this.functions = new LinkedHashMap<String, FunctionMethod>();
+ this.functions = new TreeMap<String, FunctionMethod>(String.CASE_INSENSITIVE_ORDER);
}
}
Modified: trunk/build/kits/jboss-as7/docs/teiid/teiid-releasenotes.html
===================================================================
--- trunk/build/kits/jboss-as7/docs/teiid/teiid-releasenotes.html 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/build/kits/jboss-as7/docs/teiid/teiid-releasenotes.html 2012-05-05 23:32:41 UTC (rev 4058)
@@ -60,6 +60,11 @@
<li>allowCreateTemporaryTablesByDefault and allowFunctionCallsByDefault are now set to false. When data roles are in use the user must explicitly grant these options to the user on VDB
</ul>
+<h4>from 8.0</h4>
+<ul>
+ <li>org.teiid.metadata.Schema holds FunctionMethods by uuid rather than name to accommodate overriden method signatures.
+<ul>
+
<h4>from 7.x</h4>
<ul>
<li>TRANSLATE/HAS CRITERIA has been removed. INSTEAD OF trigger actions should be used instead. ROWS_UPDATED, INPUTS, and INPUT are no longer procedure reserved words.
Modified: trunk/engine/src/main/java/org/teiid/query/parser/QueryParser.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/parser/QueryParser.java 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/engine/src/main/java/org/teiid/query/parser/QueryParser.java 2012-05-05 23:32:41 UTC (rev 4058)
@@ -30,6 +30,9 @@
import java.util.List;
import org.teiid.api.exception.query.QueryParserException;
+import org.teiid.connector.DataPlugin;
+import org.teiid.metadata.DuplicateRecordException;
+import org.teiid.metadata.FunctionMethod;
import org.teiid.metadata.MetadataFactory;
import org.teiid.query.QueryPlugin;
import org.teiid.query.sql.lang.CacheHint;
@@ -347,7 +350,12 @@
public void parseDDL(MetadataFactory factory, String ddl) throws ParseException {
getSqlParser(ddl).parseMetadata(factory);
- SQLParserUtil.replaceProceduresWithFunctions(factory);
+ HashSet<FunctionMethod> functions = new HashSet<FunctionMethod>();
+ for (FunctionMethod functionMethod : factory.getFunctions().values()) {
+ if (!functions.add(functionMethod)) {
+ throw new DuplicateRecordException(DataPlugin.Util.gs(DataPlugin.Event.TEIID60015, functionMethod.getName()));
+ }
+ }
}
}
Modified: trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2012-05-05 23:32:41 UTC (rev 4058)
@@ -445,77 +445,63 @@
}
}
- static void replaceProceduresWithFunctions(MetadataFactory factory) throws ParseException {
- ArrayList<String> procs = new ArrayList<String>();
-
- for (Procedure proc: factory.getProcedures().values()) {
- if (!proc.isFunction()) {
- continue;
- }
-
- procs.add(proc.getName());
-
- FunctionMethod method = new FunctionMethod();
- method.setName(proc.getName());
- method.setPushdown(proc.isVirtual()?FunctionMethod.PushDown.CAN_PUSHDOWN:FunctionMethod.PushDown.MUST_PUSHDOWN);
-
- ArrayList<FunctionParameter> ins = new ArrayList<FunctionParameter>();
- for (ProcedureParameter pp:proc.getParameters()) {
- if (pp.getType() != ProcedureParameter.Type.In) {
- throw new ParseException("Functions can only support 'In' parameters"); //$NON-NLS-1$
- }
-
- FunctionParameter fp = new FunctionParameter(pp.getName(), pp.getDatatype().getName());
- fp.setVarArg(pp.isVarArg());
- ins.add(fp);
- }
- method.setInputParameters(ins);
-
- List<Column> returnCols = proc.getResultSet().getColumns();
- if (returnCols != null && !returnCols.isEmpty()) {
- if (returnCols.size() > 1) {
- throw new ParseException("Functions can only return single parameter"); //$NON-NLS-1$
- }
- Column c = returnCols.get(0);
- FunctionParameter fp = new FunctionParameter(c.getName(), c.getDatatype().getName());
- method.setOutputParameter(fp);
- }
-
- method.setAnnotation(proc.getAnnotation());
- method.setNameInSource(proc.getNameInSource());
- method.setUUID(proc.getUUID());
-
- Map<String, String> props = proc.getProperties();
-
- String value = props.remove("CATEGORY"); //$NON-NLS-1$
- method.setCategory(value);
-
- value = props.remove("DETERMINISM"); //$NON-NLS-1$
- if (value != null) {
- method.setDeterminism(FunctionMethod.Determinism.valueOf(value.toUpperCase()));
+ static void replaceProcedureWithFunction(MetadataFactory factory,
+ Procedure proc) throws ParseException {
+ FunctionMethod method = new FunctionMethod();
+ method.setName(proc.getName());
+ method.setPushdown(proc.isVirtual()?FunctionMethod.PushDown.CAN_PUSHDOWN:FunctionMethod.PushDown.MUST_PUSHDOWN);
+
+ ArrayList<FunctionParameter> ins = new ArrayList<FunctionParameter>();
+ for (ProcedureParameter pp:proc.getParameters()) {
+ if (pp.getType() != ProcedureParameter.Type.In) {
+ throw new ParseException(QueryPlugin.Util.getString("SQLParser.function_in", proc.getName())); //$NON-NLS-1$
}
-
- value = props.remove("JAVA_CLASS"); //$NON-NLS-1$
- method.setInvocationClass(value);
- value = props.remove("JAVA_METHOD"); //$NON-NLS-1$
- method.setInvocationMethod(value);
-
- for (String key:props.keySet()) {
- value = props.get(key);
- method.setProperty(key, value);
- }
-
- FunctionMethod.convertExtensionMetadata(proc, method);
-
- factory.addFunction(method);
- }
-
- // remove the old procs
- for (String name:procs) {
- factory.getProcedures().remove(name);
- }
- }
+ FunctionParameter fp = new FunctionParameter(pp.getName(), pp.getDatatype().getName());
+ fp.setVarArg(pp.isVarArg());
+ ins.add(fp);
+ }
+ method.setInputParameters(ins);
+
+ List<Column> returnCols = proc.getResultSet().getColumns();
+ if (returnCols != null && !returnCols.isEmpty()) {
+ if (returnCols.size() > 1) {
+ throw new ParseException(QueryPlugin.Util.getString("SQLParser.function_return", proc.getName())); //$NON-NLS-1$
+ }
+ Column c = returnCols.get(0);
+ FunctionParameter fp = new FunctionParameter(c.getName(), c.getDatatype().getName());
+ method.setOutputParameter(fp);
+ }
+
+ method.setAnnotation(proc.getAnnotation());
+ method.setNameInSource(proc.getNameInSource());
+ method.setUUID(proc.getUUID());
+
+ Map<String, String> props = proc.getProperties();
+
+ String value = props.remove("CATEGORY"); //$NON-NLS-1$
+ method.setCategory(value);
+
+ value = props.remove("DETERMINISM"); //$NON-NLS-1$
+ if (value != null) {
+ method.setDeterminism(FunctionMethod.Determinism.valueOf(value.toUpperCase()));
+ }
+
+ value = props.remove("JAVA_CLASS"); //$NON-NLS-1$
+ method.setInvocationClass(value);
+
+ value = props.remove("JAVA_METHOD"); //$NON-NLS-1$
+ method.setInvocationMethod(value);
+
+ for (String key:props.keySet()) {
+ value = props.get(key);
+ method.setProperty(key, value);
+ }
+
+ FunctionMethod.convertExtensionMetadata(proc, method);
+ factory.addFunction(method);
+ factory.getProcedures().remove(proc.getName());
+ }
void setProcedureOptions(Procedure proc) {
Map<String, String> props = proc.getProperties();
Modified: trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
===================================================================
--- trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2012-05-05 23:32:41 UTC (rev 4058)
@@ -4158,6 +4158,9 @@
if (returnDataType != null){
addProcReturnColumn(factory, proc, "return", returnDataType);
}
+ if (function) {
+ replaceProcedureWithFunction(factory, proc);
+ }
return procCmd;
}
}
Modified: trunk/engine/src/main/resources/org/teiid/query/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/org/teiid/query/i18n.properties 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/engine/src/main/resources/org/teiid/query/i18n.properties 2012-05-05 23:32:41 UTC (rev 4058)
@@ -272,6 +272,8 @@
SQLParser.view_def=Virtual view {0} must be defined with a query expression.
SQLParser.pk_exists=Primary Key is already defined on {0}
SQLParser.no_column=Column name {0} not found on table {1}
+SQLParser.function_return=Function {0} is not valid. Functions can only return a single parameter.
+SQLParser.function_in=Functions {0} is not valid. Functions can only support 'In' parameters.
SystemSource.array_length_desc=Get the length of the given array value
SystemSource.array_param1=Array
SystemSource.array_length_result=The array length
Modified: trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/engine/src/test/java/org/teiid/query/parser/TestDDLParser.java 2012-05-05 23:32:41 UTC (rev 4058)
@@ -390,25 +390,43 @@
@Test
public void testPushdownFunctionNoArgs() throws Exception {
- String ddl = "CREATE FUNCTION SourceFunc() RETURNS integer";
+ String ddl = "CREATE FUNCTION SourceFunc() RETURNS integer OPTIONS (UUID 'hello world')";
Schema s = helpParse(ddl, "model");
- FunctionMethod fm = s.getFunction("SourceFunc");
+ FunctionMethod fm = s.getFunction("hello world");
assertNotNull(fm);
assertEquals("integer", fm.getOutputParameter().getType());
assertEquals(FunctionMethod.PushDown.MUST_PUSHDOWN, fm.getPushdown());
}
+ @Test(expected=DuplicateRecordException.class)
+ public void testDuplicateFunctions() throws Exception {
+ String ddl = "CREATE FUNCTION SourceFunc() RETURNS integer; CREATE FUNCTION SourceFunc() RETURNS string";
+ helpParse(ddl, "model");
+ }
+
+ @Test(expected=DuplicateRecordException.class)
+ public void testDuplicateFunctions1() throws Exception {
+ String ddl = "CREATE FUNCTION SourceFunc() RETURNS string OPTIONS (UUID 'a'); CREATE FUNCTION SourceFunc1() RETURNS string OPTIONS (UUID 'a')";
+ helpParse(ddl, "model");
+ }
+
+ @Test()
+ public void testDuplicateFunctions2() throws Exception {
+ String ddl = "CREATE FUNCTION SourceFunc() RETURNS string; CREATE FUNCTION SourceFunc(param string) RETURNS string";
+ helpParse(ddl, "model");
+ }
+
@Test
public void testUDF() throws Exception {
String ddl = "CREATE VIRTUAL FUNCTION SourceFunc(flag boolean, msg varchar) RETURNS varchar " +
"OPTIONS(CATEGORY 'misc', DETERMINISM 'DETERMINISTIC', " +
- "\"NULL-ON-NULL\" 'true', JAVA_CLASS 'foo', JAVA_METHOD 'bar', RANDOM 'any')";
+ "\"NULL-ON-NULL\" 'true', JAVA_CLASS 'foo', JAVA_METHOD 'bar', RANDOM 'any', UUID 'x')";
Schema s = helpParse(ddl, "model");
- FunctionMethod fm = s.getFunction("SourceFunc");
+ FunctionMethod fm = s.getFunction("x");
assertNotNull(fm);
assertEquals("string", fm.getOutputParameter().getType());
assertEquals(FunctionMethod.PushDown.CAN_PUSHDOWN, fm.getPushdown());
@@ -430,11 +448,11 @@
@Test
public void testUDAggregate() throws Exception {
String ddl = "CREATE VIRTUAL FUNCTION SourceFunc(flag boolean, msg varchar) RETURNS varchar " +
- "OPTIONS(CATEGORY 'misc', AGGREGATE 'true', \"allows-distinct\" 'true')";
+ "OPTIONS(CATEGORY 'misc', AGGREGATE 'true', \"allows-distinct\" 'true', UUID 'y')";
Schema s = helpParse(ddl, "model");
- FunctionMethod fm = s.getFunction("SourceFunc");
+ FunctionMethod fm = s.getFunction("y");
assertNotNull(fm);
assertEquals("string", fm.getOutputParameter().getType());
assertEquals(FunctionMethod.PushDown.CAN_PUSHDOWN, fm.getPushdown());
@@ -453,11 +471,11 @@
@Test
public void testVarArgs() throws Exception {
- String ddl = "CREATE FUNCTION SourceFunc(flag boolean) RETURNS varchar options (varargs 'true')";
+ String ddl = "CREATE FUNCTION SourceFunc(flag boolean) RETURNS varchar options (varargs 'true', UUID 'z')";
Schema s = helpParse(ddl, "model");
- FunctionMethod fm = s.getFunction("SourceFunc");
+ FunctionMethod fm = s.getFunction("z");
assertTrue( fm.getInputParameters().get(0).isVarArg());
}
Modified: trunk/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java 2012-05-04 18:29:47 UTC (rev 4057)
+++ trunk/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java 2012-05-05 23:32:41 UTC (rev 4058)
@@ -537,7 +537,7 @@
}
FunctionMethod func = FunctionMethod.createFunctionMethod(name, name, "pg", returnType, paramTypes); //$NON-NLS-1$
setUUID(func);
- addFunction(javaFunction, func);
+ addFunction(func);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
func.setInvocationMethod(javaFunction);
func.setPushdown(PushDown.CANNOT_PUSHDOWN);
12 years, 9 months