teiid SVN: r2134 - in trunk/connectors: connector-ws and 10 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-18 08:01:08 -0400 (Tue, 18 May 2010)
New Revision: 2134
Added:
trunk/connectors/connector-ws/
trunk/connectors/connector-ws/pom.xml
trunk/connectors/connector-ws/src/
trunk/connectors/connector-ws/src/main/
trunk/connectors/connector-ws/src/main/java/
trunk/connectors/connector-ws/src/main/java/org/
trunk/connectors/connector-ws/src/main/java/org/teiid/
trunk/connectors/connector-ws/src/main/java/org/teiid/resource/
trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/
trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/
trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java
trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java
trunk/connectors/connector-ws/src/main/rar/
trunk/connectors/connector-ws/src/main/rar/META-INF/
trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml
trunk/connectors/connector-ws/src/main/resources/
Removed:
trunk/connectors/connector-xml/
Log:
TEIID-1077: adding the connector-ws module
Added: trunk/connectors/connector-ws/pom.xml
===================================================================
--- trunk/connectors/connector-ws/pom.xml (rev 0)
+++ trunk/connectors/connector-ws/pom.xml 2010-05-18 12:01:08 UTC (rev 2134)
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-ws</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Web Service Connector</name>
+ <packaging>rar</packaging>
+ <description>This connector reads data from Web Services</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.ws.native</groupId>
+ <artifactId>jbossws-native-core</artifactId>
+ <version>3.1.1.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Added: trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java
===================================================================
--- trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java (rev 0)
+++ trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java 2010-05-18 12:01:08 UTC (rev 2134)
@@ -0,0 +1,188 @@
+package org.teiid.resource.adapter.ws;
+
+import java.io.StringReader;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+
+import javax.resource.ResourceException;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.AsyncHandler;
+import javax.xml.ws.Binding;
+import javax.xml.ws.BindingProvider;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.EndpointReference;
+import javax.xml.ws.Response;
+import javax.xml.ws.Service;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.http.HTTPBinding;
+import javax.xml.ws.soap.SOAPBinding;
+
+import org.jboss.ws.core.ConfigProvider;
+import org.teiid.resource.adapter.ws.WSManagedConnectionFactory.ParameterType;
+import org.teiid.resource.spi.BasicConnection;
+
+public class WSConnection extends BasicConnection implements Dispatch<Source>{
+ private static QName svcQname = new QName("http://teiid.org", "teiid"); //$NON-NLS-1$ //$NON-NLS-2$
+ private static QName portQName = new QName("http://teiid.org", "teiid");//$NON-NLS-1$ //$NON-NLS-2$
+
+ private Dispatch delegate;
+ private WSManagedConnectionFactory mcf;
+
+ public WSConnection(WSManagedConnectionFactory mcf) {
+ if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
+ this.delegate = createSOAPDispatch(mcf);
+ }
+ else if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
+ this.delegate = createHTTPDispatch(mcf, "GET"); //$NON-NLS-1$
+ }
+ else if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_POST) {
+ this.delegate = createHTTPDispatch(mcf, "POST"); //$NON-NLS-1$
+ }
+ this.mcf = mcf;
+ }
+
+
+ private Dispatch createHTTPDispatch(WSManagedConnectionFactory mcf, String requestMethod){
+ Service svc = Service.create(svcQname);
+ svc.addPort(portQName, HTTPBinding.HTTP_BINDING, mcf.getEndPoint());
+
+ Dispatch<Source> dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
+ dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_METHOD, requestMethod);
+ if (mcf.getSecurityType() == WSManagedConnectionFactory.SecurityType.HTTPBasic){
+ dispatch.getRequestContext().put(Dispatch.USERNAME_PROPERTY, mcf.getAuthUserName());
+ dispatch.getRequestContext().put(Dispatch.PASSWORD_PROPERTY, mcf.getAuthPassword());
+ }
+
+ Map<String, List<String>> httpHeaders = (Map<String, List<String>>)dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
+ if(httpHeaders == null) {
+ httpHeaders = new HashMap<String, List<String>>();
+ }
+ httpHeaders.put("Content-Type", Collections.singletonList("text/xml; charset=utf-8"));//$NON-NLS-1$ //$NON-NLS-2$
+ httpHeaders.put("User-Agent", Collections.singletonList("Teiid Server"));//$NON-NLS-1$ //$NON-NLS-2$
+ dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
+
+ return dispatch;
+ }
+
+ private Dispatch createSOAPDispatch(WSManagedConnectionFactory mcf) {
+ Service svc = Service.create(svcQname);
+
+ svc.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, mcf.getEndPoint());
+
+ Dispatch dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
+ if (mcf.getSecurityType() == WSManagedConnectionFactory.SecurityType.WSSecurity) {
+ // JBoss WS-Security
+ ((ConfigProvider) this.delegate).setSecurityConfig(mcf.getWsSecurityConfigURL());
+ ((ConfigProvider) delegate).setConfigName(mcf.getWsSecurityConfigName());
+ }
+ return dispatch;
+ }
+
+ public Binding getBinding() {
+ return delegate.getBinding();
+ }
+
+ public EndpointReference getEndpointReference() {
+ return delegate.getEndpointReference();
+ }
+
+ public <T extends EndpointReference> T getEndpointReference(Class<T> clazz) {
+ return delegate.getEndpointReference(clazz);
+ }
+
+ public Map<String, Object> getRequestContext() {
+ return delegate.getRequestContext();
+ }
+
+ public Map<String, Object> getResponseContext() {
+ return delegate.getResponseContext();
+ }
+
+
+ /**
+ * NOTE: the source msg from the teiid translator going to be SOAP. If execution is different from
+ * soap then fix it now.
+ */
+ @Override
+ public Source invoke(Source msg) {
+
+ String xmlPayload = null;
+ Map<String, Object> map = (Map)getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
+ if (map != null) {
+ xmlPayload = (String)map.remove("xml"); //$NON-NLS-1$
+ }
+
+ if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
+ if (isXMLInput() && xmlPayload != null) {
+ getRequestContext().put(MessageContext.QUERY_STRING, this.mcf.getXMLParamName()+"="+xmlPayload); //$NON-NLS-1$
+ }
+ else {
+ if (getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null) {
+
+ String path = (String)getRequestContext().get(MessageContext.PATH_INFO);
+ String queryString = (String)getRequestContext().get(MessageContext.QUERY_STRING);
+ String url = this.mcf.getEndPoint();
+ if (path != null) {
+ url = url + "/" + path; //$NON-NLS-1$
+ }
+ if (queryString != null) {
+ url = url + "?" + queryString; //$NON-NLS-1$
+ }
+ getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
+ }
+ }
+ msg = null;
+ }
+ else if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_POST) {
+ getRequestContext().put(MessageContext.QUERY_STRING, ""); //$NON-NLS-1$
+ if (isXMLInput() && xmlPayload != null) {
+ msg = new StreamSource(new StringReader(xmlPayload));
+ }
+ else {
+ msg = null;
+ }
+ }
+ else if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
+ // JBossWS native adds the null based address property somewhere and results in error if this
+ // is corrected
+ if (getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null) {
+ getRequestContext().remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
+ }
+ }
+
+ if (msg == null) {
+ // JBoss Native DispatchImpl throws exception when the source is null
+ msg = new StreamSource(new StringReader("<none/>"));
+ }
+ return (Source)delegate.invoke(msg);
+ }
+
+ private boolean isXMLInput() {
+ return (this.mcf.getParameterMethod() == ParameterType.XMLInQueryString || this.mcf.getParameterMethod() == ParameterType.XMLRequest);
+ }
+
+ @Override
+ public Future invokeAsync(Source msg, AsyncHandler handler) {
+ return delegate.invokeAsync(msg, handler);
+ }
+
+ @Override
+ public Response invokeAsync(Source msg) {
+ return delegate.invokeAsync(msg);
+ }
+
+ @Override
+ public void invokeOneWay(Source msg) {
+ delegate.invokeOneWay(msg);
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ this.delegate = null;
+ }
+}
Added: trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java
===================================================================
--- trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java (rev 0)
+++ trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java 2010-05-18 12:01:08 UTC (rev 2134)
@@ -0,0 +1,134 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.ws;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.ConnectionSpec;
+
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
+public class WSManagedConnectionFactory extends BasicManagedConnectionFactory {
+
+ private static final long serialVersionUID = -2998163922934555003L;
+
+ enum InvocationType {HTTP_GET, HTTP_POST, SOAP};
+ enum SecurityType {None,HTTPBasic,WSSecurity}
+ enum ParameterType{None,Name_Value,XMLRequest,XMLInQueryString};
+
+ private String invocationType;
+ private String endPoint;
+
+ private String securityType; // None, HTTPBasic, WS-Security
+ private String wsSecurityConfigURL; // path to the "jboss-wsse-client.xml" file
+ private String wsSecurityConfigName; // ws-security config name in the above file
+ private String authPassword; // httpbasic - password
+ private String authUserName; // httpbasic - username
+ private String parameterMethod;
+ private String xMLParamName;
+
+
+ @Override
+ public Object createConnectionFactory() throws ResourceException {
+ return new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new WSConnection(WSManagedConnectionFactory.this);
+ }
+ };
+ }
+
+
+ public InvocationType getInvocationType() {
+ return InvocationType.valueOf(invocationType);
+ }
+
+
+ public void setInvocationType(String invocationType) {
+ this.invocationType = invocationType;
+ }
+
+ public String getAuthPassword() {
+ return this.authPassword;
+ }
+
+ public void setAuthPassword(String authPassword) {
+ this.authPassword = authPassword;
+ }
+
+ public String getAuthUserName() {
+ return this.authUserName;
+ }
+
+ public void setAuthUserName(String authUserName) {
+ this.authUserName = authUserName;
+ }
+
+ public String getEndPoint() {
+ return this.endPoint;
+ }
+
+ public void setEndPoint(String endPoint) {
+ this.endPoint = endPoint;
+ }
+
+ public SecurityType getSecurityType() {
+ return SecurityType.valueOf(this.securityType);
+ }
+
+ public void setSecurityType(String securityType) {
+ this.securityType = securityType;
+ }
+
+ public String getWsSecurityConfigURL() {
+ return wsSecurityConfigURL;
+ }
+
+ public void setWsSecurityConfigURL(String wsSecurityConfigURL) {
+ this.wsSecurityConfigURL = wsSecurityConfigURL;
+ }
+
+ public String getWsSecurityConfigName() {
+ return wsSecurityConfigName;
+ }
+
+ public void setWsSecurityConfigName(String wsSecurityConfigName) {
+ this.wsSecurityConfigName = wsSecurityConfigName;
+ }
+
+ public ParameterType getParameterMethod() {
+ return ParameterType.valueOf(parameterMethod);
+ }
+
+ public void setParameterMethod(String parameterMethod) {
+ this.parameterMethod = parameterMethod;
+ }
+
+ public String getXMLParamName() {
+ return xMLParamName;
+ }
+
+ public void setXMLParamName(String xMLParamName) {
+ this.xMLParamName = xMLParamName;
+ }
+}
Added: trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml (rev 0)
+++ trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml 2010-05-18 12:01:08 UTC (rev 2134)
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<connector xmlns="http://java.sun.com/xml/ns/j2ee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
+ http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd"
+ version="1.5">
+
+ <vendor-name>Red Hat Middleware LLC</vendor-name>
+ <eis-type>Teiid XML SOAP Connector</eis-type>
+ <resourceadapter-version>1.0</resourceadapter-version>
+ <license>
+ <description>
+ JBoss, Home of Professional Open Source.
+ Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ as indicated by the @author tags. See the copyright.txt file in the
+ distribution for a full listing of individual contributors.
+
+ This is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as
+ published by the Free Software Foundation; either version 2.1 of
+ the License, or (at your option) any later version.
+
+ This software is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this software; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ </description>
+ <license-required>true</license-required>
+ </license>
+ <resourceadapter>
+ <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
+
+ <outbound-resourceadapter>
+ <connection-definition>
+ <managedconnectionfactory-class>org.teiid.resource.adapter.ws.WSManagedConnectionFactory</managedconnectionfactory-class>
+
+ <config-property>
+ <description>{$display:"Invocation Type",$description:"Service Invocation type (HTTP or SOAP)", $allowed="HTTP_GET, HTTP_POST,SOAP", $required="true", $defaultValue="SOAP"}</description>
+ <config-property-name>InvocationType</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>SOAP</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"URL, End Point",$description:"URL for HTTP, Service Endpoint for SOAP",$required="true"}</description>
+ <config-property-name>EndPoint</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"WebService Security Used(None, HTTPBasic, WS-Security)",$allowed="None,HTTPBasic,WSSecurity", $description:"Type of Authentication to used with the web service; If WS-Secuirty is being used, then WS-Secuirty type must be defined", $required:"true", $defaultValue="None"}</description>
+ <config-property-name>SecurityType</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>None</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Authentication User Name",$description:"Name value for authentication",$advanced:"true"}</description>
+ <config-property-name>AuthUserName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Authentication User Password",$description:"Password value for authentication",$advanced:"true",$masked:"true"}</description>
+ <config-property-name>AuthPassword</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"URL to the WS-Security Configuration File(jboss-wsse-client.xml)",$description:"JBoss WS-Security client configuration File"}</description>
+ <config-property-name>WsSecurityConfigURL</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"WS-Security Configuration Name in jboss-wsse-client.xml",$description:"JBoss WS-Security client configuration name to use"}</description>
+ <config-property-name>WsSecurityConfigName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"XML Parameter Name", $description="only required for the HTTP with XML based request"}</description>
+ <config-property-name>XMLParamName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Parameter Method (None, Name_Value, XMLRequest, XMLInQueryString)",$description:"",$allowed:["None","Name_Value","XMLRequest","XMLInQueryString"], $editable:"false", defaultValue="Name_Value"}</description>
+ <config-property-name>ParameterMethod</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>Name_Value</config-property-value>
+ </config-property>
+
+ <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
+ <connectionfactory-impl-class>org.teiid.resource.spi.WrappedConnectionFactory</connectionfactory-impl-class>
+ <connection-interface>javax.resource.cci.Connection</connection-interface>
+ <connection-impl-class>org.teiid.resource.spi.WrappedConnection</connection-impl-class>
+
+ </connection-definition>
+
+ <transaction-support>NoTransaction</transaction-support>
+
+ <authentication-mechanism>
+ <authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
+ <credential-interface>javax.resource.spi.security.PasswordCredential</credential-interface>
+ </authentication-mechanism>
+ <reauthentication-support>false</reauthentication-support>
+ </outbound-resourceadapter>
+ </resourceadapter>
+</connector>
14 years, 7 months
teiid SVN: r2133 - trunk/connectors.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-17 18:21:02 -0400 (Mon, 17 May 2010)
New Revision: 2133
Modified:
trunk/connectors/pom.xml
Log:
TEIID-1077: Adding XML translator. Previous "connector-xml" became "translator-xml" with few modifications. New module "connector-ws" is being introduced, in exchange for the "connector-http, file, soap" modules. This one works with JAX-WS.
Modified: trunk/connectors/pom.xml
===================================================================
--- trunk/connectors/pom.xml 2010-05-17 22:19:02 UTC (rev 2132)
+++ trunk/connectors/pom.xml 2010-05-17 22:21:02 UTC (rev 2133)
@@ -86,14 +86,15 @@
<module>connector-salesforce</module>
<module>connector-ldap</module>
<module>salesforce-api</module>
+ <module>connector-ws</module>
<module>sandbox</module>
- <!--
- <module>connector-xml</module>
+ <module>translator-xml</module>
+ <!--
<module>connector-xml-file</module>
<module>connector-xml-soap</module>
<module>connector-xml-http</module>
- -->
+ -->
</modules>
</project>
14 years, 7 months
teiid SVN: r2132 - connector-ws/src and 36 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-17 18:19:02 -0400 (Mon, 17 May 2010)
New Revision: 2132
Added:
connector-ws/pom.xml
connector-ws/src/
connector-ws/src/main/
connector-ws/src/main/java/
connector-ws/src/main/java/org/
connector-ws/src/main/java/org/teiid/
connector-ws/src/main/java/org/teiid/resource/
connector-ws/src/main/java/org/teiid/resource/adapter/
connector-ws/src/main/java/org/teiid/resource/adapter/ws/
connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java
connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java
connector-ws/src/main/rar/
connector-ws/src/main/rar/META-INF/
connector-ws/src/main/rar/META-INF/ra.xml
connector-ws/src/main/resources/
trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml
trunk/connectors/translator-xml/
trunk/connectors/translator-xml/src/main/java/org/
trunk/connectors/translator-xml/src/main/java/org/teiid/
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Constants.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CriteriaDesc.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Document.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/DocumentBuilder.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ExecutionInfo.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileProcedureExecution.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/IDGeneratingXmlFilter.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/OutputXPathDesc.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ParameterDescriptor.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/QueryAnalyzer.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestGenerator.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestPreprocessor.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/SAXFilterProvider.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLPlugin.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/DocumentImpl.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ElementProcessor.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/InvalidPathException.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ReaderFactory.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingMultiPathFilter.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingResultsProducer.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingRowCollector.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/XPathSplitter.java
trunk/connectors/translator-xml/src/main/resources/META-INF/
trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml
trunk/connectors/translator-xml/src/main/resources/org/
trunk/connectors/translator-xml/src/main/resources/org/teiid/
trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/
trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/xml/
trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/xml/i18n.properties
trunk/connectors/translator-xml/src/test/java/org/
trunk/connectors/translator-xml/src/test/java/org/teiid/
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/MockQueryPreprocessor.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/ProxyObjectFactory.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCriteriaDesc.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestElementCollector.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestExecutionInfo.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestOutputXPathDesc.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestParameterDescriptor.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestQueryAnalyzer.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLCapabilities.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLReaderFactory.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXPathSplitter.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestCachingFileConnectorLong.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileConnector.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileExecution.java
trunk/connectors/translator-xml/src/test/resources/BookCollection.xml
trunk/connectors/translator-xml/src/test/resources/documents/purchaseOrdersShort.xml
Removed:
trunk/connectors/translator-xml/src/main/java/com/metamatrix/connector/xml/base/
trunk/connectors/translator-xml/src/main/java/com/metamatrix/connector/xml/streaming/
trunk/connectors/translator-xml/src/main/resources/com/
trunk/connectors/translator-xml/src/test/java/com/
trunk/connectors/translator-xml/src/test/resources/com/
Modified:
connector-ws/
trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java
trunk/build/assembly/jboss-container/dist.xml
trunk/connectors/connector-text/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java
trunk/connectors/translator-xml/pom.xml
Log:
TEIID-1077: Adding XML translator. Previous "connector-xml" became "translator-xml" with few modifications. New module "connector-ws" is being introduced, in exchange for the "connector-http, file, soap" modules. This one works with JAX-WS.
Property changes on: connector-ws
___________________________________________________________________
Name: svn:ignore
+ target
.classpath
.project
.settings
Added: connector-ws/pom.xml
===================================================================
--- connector-ws/pom.xml (rev 0)
+++ connector-ws/pom.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-ws</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <name>Web Service Connector</name>
+ <packaging>rar</packaging>
+ <description>This connector reads data from Web Services</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.resource</groupId>
+ <artifactId>connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.ws.native</groupId>
+ <artifactId>jbossws-native</artifactId>
+ <version>3.1.2.GA</version>
+ <scope>provided</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>build_jar</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>deploy_jar</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <classifier>lib</classifier>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
\ No newline at end of file
Property changes on: connector-ws/pom.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java
===================================================================
--- connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java (rev 0)
+++ connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,188 @@
+package org.teiid.resource.adapter.ws;
+
+import java.io.StringReader;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+
+import javax.resource.ResourceException;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.AsyncHandler;
+import javax.xml.ws.Binding;
+import javax.xml.ws.BindingProvider;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.EndpointReference;
+import javax.xml.ws.Response;
+import javax.xml.ws.Service;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.http.HTTPBinding;
+import javax.xml.ws.soap.SOAPBinding;
+
+import org.jboss.ws.core.ConfigProvider;
+import org.teiid.resource.adapter.ws.WSManagedConnectionFactory.ParameterType;
+import org.teiid.resource.spi.BasicConnection;
+
+public class WSConnection extends BasicConnection implements Dispatch<Source>{
+ private static QName svcQname = new QName("http://teiid.org", "teiid"); //$NON-NLS-1$ //$NON-NLS-2$
+ private static QName portQName = new QName("http://teiid.org", "teiid");//$NON-NLS-1$ //$NON-NLS-2$
+
+ private Dispatch delegate;
+ private WSManagedConnectionFactory mcf;
+
+ public WSConnection(WSManagedConnectionFactory mcf) {
+ if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
+ this.delegate = createSOAPDispatch(mcf);
+ }
+ else if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
+ this.delegate = createHTTPDispatch(mcf, "GET"); //$NON-NLS-1$
+ }
+ else if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_POST) {
+ this.delegate = createHTTPDispatch(mcf, "POST"); //$NON-NLS-1$
+ }
+ this.mcf = mcf;
+ }
+
+
+ private Dispatch createHTTPDispatch(WSManagedConnectionFactory mcf, String requestMethod){
+ Service svc = Service.create(svcQname);
+ svc.addPort(portQName, HTTPBinding.HTTP_BINDING, mcf.getEndPoint());
+
+ Dispatch<Source> dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
+ dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_METHOD, requestMethod);
+ if (mcf.getSecurityType() == WSManagedConnectionFactory.SecurityType.HTTPBasic){
+ dispatch.getRequestContext().put(Dispatch.USERNAME_PROPERTY, mcf.getAuthUserName());
+ dispatch.getRequestContext().put(Dispatch.PASSWORD_PROPERTY, mcf.getAuthPassword());
+ }
+
+ Map<String, List<String>> httpHeaders = (Map<String, List<String>>)dispatch.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS);
+ if(httpHeaders == null) {
+ httpHeaders = new HashMap<String, List<String>>();
+ }
+ httpHeaders.put("Content-Type", Collections.singletonList("text/xml; charset=utf-8"));//$NON-NLS-1$ //$NON-NLS-2$
+ httpHeaders.put("User-Agent", Collections.singletonList("Teiid Server"));//$NON-NLS-1$ //$NON-NLS-2$
+ dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
+
+ return dispatch;
+ }
+
+ private Dispatch createSOAPDispatch(WSManagedConnectionFactory mcf) {
+ Service svc = Service.create(svcQname);
+
+ svc.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, mcf.getEndPoint());
+
+ Dispatch dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
+ if (mcf.getSecurityType() == WSManagedConnectionFactory.SecurityType.WSSecurity) {
+ // JBoss WS-Security
+ ((ConfigProvider) this.delegate).setSecurityConfig(mcf.getWsSecurityConfigURL());
+ ((ConfigProvider) delegate).setConfigName(mcf.getWsSecurityConfigName());
+ }
+ return dispatch;
+ }
+
+ public Binding getBinding() {
+ return delegate.getBinding();
+ }
+
+ public EndpointReference getEndpointReference() {
+ return delegate.getEndpointReference();
+ }
+
+ public <T extends EndpointReference> T getEndpointReference(Class<T> clazz) {
+ return delegate.getEndpointReference(clazz);
+ }
+
+ public Map<String, Object> getRequestContext() {
+ return delegate.getRequestContext();
+ }
+
+ public Map<String, Object> getResponseContext() {
+ return delegate.getResponseContext();
+ }
+
+
+ /**
+ * NOTE: the source msg from the teiid translator going to be SOAP. If execution is different from
+ * soap then fix it now.
+ */
+ @Override
+ public Source invoke(Source msg) {
+
+ String xmlPayload = null;
+ Map<String, Object> map = (Map)getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
+ if (map != null) {
+ xmlPayload = (String)map.remove("xml"); //$NON-NLS-1$
+ }
+
+ if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
+ if (isXMLInput() && xmlPayload != null) {
+ getRequestContext().put(MessageContext.QUERY_STRING, this.mcf.getXMLParamName()+"="+xmlPayload); //$NON-NLS-1$
+ }
+ else {
+ if (getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null) {
+
+ String path = (String)getRequestContext().get(MessageContext.PATH_INFO);
+ String queryString = (String)getRequestContext().get(MessageContext.QUERY_STRING);
+ String url = this.mcf.getEndPoint();
+ if (path != null) {
+ url = url + "/" + path; //$NON-NLS-1$
+ }
+ if (queryString != null) {
+ url = url + "?" + queryString; //$NON-NLS-1$
+ }
+ getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
+ }
+ }
+ msg = null;
+ }
+ else if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_POST) {
+ getRequestContext().put(MessageContext.QUERY_STRING, ""); //$NON-NLS-1$
+ if (isXMLInput() && xmlPayload != null) {
+ msg = new StreamSource(new StringReader(xmlPayload));
+ }
+ else {
+ msg = null;
+ }
+ }
+ else if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
+ // JBossWS native adds the null based address property somewhere and results in error if this
+ // is corrected
+ if (getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null) {
+ getRequestContext().remove(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
+ }
+ }
+
+ if (msg == null) {
+ // JBoss Native DispatchImpl throws exception when the source is null
+ msg = new StreamSource(new StringReader("<none/>"));
+ }
+ return (Source)delegate.invoke(msg);
+ }
+
+ private boolean isXMLInput() {
+ return (this.mcf.getParameterMethod() == ParameterType.XMLInQueryString || this.mcf.getParameterMethod() == ParameterType.XMLRequest);
+ }
+
+ @Override
+ public Future invokeAsync(Source msg, AsyncHandler handler) {
+ return delegate.invokeAsync(msg, handler);
+ }
+
+ @Override
+ public Response invokeAsync(Source msg) {
+ return delegate.invokeAsync(msg);
+ }
+
+ @Override
+ public void invokeOneWay(Source msg) {
+ delegate.invokeOneWay(msg);
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ this.delegate = null;
+ }
+}
Property changes on: connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java
===================================================================
--- connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java (rev 0)
+++ connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,133 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.resource.adapter.ws;
+
+import javax.resource.ResourceException;
+
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.resource.spi.BasicManagedConnectionFactory;
+
+public class WSManagedConnectionFactory extends BasicManagedConnectionFactory {
+
+ private static final long serialVersionUID = -2998163922934555003L;
+
+ enum InvocationType {HTTP_GET, HTTP_POST, SOAP};
+ enum SecurityType {None,HTTPBasic,WSSecurity}
+ enum ParameterType{None,Name_Value,XMLRequest,XMLInQueryString};
+
+ private String invocationType;
+ private String endPoint;
+
+ private String securityType; // None, HTTPBasic, WS-Security
+ private String wsSecurityConfigURL; // path to the "jboss-wsse-client.xml" file
+ private String wsSecurityConfigName; // ws-security config name in the above file
+ private String authPassword; // httpbasic - password
+ private String authUserName; // httpbasic - username
+ private String parameterMethod;
+ private String xMLParamName;
+
+
+ @Override
+ public Object createConnectionFactory() throws ResourceException {
+ return new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new WSConnection(WSManagedConnectionFactory.this);
+ }
+ };
+ }
+
+
+ public InvocationType getInvocationType() {
+ return InvocationType.valueOf(invocationType);
+ }
+
+
+ public void setInvocationType(String invocationType) {
+ this.invocationType = invocationType;
+ }
+
+ public String getAuthPassword() {
+ return this.authPassword;
+ }
+
+ public void setAuthPassword(String authPassword) {
+ this.authPassword = authPassword;
+ }
+
+ public String getAuthUserName() {
+ return this.authUserName;
+ }
+
+ public void setAuthUserName(String authUserName) {
+ this.authUserName = authUserName;
+ }
+
+ public String getEndPoint() {
+ return this.endPoint;
+ }
+
+ public void setEndPoint(String endPoint) {
+ this.endPoint = endPoint;
+ }
+
+ public SecurityType getSecurityType() {
+ return SecurityType.valueOf(this.securityType);
+ }
+
+ public void setSecurityType(String securityType) {
+ this.securityType = securityType;
+ }
+
+ public String getWsSecurityConfigURL() {
+ return wsSecurityConfigURL;
+ }
+
+ public void setWsSecurityConfigURL(String wsSecurityConfigURL) {
+ this.wsSecurityConfigURL = wsSecurityConfigURL;
+ }
+
+ public String getWsSecurityConfigName() {
+ return wsSecurityConfigName;
+ }
+
+ public void setWsSecurityConfigName(String wsSecurityConfigName) {
+ this.wsSecurityConfigName = wsSecurityConfigName;
+ }
+
+ public ParameterType getParameterMethod() {
+ return ParameterType.valueOf(parameterMethod);
+ }
+
+ public void setParameterMethod(String parameterMethod) {
+ this.parameterMethod = parameterMethod;
+ }
+
+ public String getXMLParamName() {
+ return xMLParamName;
+ }
+
+ public void setXMLParamName(String xMLParamName) {
+ this.xMLParamName = xMLParamName;
+ }
+}
Property changes on: connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: connector-ws/src/main/rar/META-INF/ra.xml
===================================================================
--- connector-ws/src/main/rar/META-INF/ra.xml (rev 0)
+++ connector-ws/src/main/rar/META-INF/ra.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<connector xmlns="http://java.sun.com/xml/ns/j2ee"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
+ http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd"
+ version="1.5">
+
+ <vendor-name>Red Hat Middleware LLC</vendor-name>
+ <eis-type>Teiid XML SOAP Connector</eis-type>
+ <resourceadapter-version>1.0</resourceadapter-version>
+ <license>
+ <description>
+ JBoss, Home of Professional Open Source.
+ Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ as indicated by the @author tags. See the copyright.txt file in the
+ distribution for a full listing of individual contributors.
+
+ This is free software; you can redistribute it and/or modify it
+ under the terms of the GNU Lesser General Public License as
+ published by the Free Software Foundation; either version 2.1 of
+ the License, or (at your option) any later version.
+
+ This software is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this software; if not, write to the Free
+ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ </description>
+ <license-required>true</license-required>
+ </license>
+ <resourceadapter>
+ <resourceadapter-class>org.teiid.resource.spi.BasicResourceAdapter</resourceadapter-class>
+
+ <outbound-resourceadapter>
+ <connection-definition>
+ <managedconnectionfactory-class>org.teiid.resource.adapter.ws.WSManagedConnectionFactory</managedconnectionfactory-class>
+
+ <config-property>
+ <description>{$display:"Invocation Type",$description:"Service Invocation type (HTTP or SOAP)", $allowed="HTTP_GET, HTTP_POST,SOAP", $required="true", $defaultValue="SOAP"}</description>
+ <config-property-name>InvocationType</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>SOAP</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"URL, End Point",$description:"URL for HTTP, Service Endpoint for SOAP",$required="true"}</description>
+ <config-property-name>EndPoint</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"WebService Security Used(None, HTTPBasic, WS-Security)",$allowed="None,HTTPBasic,WSSecurity", $description:"Type of Authentication to used with the web service; If WS-Secuirty is being used, then WS-Secuirty type must be defined", $required:"true", $defaultValue="None"}</description>
+ <config-property-name>SecurityType</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>None</config-property-value>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Authentication User Name",$description:"Name value for authentication",$advanced:"true"}</description>
+ <config-property-name>AuthUserName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Authentication User Password",$description:"Password value for authentication",$advanced:"true",$masked:"true"}</description>
+ <config-property-name>AuthPassword</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"URL to the WS-Security Configuration File(jboss-wsse-client.xml)",$description:"JBoss WS-Security client configuration File"}</description>
+ <config-property-name>WsSecurityConfigURL</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"WS-Security Configuration Name in jboss-wsse-client.xml",$description:"JBoss WS-Security client configuration name to use"}</description>
+ <config-property-name>WsSecurityConfigName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"XML Parameter Name", $description="only required for the HTTP with XML based request"}</description>
+ <config-property-name>XMLParamName</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ </config-property>
+
+ <config-property>
+ <description>{$display:"Parameter Method (None, Name_Value, XMLRequest, XMLInQueryString)",$description:"",$allowed:["None","Name_Value","XMLRequest","XMLInQueryString"], $editable:"false", defaultValue="Name_Value"}</description>
+ <config-property-name>ParameterMethod</config-property-name>
+ <config-property-type>java.lang.String</config-property-type>
+ <config-property-value>Name_Value</config-property-value>
+ </config-property>
+
+ <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
+ <connectionfactory-impl-class>org.teiid.resource.spi.WrappedConnectionFactory</connectionfactory-impl-class>
+ <connection-interface>javax.resource.cci.Connection</connection-interface>
+ <connection-impl-class>org.teiid.resource.spi.WrappedConnection</connection-impl-class>
+
+ </connection-definition>
+
+ <transaction-support>NoTransaction</transaction-support>
+
+ <authentication-mechanism>
+ <authentication-mechanism-type>BasicPassword</authentication-mechanism-type>
+ <credential-interface>javax.resource.spi.security.PasswordCredential</credential-interface>
+ </authentication-mechanism>
+ <reauthentication-support>false</reauthentication-support>
+ </outbound-resourceadapter>
+ </resourceadapter>
+</connector>
Property changes on: connector-ws/src/main/rar/META-INF/ra.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java
===================================================================
--- trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java 2010-05-17 22:13:10 UTC (rev 2131)
+++ trunk/api/src/main/java/org/teiid/translator/ExecutionFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -22,8 +22,11 @@
package org.teiid.translator;
+import java.util.Collection;
import java.util.List;
+import org.teiid.core.TeiidException;
+import org.teiid.core.util.ReflectionHelper;
import org.teiid.language.BatchedUpdates;
import org.teiid.language.Call;
import org.teiid.language.Command;
@@ -683,4 +686,21 @@
return false;
}
+ public static <T> T getInstance(Class<T> expectedType, String className, Collection ctorObjs, Class defaultClass) throws TranslatorException {
+ try {
+ if (className == null) {
+ if (defaultClass == null) {
+ throw new TranslatorException("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 (TeiidException e) {
+ throw new TranslatorException(e);
+ } catch (IllegalAccessException e) {
+ throw new TranslatorException(e);
+ } catch(InstantiationException e) {
+ throw new TranslatorException(e);
+ }
+ }
}
Modified: trunk/build/assembly/jboss-container/dist.xml
===================================================================
--- trunk/build/assembly/jboss-container/dist.xml 2010-05-17 22:13:10 UTC (rev 2131)
+++ trunk/build/assembly/jboss-container/dist.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -47,7 +47,7 @@
<includes>
<include>org.jboss.teiid:teiid-jboss-integration</include>
- <include>org.jboss.teiid.connectors:connector-xml</include>
+ <include>org.jboss.teiid.connectors:translator-xml</include>
</includes>
<binaries>
@@ -78,6 +78,8 @@
<include>org.jboss.teiid.connectors:connector-ldap:rar</include>
<include>org.jboss.teiid.connectors:translator-salesforce</include>
<include>org.jboss.teiid.connectors:connector-salesforce:rar</include>
+ <include>org.jboss.teiid.connectors:connector-ws:rar</include>
+
<!--
<include>org.jboss.teiid.connectors:connector-xml-http:rar</include>
<include>org.jboss.teiid.connectors:connector-xml-file:rar</include>
Added: trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml (rev 0)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<translator-factory>
+ <translator>
+ <name>xml</name>
+ <execution-factory-class>org.teiid.translator.xml.base.XMLExecutionFactory</execution-factory-class>
+ <template-name>translator-xml-${project.version}</template-name>
+ </translator>
+</translator-factory>
\ No newline at end of file
Property changes on: trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/connectors/connector-text/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java
===================================================================
--- trunk/connectors/connector-text/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java 2010-05-17 22:13:10 UTC (rev 2131)
+++ trunk/connectors/connector-text/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -43,9 +43,14 @@
}
public File[] getFiles(String location) {
- if (location == null) return null;
+ File datafile = null;
- File datafile = new File(parentDirectory, location);
+ if (location == null) {
+ datafile = this.parentDirectory;
+ }
+ else {
+ datafile = new File(parentDirectory, location);
+ }
if (datafile.isDirectory()) {
return datafile.listFiles();
Copied: trunk/connectors/translator-xml (from rev 2125, trunk/connectors/connector-xml)
Modified: trunk/connectors/translator-xml/pom.xml
===================================================================
--- trunk/connectors/connector-xml/pom.xml 2010-05-13 18:31:49 UTC (rev 2125)
+++ trunk/connectors/translator-xml/pom.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -8,15 +8,15 @@
<version>7.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
- <artifactId>connector-xml</artifactId>
+ <artifactId>translator-xml</artifactId>
<groupId>org.jboss.teiid.connectors</groupId>
- <name>XML Connector</name>
- <description>This connector produces the XML documents from Web
+ <name>XML Translator</name>
+ <description>This translator consumes the XML documents from Web
service and transforms the document into a relational structure.</description>
<dependencies>
<dependency>
<groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-connector-api</artifactId>
+ <artifactId>teiid-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
@@ -57,4 +57,4 @@
</dependency>
</dependencies>
-</project>
\ No newline at end of file
+</project>
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Constants.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Constants.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Constants.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,11 @@
+package org.teiid.translator.xml;
+
+public class Constants {
+
+ static public final String NAMESPACE_PREFIX_PROPERTY_NAME = "NamespacePrefixes"; //$NON-NLS-1$
+ static public final String SERVICE_NAME = "ServiceName"; //$NON-NLS-1$
+ static public final String SERVICE_NAMESPACE = "ServiceNamespace"; //$NON-NLS-1$
+ static public final String PORT_NAME = "PortName"; //$NON-NLS-1$
+ static public final String PORT_NAMESPACE = "PortNamespace"; //$NON-NLS-1$
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CriteriaDesc.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CriteriaDesc.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CriteriaDesc.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,473 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.teiid.language.BaseInCondition;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Condition;
+import org.teiid.language.Expression;
+import org.teiid.language.In;
+import org.teiid.language.LanguageUtil;
+import org.teiid.language.Literal;
+import org.teiid.language.Select;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.translator.TranslatorException;
+
+
+public class CriteriaDesc extends ParameterDescriptor {
+ // TODO: a lot of this is HTTP/SOAP specific (i.e., do not apply to files).
+ // There are various
+ // places that we work around that (extension properties being null),
+ // but it should be handled properly by moving the code into
+ // HTTP and SOAP specific places
+
+ // Describes an item in the parameter or criteria structure, and all the
+ // attributes of it
+ // Added to allow all the attributes of criteira to be managed in a single
+ // structure,
+ // and to make the code more manageable
+
+ private List m_values;
+
+ private int m_currentIndexInValuesList = 0;
+
+ private Boolean m_parentAttribute = null;
+
+ private Boolean m_enumeratedAttribute = null;
+
+ private Boolean m_allowEmptyValue = null;
+
+ private String m_dataAttributeName = null;
+
+ private Properties m_additionalAttributes = null;
+
+ private String m_inputXpath = null;
+
+ private String nativeType = null;
+
+ private boolean m_unlimited = false;
+
+ private boolean m_enumerated = false;
+
+ private boolean m_multiElement = false;
+
+ private boolean m_soapArrayElement = false;
+
+ private boolean m_simpleSoapElement;
+
+ public static final String PARM_REQUIRED_VALUE_COLUMN_PROPERTY_NAME = "RequiredValue"; //$NON-NLS-1$
+
+ public static final String PARM_ALLOWS_EMPTY_VALUES_COLUMN_PROPERTY_NAME = "AllowEmptyInputElement"; //$NON-NLS-1$
+
+ public static final String PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME = "MultipleValues"; //$NON-NLS-1$
+
+ public static final String PARM_HAS_MULTIPLE_VALUES_COMMA_DELIMITED_NAME = "CommaDelimited"; //$NON-NLS-1$
+
+ public static final String PARM_HAS_MULTIPLE_VALUES_MULTI_ELEMENT_NAME = "MultiElement"; //$NON-NLS-1$
+
+ public static final String PARM_IS_SIMPLE_SOAP_ARRAY_ELEMENT_NAME = "SimpleSoapArrayElement"; //$NON-NLS-1$
+
+ public static final String PARM_IS_COMPLEX_SOAP_ARRAY_ELEMENT_NAME = "ComplexSoapArrayElement"; //$NON-NLS-1$
+
+ public static final String PARM_XPATH_INPUT_COLUMN_PROPERTY_NAME = "XPathForInputParameter"; //$NON-NLS-1$
+
+ public static final String PARM_AS_PARENT_ATTRIBUTE_COLUMN_PROPERTY_NAME = "AttributeOfParent"; //$NON-NLS-1$
+
+ public static final String PARM_AS_NAMED_ATTRIBUTE_COLUMN_PROPERTY_NAME = "DataAttributeName"; //$NON-NLS-1$
+
+ //use static method do see if a criteria object needs to be created
+ public static CriteriaDesc getCriteriaDescForColumn(Column element,
+ Select query) throws TranslatorException {
+
+ CriteriaDesc retVal = null;
+ List values = parseCriteriaToValues(element, query);
+
+ if (values.size() == 0) {
+ if (testForParam(element)) {
+ //add default value to values if it exists
+ //throws exception if no default specified and its required
+ handleDefaultValue(element, values);
+ }
+ }
+ //values.size may have changed if default value was added above
+ //so we retest
+ if (values.size() > 0 || findAllowEmptyValue(element)) {
+ retVal = new CriteriaDesc(element, values);
+ retVal.setNativeType(element.getNativeType());
+ }
+ return retVal;
+ }
+
+ private static void handleDefaultValue(Column element, List values) throws TranslatorException {
+ Object defaultVal = element.getDefaultValue();
+ if (defaultVal != null) {
+ values.add(defaultVal);
+ } else if (findIsRequired(element)) {
+ throw new TranslatorException(
+ XMLPlugin.getString("CriteriaDesc.value.not.found.for.param") //$NON-NLS-1$
+ + element.getName());
+ }
+ }
+
+ private static boolean findIsRequired(Column element)
+ throws TranslatorException {
+ String value = element.getProperties().get(
+ PARM_REQUIRED_VALUE_COLUMN_PROPERTY_NAME);
+ return Boolean.valueOf(value);
+ }
+
+ private static boolean findAllowEmptyValue(Column element)
+ throws TranslatorException {
+ String value = element.getProperties().get(
+ PARM_ALLOWS_EMPTY_VALUES_COLUMN_PROPERTY_NAME);
+ return Boolean.valueOf(value);
+ }
+
+ /**
+ * @see com.metamatrix.server.datatier.SynchConnectorConnection#submitRequest(java.lang.Object)
+ */
+ public CriteriaDesc(Column myElement, List myValues)
+ throws TranslatorException {
+
+ super(myElement);
+ m_values = myValues;
+ final String enumerated = PARM_HAS_MULTIPLE_VALUES_COMMA_DELIMITED_NAME;
+ final String multiElement = PARM_HAS_MULTIPLE_VALUES_MULTI_ELEMENT_NAME;
+ String multiplicityStr = getElement().getProperties().get(
+ PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ if (multiplicityStr == null) {
+ multiplicityStr = ""; //$NON-NLS-1$
+ }
+ if (multiplicityStr.equals(enumerated)) {
+ m_unlimited = true;
+ m_enumerated = true;
+ } else if (multiplicityStr.equals(multiElement)) {
+ m_unlimited = true;
+ m_enumerated = false;
+ m_multiElement = true;
+ } else if (multiplicityStr.equals(PARM_IS_SIMPLE_SOAP_ARRAY_ELEMENT_NAME) ||
+ multiplicityStr.equals(PARM_IS_COMPLEX_SOAP_ARRAY_ELEMENT_NAME)) {
+ m_unlimited = true;
+ m_enumerated = false;
+ m_multiElement = true;
+ m_soapArrayElement = true;
+ if (multiplicityStr.equals(PARM_IS_SIMPLE_SOAP_ARRAY_ELEMENT_NAME)) {
+ m_simpleSoapElement = true;
+ } else {
+ m_simpleSoapElement = false;
+ }
+ } else {
+ m_unlimited = false;
+ m_enumerated = false;
+ }
+ }
+
+ private CriteriaDesc(CriteriaDesc other) {
+ //from ParameterDescriptor
+ setXPath(other.getXPath());
+ setIsParameter(other.isParameter());
+ setIsResponseId(other.isResponseId());
+ setIsLocation(other.isLocation());
+ setColumnName(String.valueOf(other.getColumnName()));
+ setColumnNumber(other.getColumnNumber());
+ setElement(other.getElement());
+ setNativeType(other.getNativeType());
+
+ m_parentAttribute = other.m_parentAttribute == null ? null : Boolean.valueOf(other.m_parentAttribute);
+ m_enumeratedAttribute = other.m_enumeratedAttribute == null ? null : Boolean.valueOf(other.m_enumeratedAttribute);
+ m_allowEmptyValue = other.m_allowEmptyValue == null ? null : Boolean.valueOf(other.m_allowEmptyValue);
+ m_dataAttributeName = other.m_dataAttributeName == null ? null : String.valueOf(other.m_dataAttributeName);
+ m_additionalAttributes = other.m_additionalAttributes == null ? null : new Properties(other.m_additionalAttributes);
+ m_inputXpath = other.m_inputXpath == null ? null : String.valueOf(other.m_inputXpath);
+ m_unlimited = other.m_unlimited;
+ m_enumerated = other.m_enumerated;
+ m_multiElement = other.m_multiElement;
+ m_soapArrayElement = other.m_soapArrayElement;
+ //don't copy the values
+ m_values = new ArrayList();
+ }
+
+ public String getInputXpath() throws TranslatorException {
+ if (m_inputXpath == null) {
+ findInputXPath();
+ }
+ return m_inputXpath;
+ }
+
+ private void findInputXPath() throws TranslatorException {
+ m_inputXpath = getElement().getProperties().get(PARM_XPATH_INPUT_COLUMN_PROPERTY_NAME);
+ if (m_inputXpath == null || m_inputXpath.trim().length() == 0) {
+ m_inputXpath = getColumnName();
+ }
+ }
+
+ public boolean isUnlimited() {
+ return m_unlimited;
+ }
+
+ public boolean isMultiElement() {
+ return m_multiElement;
+ }
+
+ public boolean isSOAPArrayElement() {
+ return m_soapArrayElement;
+ }
+
+ public boolean isAutoIncrement() throws TranslatorException {
+ return getElement().isAutoIncremented();
+ }
+
+ //from model extensions
+ public boolean isParentAttribute() throws TranslatorException {
+ if (m_parentAttribute == null) {
+ findParentAttribute();
+ }
+ return m_parentAttribute.booleanValue();
+ }
+
+ private void findParentAttribute() throws TranslatorException {
+ String value = getElement().getProperties()
+ .get(PARM_AS_PARENT_ATTRIBUTE_COLUMN_PROPERTY_NAME);
+ m_parentAttribute = Boolean.valueOf(value);
+ }
+
+ //from model extensions
+ public boolean isEnumeratedAttribute() throws TranslatorException {
+ return m_enumerated;
+ }
+
+ //from model extensions
+ public boolean allowEmptyValue() throws TranslatorException {
+
+ if (m_allowEmptyValue == null) {
+ findAllowEmptyValue();
+ }
+ return m_allowEmptyValue.booleanValue();
+ }
+
+ private void findAllowEmptyValue() throws TranslatorException {
+ String value = getElement().getProperties()
+ .get(PARM_ALLOWS_EMPTY_VALUES_COLUMN_PROPERTY_NAME);
+ m_allowEmptyValue = Boolean.valueOf(value);
+ }
+
+ //from model extensions
+ public boolean isDataInAttribute() throws TranslatorException {
+ String dataAttribute = getDataAttributeName();
+ if (dataAttribute.trim().length() == 0) {
+ return false;
+ }
+ return true;
+ }
+
+ //from model extensions
+ public String getDataAttributeName() throws TranslatorException {
+
+ if (m_dataAttributeName == null) {
+ findDataAttributeName();
+ }
+ return m_dataAttributeName;
+ }
+
+ private void findDataAttributeName() throws TranslatorException {
+ m_dataAttributeName = getElement().getProperties().get(
+ PARM_AS_NAMED_ATTRIBUTE_COLUMN_PROPERTY_NAME);
+ if (m_dataAttributeName == null) {
+ m_dataAttributeName = ""; //$NON-NLS-1$
+ }
+ }
+
+ public List getValues() {
+ return m_values;
+ }
+
+ public int getNumberOfValues() {
+ return m_values.size();
+ }
+
+ //This code manages the looping of parameters to make multiple server
+ // calls.
+ //The current index is used to get a value to be added to the parmString
+ public String getCurrentIndexValue() throws TranslatorException {
+ final int initialBufferSize = 1000;
+ if (m_values.size() == 0 && allowEmptyValue()) {
+ return ""; //$NON-NLS-1$
+ }
+ if (isEnumeratedAttribute()) {
+ StringBuffer sb = new StringBuffer(initialBufferSize);
+ String startChar = ""; //$NON-NLS-1$
+ for (int x = 0; x < m_values.size(); x++) {
+ sb.append(startChar);
+ sb.append(m_values.get(x));
+ startChar = ","; //$NON-NLS-1$
+ }
+ return sb.toString();
+ }
+ if (m_values.size() > 0) {
+ return (String) m_values.get(m_currentIndexInValuesList);
+ }
+ return null;
+ }
+ //if so, it is incremented
+ public boolean incrementIndex() throws TranslatorException {
+ if (isEnumeratedAttribute()) {
+ return false;
+ } else if (m_currentIndexInValuesList < m_values.size() - 1) {
+ m_currentIndexInValuesList++;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void resetIndex() {
+ m_currentIndexInValuesList = 0;
+ }
+
+ private static ArrayList parseCriteriaToValues(Column element, Select query) throws TranslatorException {
+
+ String fullName = element.getFullName().trim().toUpperCase();
+ ArrayList parmPair = new ArrayList();
+ if (element.getSearchType() == SearchType.Searchable
+ || element.getSearchType() == SearchType.All_Except_Like) {
+ // Check and set criteria for the IData input
+ Condition criteria = query.getWhere();
+ List<Condition> criteriaList = LanguageUtil.separateCriteriaByAnd(criteria);
+ for(Condition criteriaSeg: criteriaList) {
+ if (criteriaSeg instanceof Comparison) {
+ Comparison compCriteria = (Comparison) criteriaSeg;
+ if (compCriteria.getOperator() == Operator.EQ) {
+ Expression lExpr = compCriteria.getLeftExpression();
+ Expression rExpr = compCriteria.getRightExpression();
+ handleCompareCriteria(lExpr, rExpr, fullName, parmPair);
+ }
+ } else if (criteriaSeg instanceof BaseInCondition) {
+ handleInCriteria((BaseInCondition) criteriaSeg, fullName, parmPair);
+
+ }
+ }
+ }
+ return parmPair;
+ }
+
+ private static void handleInCriteria(BaseInCondition baseInCriteria, String fullName, ArrayList parmPair) {
+ Expression expr = baseInCriteria.getLeftExpression();
+ if (expr instanceof ColumnReference) {
+ if (nameMatch(expr, fullName)) {
+ Iterator vIter = null;
+
+ vIter = ((In) baseInCriteria).getRightExpressions().iterator();
+ while (vIter.hasNext()) {
+ Literal val = (Literal) vIter.next();
+ String constantValue = val.getValue()
+ .toString();
+ constantValue = stringifyCriteria(constantValue);
+ parmPair.add(constantValue);
+ }
+ }
+ }
+ }
+
+ private static void handleCompareCriteria(Expression lExpr, Expression rExpr, String fullName, ArrayList parmPair) {
+ checkElement(lExpr, rExpr, fullName, parmPair);
+ checkElement(rExpr, lExpr, fullName, parmPair);
+ }
+
+ private static void checkElement(Expression expression, Expression literalCandidate, String fullName, ArrayList parmPair) {
+ if (expression instanceof ColumnReference) {
+ if ((nameMatch(expression, fullName))
+ && (literalCandidate instanceof Literal)) {
+ String constantValue = ((Literal) literalCandidate)
+ .getValue().toString();
+ constantValue = stringifyCriteria(constantValue);
+ parmPair.add(constantValue);
+ }
+ }
+ }
+
+ public static boolean nameMatch(Expression expr, String elementName) {
+ ColumnReference exprElement = (ColumnReference) expr;
+ String symbolName = exprElement.getName().toUpperCase().trim();
+ String tempElementName = elementName.toUpperCase();
+ int indx = symbolName.lastIndexOf("."); //$NON-NLS-1$
+ //. has to be there
+ symbolName = symbolName.substring(indx + 1);
+ indx = elementName.lastIndexOf("."); //$NON-NLS-1$
+ //. has to be there
+ tempElementName = tempElementName.substring(indx + 1);
+ return symbolName.equals(tempElementName);
+ }
+
+ public static String stringifyCriteria(String startCriteria) {
+ int indx = 0;
+ String cStr = startCriteria;
+ indx = cStr.indexOf("'"); //$NON-NLS-1$
+ if (indx == 0) {
+ int indx2 = cStr.substring(1).indexOf("'"); //$NON-NLS-1$
+ if (indx2 >= 0) {
+ return cStr.substring(1, indx2 + 1);
+ }
+ }
+ indx = cStr.indexOf('"');
+ if (indx == 0) {
+ int indx2 = cStr.substring(1).indexOf('"');
+ if (indx2 > 0) {
+ return cStr.substring(1, indx2 + 1);
+ }
+ }
+ return cStr;
+ }
+
+ public CriteriaDesc cloneWithoutValues() {
+ CriteriaDesc newDesc = new CriteriaDesc(this);
+ return newDesc;
+ }
+
+ public void setValue(int i, Object object) {
+ if(m_values.size() <= i) {
+ m_values.add(i, object);
+ } else {
+ m_values.set(i, object);
+ }
+ }
+
+ private void setNativeType(String nativeType) {
+ this.nativeType = nativeType;
+ }
+
+ public String getNativeType() {
+ return nativeType;
+ }
+
+ public boolean isSimpleSoapElement() {
+ return m_simpleSoapElement;
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Document.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Document.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/Document.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,12 @@
+package org.teiid.translator.xml;
+
+import java.io.InputStream;
+import java.sql.SQLException;
+
+public interface Document {
+
+ public InputStream getStream() throws SQLException;
+
+ public String getCachekey();
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/DocumentBuilder.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/DocumentBuilder.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/DocumentBuilder.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,526 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+import org.jdom.Attribute;
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.IllegalNameException;
+import org.jdom.Namespace;
+import org.jdom.output.XMLOutputter;
+import org.teiid.translator.TranslatorException;
+
+
+public class DocumentBuilder {
+
+ public static final String PARM_INPUT_XPATH_TABLE_PROPERTY_NAME = "XPathRootForInput"; //$NON-NLS-1$
+ public static final String ENCODING_STYLE_URL = "http://schemas.xmlsoap.org/soap/encoding/"; //$NON-NLS-1$
+
+ private Map m_namespaceMap;
+
+ private boolean m_useTypeAttributes;
+
+ public DocumentBuilder() {
+ m_namespaceMap = new HashMap();
+ m_useTypeAttributes = false;
+ }
+
+ private Map getNamespaces() {
+ return m_namespaceMap;
+ }
+
+ public String buildDocumentString(List contents, String topLevelXPath,
+ String nsDecl) throws TranslatorException {
+ Document doc = buildDocument(contents, topLevelXPath, nsDecl);
+ return outputDocToString(doc);
+ }
+
+ public Document buildDocument(List contents, String topLevelXPath, String nsDecl) throws TranslatorException {
+ Document doc = null;
+ setNamespaces(nsDecl);
+ // assemble table-level elements
+ org.jdom.Element curElement = null;
+ try {
+ curElement = makeElement(curElement, topLevelXPath, false);
+ } catch(IllegalNameException ex) {
+ throw new TranslatorException(topLevelXPath + " is not a valid XPath for the root request node." + "Change the Request table " + PARM_INPUT_XPATH_TABLE_PROPERTY_NAME);
+ }
+ if (curElement == null) {
+ throw new TranslatorException(XMLPlugin.getString("HTTPExecutor.root.element.required")); //$NON-NLS-1$
+ }
+ doc = makeTableLevelElements(curElement);
+
+ // loop through each parameter
+ processParameters(contents, curElement);
+
+ // add all of the namespaces
+ Element nsHolder = doc.getRootElement();
+ addAllNamespaces(nsHolder);
+
+ return doc;
+ }
+
+ private void addAllNamespaces(Element nsHolder) {
+ Map namespaceMap = getNamespaces();
+ Iterator nsIter = namespaceMap.values().iterator();
+ while (nsIter.hasNext()) {
+ nsHolder.addNamespaceDeclaration((Namespace) nsIter.next());
+ }
+ }
+
+ private Document makeTableLevelElements(Element curElement)
+ throws TranslatorException {
+
+ // this walks up from the current node to the root, so the root can be
+ // assigned to a document
+ Element walkupElement = curElement;
+ Element parentElement;
+ // why is this failing?
+ // could be due to incompatibilities with core jdom version
+ // and the one the connector uses
+ while ((parentElement = (Element) walkupElement.getParent()) != null) {
+ walkupElement = parentElement;
+ }
+ Document document = new Document(walkupElement);
+ return document;
+ }
+
+ private void setNamespaces(String nsDecl) throws TranslatorException {
+ if (nsDecl != null && nsDecl.trim().length() > 0) {
+ String[] nsPairs = nsDecl.trim().replace('\"', '\0').replace('\'',
+ '\0').split("xmlns"); //$NON-NLS-1$
+ // the first entry will be blank since the string starts with the
+ // delimiter
+ for (int i = 1; i < nsPairs.length; i++) {
+ // remove the ':'
+ if (nsPairs[i].startsWith(":"))
+ nsPairs[i] = nsPairs[i].substring(1);
+ String[] nsSplit = nsPairs[i].split("="); //$NON-NLS-1$
+ if (nsSplit.length != 2) {
+ throw new TranslatorException(
+ XMLPlugin
+ .getString("DocumentBuilder.could.not.parse.namespaces")); //$NON-NLS-1$
+ }
+ Namespace ns = Namespace.getNamespace(nsSplit[0].trim(),
+ nsSplit[1].trim());
+ m_namespaceMap.put(nsSplit[0], ns);
+ }
+ }
+ }
+
+ private Element makeElement(Element colElement, String inputXPath,
+ boolean dupLastElement) throws TranslatorException {
+ if (inputXPath == null || inputXPath.trim().length() == 0) {
+ return colElement;
+ }
+ Element tempElement = colElement;
+ String tempXPath = inputXPath.trim();
+ tempElement = visitXPath(colElement, tempXPath, dupLastElement);
+ return tempElement;
+ }
+
+ private Element visitXPath(Element elem, String tempXPath,
+ boolean dupLastElement) throws TranslatorException {
+ // loop through, searching for path seperators
+ int startParmIndx = 0;
+ int endParmIndx = tempXPath.indexOf("/", startParmIndx); //$NON-NLS-1$
+ int endOfTempXPath = tempXPath.length() - 1;
+ while (endParmIndx >= 0 && endParmIndx < endOfTempXPath) {
+ elem = setElement(elem, tempXPath, startParmIndx, endParmIndx);
+ startParmIndx = endParmIndx + 1;
+ endParmIndx = checkForIndexEnd(tempXPath, startParmIndx);
+ }
+ String finalXpath = getFinalXPath(tempXPath, startParmIndx, endParmIndx);
+ if (finalXpath != null) {
+ elem = addOneElement(elem, finalXpath, dupLastElement);
+ }
+ return elem;
+
+ }
+
+ private int checkForIndexEnd(String tempXPath, int startParmIndx) {
+ int endParmIndx;
+ if (startParmIndx < tempXPath.length() - 1) {
+ endParmIndx = tempXPath.indexOf("/", startParmIndx); //$NON-NLS-1$
+ } else {
+ endParmIndx = -1;
+ }
+ return endParmIndx;
+ }
+
+ private String getFinalXPath(String tempXPath, int startParmIndx,
+ int endParmIndx) {
+ String finalXpath = null;
+ if (endParmIndx > 0) {
+ finalXpath = tempXPath.substring(startParmIndx, endParmIndx);
+ } else {
+ if (startParmIndx <= tempXPath.length() - 1) {
+ finalXpath = tempXPath.substring(startParmIndx);
+ }
+ }
+ return finalXpath;
+ }
+
+ private Element setElement(Element element, String tempXPath,
+ int startParmIndx, int endParmIndx) throws TranslatorException {
+ Element tempElement = element;
+ if (endParmIndx > 0) {
+ String tempXP = tempXPath.substring(startParmIndx, endParmIndx);
+ if (tempXP.indexOf("..") >= 0) { //$NON-NLS-1$
+ throw new TranslatorException(XMLPlugin
+ .getString("HTTPExecutor.dot.notation.not.allowed")); //$NON-NLS-1$
+ }
+
+ if (tempXP != null && tempXP.trim().length() > 0) {
+ tempElement = addOneElement(tempElement, tempXP, false);
+ }
+ }
+ return tempElement;
+ }
+
+ private void processParameters(List<CriteriaDesc> params, Element curElement)
+ throws TranslatorException {
+
+ for(CriteriaDesc parmCriteria: params) {
+ try {
+ boolean isAutoIncrement = parmCriteria.isAutoIncrement();
+ createParameterXML(curElement, parmCriteria, isAutoIncrement);
+ } catch (Exception ex) {
+ throw new TranslatorException(XMLPlugin
+ .getString("HTTPExecutor.error.building.column") //$NON-NLS-1$
+ + parmCriteria.getColumnName() + ": " + ex.toString()); //$NON-NLS-1$
+ }
+ }
+
+ }
+
+ private void createParameterXML(Element curElement,
+ CriteriaDesc parmCriteria, boolean isAutoIncrement)
+ throws TranslatorException {
+ if (parmCriteria.isParentAttribute()) {
+ // add parameter as attribute of connector
+ curElement.setAttribute(parmCriteria.getInputXpath(), parmCriteria
+ .getCurrentIndexValue());
+ } else if (parmCriteria.isUnlimited()
+ && !parmCriteria.isEnumeratedAttribute()) {
+ // add parameter as mutliple elements
+ createMultipleElementXML(curElement, parmCriteria, isAutoIncrement);
+ } else {
+ createSingleElementXML(curElement, parmCriteria, isAutoIncrement);
+ }
+
+ }
+
+ private void createSingleElementXML(Element curElement,
+ CriteriaDesc parmCriteria, boolean isAutoIncrement)
+ throws TranslatorException {
+ org.jdom.Element colElement = null;
+ if (parmCriteria.isDataInAttribute()) {
+ // add parameter as an element and an attribute in the
+ // element
+ colElement = makeElement(curElement, parmCriteria.getInputXpath(),
+ false);
+ String attName = parmCriteria.getDataAttributeName();
+ String namePart = getNamePart(attName);
+ String nsPart = getNamespacePart(attName);
+ Namespace attNS = Namespace.NO_NAMESPACE;
+ if (nsPart != null) {
+ attNS = (Namespace) m_namespaceMap.get(nsPart);
+ colElement.setAttribute(namePart, parmCriteria
+ .getCurrentIndexValue(), attNS);
+ } else {
+ colElement.setAttribute(attName, parmCriteria
+ .getCurrentIndexValue());
+ }
+ } else {
+ // add parameter as a new element
+ colElement = makeElement(curElement, parmCriteria.getInputXpath(),
+ false);
+ colElement.addContent(parmCriteria.getCurrentIndexValue());
+ }
+ if (isAutoIncrement) {
+ String subscrValue = "[0]"; //$NON-NLS-1$
+ colElement.setAttribute("SUBSCR", subscrValue); //$NON-NLS-1$
+ }
+
+ if (useTypeAttributes()) {
+ // if there is a native type in the model use it, otherwise
+ // if 5.0 or later, derive from the data type
+ String xsdType = parmCriteria.getElement().getNativeType();
+ if (xsdType == null) {
+ // attempt use the data type
+ // this method call does not exist before 5.0 so we have to
+ // check for it before we call it.
+ try {
+ Method method = parmCriteria.getElement().getClass()
+ .getMethod("getModeledType", new Class[] {});
+ String type = parmCriteria.getElement().getDatatypeID();
+ String nsPart = type.substring(0, type.indexOf('#'));
+ String namePart = type.substring(type.indexOf('#') + 1);
+ Iterator nsIter = getNamespaces().values().iterator();
+ String prefix = null;
+ while (nsIter.hasNext()) {
+ Namespace ns = (Namespace) nsIter.next();
+ if (ns.getURI().equals(nsPart))
+ prefix = ns.getPrefix();
+ }
+ if (prefix == null) {
+ int prefixInt = 0;
+ while (getNamespaces().get("ns" + prefixInt) != null) {
+ ++prefixInt;
+ }
+ prefix = "ns" + prefixInt;
+ Namespace newNS = Namespace
+ .getNamespace(prefix, nsPart);
+ getNamespaces().put(prefix, newNS);
+ }
+ xsdType = prefix + ":" + namePart;
+ } catch (NoSuchMethodException nme) {
+ throw new TranslatorException(
+ "column "
+ + colElement.getName()
+ + XMLPlugin
+ .getString("DocumentBuilder.encoding.type.required"));
+ }
+ }
+ final String xsiType = "type"; //$NON-NLS-1$
+ final String xsiNS = "http://www.w3.org/1999/XMLSchema-instance"; //$NON-NLS-1$
+ final String xsiPrefix = "xsi"; //$NON-NLS-1$
+ Attribute type = new Attribute(xsiType, xsdType, Namespace
+ .getNamespace(xsiPrefix, xsiNS));
+ colElement.setAttribute(type);
+ }
+ }
+
+ /**
+ *
+ */
+ private void createMultipleElementXML(Element curElement,
+ CriteriaDesc parmCriteria, boolean isAutoIncrement)
+ throws TranslatorException {
+ if(parmCriteria.isSOAPArrayElement()) {
+ createSOAPArrayElement(curElement, parmCriteria);
+ } else {
+ parmCriteria.resetIndex();
+ boolean moreParms = true;
+ boolean isDataInAttribute = parmCriteria.isDataInAttribute();
+ String inputXpath = parmCriteria.getInputXpath();
+ for (int x = 0; moreParms; x++) {
+ org.jdom.Element colElement = makeElement(curElement, inputXpath,
+ true);
+ if (isAutoIncrement) {
+ String subscrValue = "[" + Integer.toString(x) //$NON-NLS-1$
+ + "]"; //$NON-NLS-1$
+ colElement.setAttribute("SUBSCR", subscrValue); //$NON-NLS-1$
+ }
+ if (isDataInAttribute) {
+ colElement.setAttribute(parmCriteria.getDataAttributeName(),
+ parmCriteria.getCurrentIndexValue());
+ } else {
+ colElement.setText(parmCriteria.getCurrentIndexValue());
+ }
+ moreParms = parmCriteria.incrementIndex();
+ }
+ }
+ }
+
+ private void createSOAPArrayElement(Element curElement, CriteriaDesc parmCriteria) throws TranslatorException {
+
+ /*
+ * loop over the values in the criteriaDesc and create <item> nodes containing them
+ *
+ * get the imformation for the soapArray element out of the criteriaDesc's
+ * nativeType property and create the attributes including the number of items.
+ *
+ *
+ */
+ String inputXpath = parmCriteria.getInputXpath();
+ curElement = visitXPath(curElement, inputXpath, false);
+
+ parmCriteria.resetIndex();
+ boolean moreParms = true;
+
+ String nativeTypeInfo = parmCriteria.getNativeType();
+ StringTokenizer tokenizer = new StringTokenizer(nativeTypeInfo, ";");
+ String xsdTypeString = tokenizer.nextToken();
+
+ int start,end;
+ start = xsdTypeString.indexOf("\"");
+ end = xsdTypeString.indexOf("\"", start +1);
+ String xsdTypeValue = xsdTypeString.substring(start +1, end);
+
+ String arrayType = tokenizer.nextToken();
+ start = arrayType.indexOf("\"");
+ end = arrayType.indexOf("\"", start +1);
+ String arrayTypeValue = arrayType.substring(start +1, end);
+
+ end = arrayType.indexOf(":");
+ String soapEncodingPrefix = arrayType.substring(0, end);
+
+ String arrayNamespace = tokenizer.nextToken();
+ start = arrayNamespace.indexOf(":");
+ end = arrayNamespace.indexOf("=", start +1);
+ start = arrayNamespace.indexOf("\"");
+ arrayTypeValue = arrayTypeValue + "[" + parmCriteria.getNumberOfValues() + "]";
+
+
+ if(!parmCriteria.isSimpleSoapElement()) {
+ Element arrayElement = curElement.getParentElement();
+ //See if we have already added the attributes to the array from
+ //an earlier array element.
+ if(null == arrayElement.getAttribute("type", Namespace.XML_NAMESPACE)) {
+ arrayElement.setAttribute("type", xsdTypeValue, Namespace.XML_NAMESPACE);
+ Namespace soapEncodingNamespace = Namespace.getNamespace(soapEncodingPrefix, ENCODING_STYLE_URL);
+ arrayElement.setAttribute("arrayType", arrayTypeValue, soapEncodingNamespace);
+ }
+ curElement.detach();
+ org.jdom.Element itemElement = arrayElement.getChild("item");
+ if(null == itemElement) {
+ itemElement = makeElement(arrayElement, "item", true);
+ }
+ itemElement.addContent(curElement);
+ curElement.setText(parmCriteria.getCurrentIndexValue());
+
+ } else {
+ //See if we have already added the attributes to the array from
+ //an earlier array element.
+ if(null == curElement.getAttribute("type", Namespace.XML_NAMESPACE)) {
+ curElement.setAttribute("type", xsdTypeValue, Namespace.XML_NAMESPACE);
+ Namespace soapEncodingNamespace = Namespace.getNamespace(soapEncodingPrefix, ENCODING_STYLE_URL);
+ curElement.setAttribute("arrayType", arrayTypeValue, soapEncodingNamespace);
+ }
+
+ for (int x = 0; moreParms; x++) {
+ org.jdom.Element itemElement = makeElement(curElement, "item", true);
+ itemElement.setText(parmCriteria.getCurrentIndexValue());
+ moreParms = parmCriteria.incrementIndex();
+ }
+ }
+ }
+
+ private Element addOneElement(org.jdom.Element colElement,
+ String inputXPath, boolean allowDup) throws TranslatorException {
+
+ // Create element namespace if needed and use in the get Child and
+ // Element ctor
+ String tempXPath = inputXPath.trim();
+ String elementName = getElementName(tempXPath);
+ String nsPart = getNamespacePart(elementName);
+ String namePart = getNamePart(elementName);
+ Namespace elemNS = Namespace.NO_NAMESPACE;
+ if (nsPart != null) {
+ elemNS = (Namespace) getNamespaces().get(nsPart);
+ }
+
+ org.jdom.Element childElement = null;
+ if (colElement != null && !allowDup) {
+ childElement = colElement.getChild(namePart, elemNS);
+ }
+
+ // element does not already exist, create it
+ if (childElement == null) {
+ childElement = new Element(namePart, elemNS);
+ // add new element to connector
+ if (colElement != null) {
+ colElement.addContent(childElement);
+ }
+ }
+
+ addAttributes(childElement, tempXPath);
+ return childElement;
+ }
+
+ private String getNamespacePart(String elemName) {
+ int colonIndex = elemName.indexOf(':');
+ if (colonIndex < 0) {
+ return null;
+ }
+ return elemName.substring(0, colonIndex);
+ }
+
+ private String getNamePart(String elemName) {
+ int colonIndex = elemName.indexOf(':');
+ if (colonIndex < 0) {
+ return elemName;
+ }
+ return elemName.substring(colonIndex + 1);
+ }
+
+ private void addAttributes(Element childElement, String tempXPath)
+ throws TranslatorException {
+ // add attribute definitions
+ int startAttIndx = tempXPath.indexOf("["); //$NON-NLS-1$
+ while (startAttIndx > 0) {
+ int equalIndx = tempXPath.indexOf("=", startAttIndx); //$NON-NLS-1$
+ int endAttIndx = tempXPath.indexOf("]", startAttIndx); //$NON-NLS-1$
+ if (equalIndx > 0 && equalIndx < endAttIndx) {
+ String attName = tempXPath.substring(startAttIndx + 1,
+ equalIndx);
+ String namePart = getNamePart(attName);
+ String nsPart = getNamespacePart(attName);
+ Namespace attNS = Namespace.NO_NAMESPACE;
+ if (nsPart != null) {
+ attNS = (Namespace) m_namespaceMap.get(nsPart);
+ }
+ String attValue = tempXPath
+ .substring(equalIndx + 1, endAttIndx);
+ childElement.setAttribute(namePart, attValue, attNS);
+ } else {
+ throw new TranslatorException(XMLPlugin
+ .getString("HTTPExecutor.bad.attribute.def")); //$NON-NLS-1$
+ }
+ startAttIndx = tempXPath.indexOf("[", endAttIndx); //$NON-NLS-1$
+ }
+ }
+
+ private String getElementName(String tempXPath) {
+ String elementName;
+ int startAttIndx = tempXPath.indexOf("["); //$NON-NLS-1$
+ if (startAttIndx > 0) {
+ elementName = tempXPath.substring(0, startAttIndx).trim();
+ } else {
+ elementName = tempXPath;
+ }
+ return elementName;
+ }
+
+ public static String outputDocToString(Document doc) {
+ XMLOutputter out = new XMLOutputter();
+ return out.outputString(doc).trim();
+ }
+
+ public void setUseTypeAttributes(boolean m_useTypeAttributes) {
+ this.m_useTypeAttributes = m_useTypeAttributes;
+ }
+
+ private boolean useTypeAttributes() {
+ return m_useTypeAttributes;
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ExecutionInfo.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ExecutionInfo.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ExecutionInfo.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,205 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.jdom.Document;
+import org.jdom.Element;
+import org.jdom.JDOMException;
+import org.jdom.Namespace;
+import org.jdom.input.SAXBuilder;
+import org.teiid.translator.TranslatorException;
+
+
+public class ExecutionInfo {
+// TODO:Refactor. This class was defined when the multiple reqests to an XML service
+// (read HTTP) to satisfy an IN clause were abstacted beneath a single call to Executor.getResult().
+// This case is now satified within the execute call by making a single call to Executor.getResult()
+// for each paramter of the IN clause.
+
+ private List columns;
+ private int columnCount;
+ private List<CriteriaDesc> params;
+ private List<CriteriaDesc> criteria;
+ private Map<String, String> otherProps;
+ private String tablePath;
+ private String location;
+ private Map<String, String> prefixToNamespace;
+ private Map<String, String> namespaceToPrefix;
+
+ public ExecutionInfo() {
+ this.columnCount = 0;
+ this.columns = new ArrayList();
+ this.params = new ArrayList<CriteriaDesc>();
+ this.criteria = new ArrayList<CriteriaDesc>();
+ this.otherProps = new HashMap<String, String>();
+ this.tablePath = ""; //$NON-NLS-1$
+ }
+
+
+ public String getTableXPath() {
+ return this.tablePath;
+ }
+
+ public String getLocation() {
+ return this.location;
+ }
+
+ public List getRequestedColumns() {
+ return this.columns;
+ }
+
+
+ public int getColumnCount() {
+ return this.columnCount;
+ }
+
+
+ public List<CriteriaDesc> getParameters() {
+ return this.params;
+ }
+
+
+ public List<CriteriaDesc> getCriteria() {
+ return this.criteria;
+ }
+
+
+ public Map<String, String> getOtherProperties() {
+ return this.otherProps;
+ }
+
+ public void setTableXPath(String path) {
+ if (path == null || path.trim().length() == 0) {
+ this.tablePath = null;
+ } else {
+ this.tablePath = path;
+ }
+ }
+
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ public void setRequestedColumns(List value) {
+ this.columns = value;
+ }
+
+
+ public void setColumnCount(int count) {
+ this.columnCount = count;
+ }
+
+
+ public void setParameters(List<CriteriaDesc> parameters) {
+ this.params = parameters;
+ }
+
+
+ public void setCriteria(List<CriteriaDesc> criteria) {
+ this.criteria = criteria;
+ }
+
+
+ public void setOtherProperties(Map<String, String> props) {
+ if (props == null) {
+ this.otherProps = new HashMap<String, String>();
+ } else {
+ this.otherProps = props;
+ }
+ }
+
+ // It is not enforced that there is only one ResponseId in the parameters, but it is
+ // a valid assumption and the modelgenerators will never create a model that has more
+ // than one. We could enforce this with a real metamodel.
+ public CriteriaDesc getResponseIDCriterion() {
+ CriteriaDesc result = null;
+ Iterator iter = this.params.iterator();
+ while(iter.hasNext()) {
+ CriteriaDesc criterion = (CriteriaDesc)iter.next();
+ if(criterion.isResponseId()) {
+ result = criterion;
+ break;
+ }
+ }
+ return result;
+ }
+
+ public Map<String, String> getNamespaceToPrefixMap() throws TranslatorException {
+ if(this.namespaceToPrefix != null) {
+ return this.namespaceToPrefix;
+ }
+ getPrefixToNamespacesMap();
+ return this.namespaceToPrefix;
+ }
+
+ public Map<String, String> getPrefixToNamespacesMap() throws TranslatorException {
+ if (this.prefixToNamespace != null) {
+ return this.prefixToNamespace;
+ }
+
+ this.prefixToNamespace = new HashMap<String, String>();
+ this.namespaceToPrefix = new HashMap<String, String>();
+ String namespacePrefixes = getOtherProperties().get(Constants.NAMESPACE_PREFIX_PROPERTY_NAME);
+ if (namespacePrefixes == null || namespacePrefixes.trim().length() == 0) {
+ return null;
+ }
+ String prefix = null;
+ String uri = null;
+ try {
+ String xml = "<e " + namespacePrefixes + "/>"; //$NON-NLS-1$ //$NON-NLS-2$
+ Reader reader = new StringReader(xml);
+ SAXBuilder builder = new SAXBuilder();
+ Document domDoc = builder.build(reader);
+ Element elem = domDoc.getRootElement();
+ List namespaces = elem.getAdditionalNamespaces();
+ for (Iterator iter = namespaces.iterator(); iter.hasNext();) {
+ Object o = iter.next();
+ Namespace namespace = (Namespace) o;
+ prefix = namespace.getPrefix();
+ uri = namespace.getURI();
+ this.prefixToNamespace.put(prefix, uri);
+ this.namespaceToPrefix.put(uri, prefix);
+ }
+ } catch (JDOMException e) {
+ String rawMsg = XMLPlugin.getString("Executor.jaxen.error.on.namespace.pairs"); //$NON-NLS-1$
+ Object[] objs = new Object[2];
+ objs[0] = prefix;
+ objs[1] = uri;
+ String msg = MessageFormat.format(rawMsg, objs);
+ throw new TranslatorException(e, msg);
+ } catch (IOException e) {
+ throw new TranslatorException(e, e.getMessage());
+ }
+ return this.prefixToNamespace;
+ }
+}
Copied: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileProcedureExecution.java (from rev 2125, trunk/connectors/connector-xml-file/src/main/java/org/teiid/connector/xml/file/FileProcedureExecution.java)
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileProcedureExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileProcedureExecution.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,123 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLXML;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.language.Call;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.FileConnection;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.TranslatorException;
+
+
+/**
+ * Execution class for File based XML Source.
+ */
+public class FileProcedureExecution implements ProcedureExecution {
+
+ private Call procedure;
+ private XMLExecutionFactory executionFactory;
+ private boolean returnedResult;
+ private SQLXML returnValue;
+ private FileConnection connection;
+
+ /**
+ * @param env
+ * @param conn
+ * @param context
+ * @param metadata
+ */
+ public FileProcedureExecution(Call proc, XMLExecutionFactory executionFactory, FileConnection connection) {
+ this.procedure = proc;
+ this.executionFactory = executionFactory;
+ this.connection = connection;
+ }
+
+ /**
+ * @see org.teiid.connector.api.ProcedureExecution#execute(org.teiid.connector.language.Call, int)
+ */
+ @Override
+ public void execute() throws TranslatorException {
+
+ // look for the name of the file to return in the metadata, "Name in Source" property
+ AbstractMetadataRecord metaObject = procedure.getMetadataObject();
+ String fileName = metaObject.getNameInSource();
+
+ // if the source procedure name is not supplied then throw an exception
+ if (fileName == null || fileName.length() == 0) {
+ throw new TranslatorException(XMLPlugin.Util.getString("source_name_not_supplied", new Object[] {procedure.getProcedureName()})); //$NON-NLS-1$
+ }
+
+ final File[] files = this.connection.getFiles(fileName);
+ if (files.length == 0 || !files[0].exists()) {
+ throw new TranslatorException(XMLPlugin.Util.getString("file_not_supplied", new Object[] {fileName, procedure.getProcedureName()})); //$NON-NLS-1$
+ }
+
+ String encoding = this.executionFactory.getCharacterEncodingScheme();
+
+ returnValue = new SQLXMLImpl(new InputStreamFactory(encoding) {
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return new BufferedInputStream(new FileInputStream(files[0]));
+ }
+ });
+
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, XMLPlugin.Util.getString("executing_procedure", new Object[] {procedure.getProcedureName()})); //$NON-NLS-1$
+ }
+
+ @Override
+ public List<?> next() throws TranslatorException, DataNotAvailableException {
+ if (!returnedResult) {
+ returnedResult = true;
+ return Arrays.asList(returnValue);
+ }
+ return null;
+ }
+
+ @Override
+ public List<?> getOutputParameterValues() throws TranslatorException {
+ throw new TranslatorException(XMLPlugin.Util.getString("No_outputs_allowed")); //$NON-NLS-1$
+ }
+
+ public void close() throws TranslatorException {
+ // no-op
+ }
+
+ public void cancel() throws TranslatorException {
+ // no-op
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileProcedureExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,159 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.translator.xml;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.language.Select;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.FileConnection;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.streaming.DocumentImpl;
+import org.teiid.translator.xml.streaming.InvalidPathException;
+import org.teiid.translator.xml.streaming.StreamingResultsProducer;
+import org.teiid.translator.xml.streaming.XPathSplitter;
+
+public class FileResultSetExecution implements ResultSetExecution {
+ public static final String PARM_FILE_NAME_TABLE_PROPERTY_NAME = "FileName"; //$NON-NLS-1$
+
+ private ExecutionInfo executionInfo;
+ private int docNumber = 0;
+ private File[] content;
+ private XMLExecutionFactory executionFactory;
+ private List<Document> resultDocuments = null;
+ private StreamingResultsProducer streamProducer;
+ private List<Object[]> currentRowSet;
+ private int currentRow = 0;
+
+
+ public FileResultSetExecution(Select query, XMLExecutionFactory executionFactory, FileConnection connection) throws TranslatorException {
+
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ this.executionInfo = analyzer.getExecutionInfo();
+
+ String tableName = this.executionInfo.getLocation();
+ if (tableName == null) {
+ tableName = this.executionInfo.getOtherProperties().get(PARM_FILE_NAME_TABLE_PROPERTY_NAME);
+ }
+
+ this.content = connection.getFiles(tableName);
+
+ validateParams();
+ List<CriteriaDesc[]> requestPerms = analyzer.getRequestPerms();
+
+ if (requestPerms.size() > 1) {
+ throw new AssertionError("The QueryAnalyzer produced > 1 request permutation"); //$NON-NLS-1$
+ }
+
+ List<CriteriaDesc> criteriaList = Arrays.asList(requestPerms.get(0));
+ this.executionInfo.setParameters(criteriaList);
+ this.executionFactory = executionFactory;
+ this.streamProducer = new StreamingResultsProducer(this.executionInfo, this.executionFactory.getSaxFilterProvider());
+ }
+
+ /**
+ * Validates that the query can be supported. Probably better suited to a call out from QueryAnalyzer.
+ * @throws ConnectorException
+ */
+ private void validateParams() throws TranslatorException {
+ for (int i = 0; i < this.executionInfo.getRequestedColumns().size(); i++) {
+ OutputXPathDesc xPath = (OutputXPathDesc)this.executionInfo.getRequestedColumns().get(i);
+ if (xPath.isParameter()) {
+ throw new TranslatorException(XMLPlugin.getString("FileExecutor.input.not.supported.on.files")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ @Override
+ public void execute() throws TranslatorException {
+ if (this.content != null) {
+ this.resultDocuments = new ArrayList<Document>();
+ int i = 0;
+ for(File f:this.content) {
+ this.resultDocuments.add(getDocumentStream(f, i++));
+ }
+ }
+ }
+
+ @Override
+ public List<?> next() throws TranslatorException, DataNotAvailableException {
+ if (this.currentRowSet == null) {
+ while(this.docNumber < resultDocuments.size()) {
+ this.currentRowSet = streamProducer.getResult(this.resultDocuments.get(this.docNumber++), getXPaths());
+ this.currentRow = 0;
+ if (this.currentRowSet.isEmpty()) {
+ continue;
+ }
+ }
+ }
+
+ if (this.currentRowSet != null) {
+ if (this.currentRow <= this.currentRowSet.size()) {
+ List result = Arrays.asList(this.currentRowSet.get(this.currentRow++));
+ if(this.currentRow == this.currentRowSet.size()) {
+ this.currentRowSet = null;
+ }
+ return result;
+ }
+ }
+ return null;
+ }
+
+ private List<String> getXPaths() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ return splitter.split(this.executionInfo.getTableXPath());
+ } catch (InvalidPathException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ private Document getDocumentStream(final File xmlFile, int fileNumber) {
+ InputStreamFactory isf = new InputStreamFactory() {
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return new BufferedInputStream(new FileInputStream(xmlFile));
+ }
+ };
+ return new DocumentImpl(this.executionFactory.convertToXMLType(isf), xmlFile.getName()+fileNumber);
+ }
+
+ @Override
+ public void cancel() throws TranslatorException {
+
+ }
+
+ @Override
+ public void close() throws TranslatorException {
+
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/IDGeneratingXmlFilter.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/IDGeneratingXmlFilter.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/IDGeneratingXmlFilter.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,154 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+import org.xml.sax.helpers.XMLFilterImpl;
+
+
+public class IDGeneratingXmlFilter extends XMLFilterImpl
+{
+ protected static class PathElement
+ {
+ protected PathElement(String name, int index)
+ {
+ this.name = name;
+ this.index = index;
+ predecessorCounts = new HashMap();
+ }
+ protected String name;
+ protected int index;
+ protected Map predecessorCounts; // keys: predecessor sibling names, values: count of times it has appeared
+ }
+
+ public IDGeneratingXmlFilter(String documentId)
+ {
+ this.documentId = documentId;
+ }
+
+ public static final String MM_ID_ATTR_NAME_BY_PATH = "com.metamatrix.xml.xpathpart";
+ public static final String MM_ID_ATTR_NAME_BY_INDEX = "com.metamatrix.xml.xpathpart.byindex";
+ public static final String MM_ID_ATTR_NAME = MM_ID_ATTR_NAME_BY_PATH;
+ public static final String MM_ID_ATTR_VALUE_PREFIX = "";
+
+ String documentId;
+
+ // This way of doing things seems like cheating, but it will produce the desired results.
+ // Only problem: the IDs are completely opaque and meaningless.
+ int index = 0;
+
+ // This way is nicer
+ List path; // a list of PathElement objects
+
+ @Override
+ public void startDocument() throws SAXException
+ {
+ path = new ArrayList();
+ PathElement newPathElement = new PathElement(documentId, -1);
+ path.add(newPathElement);
+
+ super.startDocument();
+ }
+
+ private String getIdFromIndex()
+ {
+ String retval = MM_ID_ATTR_VALUE_PREFIX + documentId + "/" + index;
+ ++index;
+ return retval;
+ }
+
+ private String getIdFromPath(String qName)
+ {
+ StringBuffer retval = new StringBuffer();
+
+ Object oParentPath = path.get(path.size() - 1);
+ PathElement parentPath = (PathElement)oParentPath;
+ Map predecessorCounts = parentPath.predecessorCounts;
+ Object oCount = predecessorCounts.get(qName);
+ Integer count = (Integer)oCount;
+ int index;
+ if (count == null) {
+ index = 0;
+ }
+ else {
+ index = count.intValue() + 1;
+ }
+ predecessorCounts.put(qName, Integer.valueOf(index));
+
+ PathElement newPathElement = new PathElement(qName, index);
+ path.add(newPathElement);
+
+ boolean first = true;
+ for (Iterator iter = path.iterator(); iter.hasNext() ; ) {
+ Object o = iter.next();
+ PathElement pathElement = (PathElement)o;
+ if (first) {
+ first = false;
+ }
+ else {
+ retval.append('/');
+ }
+ retval.append(pathElement.name);
+ if (pathElement.index >= 0) {
+ retval.append('[');
+ retval.append(pathElement.index);
+ retval.append(']');
+ }
+ }
+
+ return retval.toString();
+ }
+
+ @Override
+ public void startElement(String namespaceURI, String localName,
+ String qName, Attributes atts) throws SAXException
+ {
+ String indexValue = getIdFromIndex();
+ String pathValue = getIdFromPath(qName);
+ Attributes newAtts = addAttributes(atts, indexValue, pathValue);
+ super.startElement(namespaceURI, localName, qName, newAtts);
+ }
+
+ protected Attributes addAttributes(Attributes atts, String indexValue, String pathValue)
+ {
+ AttributesImpl newAtts = new AttributesImpl(atts);
+ newAtts.addAttribute("", MM_ID_ATTR_NAME, MM_ID_ATTR_NAME, "CDATA", pathValue);
+ newAtts.addAttribute("", MM_ID_ATTR_NAME_BY_INDEX, MM_ID_ATTR_NAME_BY_INDEX, "CDATA", indexValue);
+ return newAtts;
+ }
+
+ @Override
+ public void endElement(String namespaceURI, String localName, String qName)
+ throws SAXException {
+ path.remove(path.size() - 1);
+ super.endElement(namespaceURI, localName, qName);
+ }
+}
\ No newline at end of file
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/OutputXPathDesc.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/OutputXPathDesc.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/OutputXPathDesc.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,84 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+
+package org.teiid.translator.xml;
+
+import java.text.MessageFormat;
+
+import org.teiid.language.Literal;
+import org.teiid.metadata.Column;
+import org.teiid.translator.TranslatorException;
+
+public class OutputXPathDesc extends ParameterDescriptor {
+
+ // Describes an item in the xpath structure, and all the attributes of it
+ // Added to allow all the attributes of an Xpath to be stored in a single structure,
+ // and to make the code more manageable
+ private Object m_currentValue = null;
+ private Class m_dataType = null;
+
+
+ /**
+ * @see com.metamatrix.server.datatier.SynchConnectorConnection#submitRequest(java.lang.Object)
+ */
+ public OutputXPathDesc (Column myElement) throws TranslatorException {
+ super(myElement);
+ m_dataType = myElement.getJavaType();
+ if (getXPath() == null) {
+ if (!isSpecial()) {
+ String rawMsg = XMLPlugin.getString("OutputXPathDesc.name.in.source.required.on.column"); //$NON-NLS-1$
+ String msg = MessageFormat.format(rawMsg, new Object[] {getColumnName()});
+ throw new TranslatorException(msg);
+ }
+ }
+ }
+
+ public boolean isSpecial() {
+ return isParameter() || isResponseId() || isLocation();
+ }
+
+ public OutputXPathDesc (Literal literal) throws TranslatorException {
+ super();
+ if (literal.getValue() == null) {
+ setCurrentValue(null);
+ } else {
+ setCurrentValue(literal.getValue().toString());
+ }
+ m_dataType = literal.getType();
+ }
+
+
+ public void setCurrentValue(Object obj) {
+ m_currentValue = obj;
+ }
+
+ public Object getCurrentValue() {
+ return m_currentValue;
+ }
+
+
+ public Class getDataType() throws TranslatorException {
+ return m_dataType;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ParameterDescriptor.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ParameterDescriptor.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/ParameterDescriptor.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,156 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import org.teiid.metadata.Column;
+import org.teiid.translator.TranslatorException;
+
+public abstract class ParameterDescriptor {
+
+ private String m_xPath;
+ private boolean m_param;
+ private boolean m_responseId;
+ private boolean m_location;
+ private String m_columnName;
+ private int m_columnNumber = -1;
+ private Column m_element;
+
+ public static final String PARM_INPUT_COLUMN_PROPERTY_NAME = "IsInputParameter"; //$NON-NLS-1$
+ public static final String ROLE_COLUMN_PROPERTY_NAME = "Role"; //$NON-NLS-1$
+ public static final String ROLE_COLUMN_PROPERTY_NAME_RESPONSE_IN = "ResponseIn"; //$NON-NLS-1$
+ public static final String ROLE_COLUMN_PROPERTY_NAME_RESPONSE_OUT = "ResponseOut"; //$NON-NLS-1$
+ public static final String ROLE_COLUMN_PROPERTY_NAME_LOCATION = "Location"; //$NON-NLS-1$
+ public static final String ROLE_COLUMN_PROPERTY_NAME_DATA = "Data"; //$NON-NLS-1$
+
+ public ParameterDescriptor( Column element ) throws TranslatorException {
+ setElement(element);
+ setIsParameter(testForParam(m_element));
+ testRole();
+ if (getElement().getNameInSource() != null) {
+ setColumnName(getElement().getNameInSource());
+ } else {
+ setColumnName(getElement().getName().trim());
+ }
+ String nis = getElement().getNameInSource();
+ if (nis != null) {
+ nis = nis.trim();
+ }
+ setXPath(nis);
+ }
+
+ protected ParameterDescriptor() {
+ setIsParameter(false);
+ setIsResponseId(false);
+ setIsLocation(false);
+ setColumnName(null);
+ setXPath(null);
+ }
+
+ public final void setXPath( String xPath ) {
+ m_xPath = xPath;
+ }
+
+ public String getXPath() {
+ return m_xPath;
+ }
+
+ public final void setIsParameter( boolean param ) {
+ m_param = param;
+ }
+
+ public final void setIsResponseId( boolean responseId ) {
+ m_responseId = responseId;
+ }
+
+ public final void setIsLocation( boolean location ) {
+ m_location = location;
+ }
+
+ public final boolean isParameter() {
+ return m_param;
+ }
+
+ public final boolean isResponseId() {
+ return m_responseId;
+ }
+
+ public final boolean isLocation() {
+ return m_location;
+ }
+
+ public final void setColumnName( String columnName ) {
+ m_columnName = columnName;
+ }
+
+ public final String getColumnName() {
+ return m_columnName;
+ }
+
+ public final void setColumnNumber( int columnNumber ) {
+ m_columnNumber = columnNumber;
+ }
+
+ public final int getColumnNumber() {
+ return m_columnNumber;
+ }
+
+ protected void setElement( Column elem ) {
+ m_element = elem;
+ }
+
+ public Column getElement() {
+ return m_element;
+ }
+
+ protected static boolean testForParam( Column element ) throws TranslatorException {
+ boolean param = false;
+ param = Boolean.valueOf(element.getProperties().get(PARM_INPUT_COLUMN_PROPERTY_NAME)).booleanValue();
+ return param;
+ }
+
+ public String getRole() throws TranslatorException {
+ return m_element.getProperties().get(ROLE_COLUMN_PROPERTY_NAME);
+ }
+
+ protected void testRole() throws TranslatorException {
+ String role = getRole();
+ if (role == null) {
+ setIsResponseId(false);
+ setIsLocation(false);
+ } else {
+ if (role.equalsIgnoreCase(ROLE_COLUMN_PROPERTY_NAME_RESPONSE_IN)) {
+ setIsResponseId(true);
+ setIsLocation(false);
+ } else if (role.equalsIgnoreCase(ROLE_COLUMN_PROPERTY_NAME_RESPONSE_OUT)) {
+ setIsResponseId(true);
+ setIsLocation(false);
+ } else if (role.equalsIgnoreCase(ROLE_COLUMN_PROPERTY_NAME_LOCATION)) {
+ setIsResponseId(false);
+ setIsLocation(true);
+ } else { // if (role.equalsIgnoreCase(ROLE_COLUMN_PROPERTY_NAME_DATA))
+ setIsResponseId(false);
+ setIsLocation(false);
+ }
+ }
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/QueryAnalyzer.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/QueryAnalyzer.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/QueryAnalyzer.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,208 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.Literal;
+import org.teiid.language.NamedTable;
+import org.teiid.language.Select;
+import org.teiid.language.TableReference;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Table;
+import org.teiid.translator.TranslatorException;
+
+public class QueryAnalyzer {
+
+ private Select command;
+ private Table table;
+ private ExecutionInfo executionInfo;
+
+ public QueryAnalyzer(Select query) throws TranslatorException {
+ this.command = query;
+ executionInfo = new ExecutionInfo();
+ analyze();
+ }
+
+ public final void analyze() throws TranslatorException {
+ setGroupInfo();
+ setRequestedColumns();
+ setParametersAndCriteria();
+ setProperties();
+ }
+
+
+
+ public ExecutionInfo getExecutionInfo() {
+ return this.executionInfo;
+ }
+
+ private void setGroupInfo() throws TranslatorException {
+ List<TableReference> fromItems = command.getFrom();
+ //Can only be one because we do not support joins
+ NamedTable group = (NamedTable) fromItems.get(0);
+ this.table = group.getMetadataObject();
+ this.executionInfo.setTableXPath(table.getNameInSource());
+ }
+
+ private void setRequestedColumns() throws TranslatorException {
+
+ List<OutputXPathDesc> columns = new ArrayList<OutputXPathDesc>();
+ //get the request items
+ List<DerivedColumn> selectSymbols = this.command.getDerivedColumns();
+
+ //setup column numbers
+ int projectedColumnCount = 0;
+
+ //add projected fields into XPath array and element array for later
+ // lookup
+
+ for(DerivedColumn selectSymbol : selectSymbols) {
+ Expression expr = selectSymbol.getExpression();
+ OutputXPathDesc xpath = null;
+
+ //build the appropriate structure
+ if (expr instanceof Literal) {
+ xpath = new OutputXPathDesc((Literal) expr);
+ } else if (expr instanceof ColumnReference) {
+ Column element = ((ColumnReference)expr).getMetadataObject();
+ xpath = new OutputXPathDesc(element);
+ }
+ if (xpath != null) {
+ xpath.setColumnNumber(projectedColumnCount);
+ }
+
+ // put xpath object into linked list
+ columns.add(xpath);
+ ++projectedColumnCount;
+ }
+
+ //set the column count
+ this.executionInfo.setColumnCount(projectedColumnCount);
+ this.executionInfo.setRequestedColumns(columns);
+ }
+
+ private void setParametersAndCriteria() throws TranslatorException {
+ //Build a linked list of parameters, and a linked list of equivilence
+ // and set selection criteria.
+ //Each parameter and criteria is itself represented by a linked list,
+ // containing names, element (metadata), and equivilence value, or all
+ // set values
+
+ ArrayList<CriteriaDesc> params = new ArrayList<CriteriaDesc>();
+ ArrayList<CriteriaDesc> crits = new ArrayList<CriteriaDesc>();
+ ArrayList<CriteriaDesc> responses = new ArrayList<CriteriaDesc>();
+ ArrayList<CriteriaDesc> locations = new ArrayList<CriteriaDesc>();
+
+ //Iterate through each field in the table
+ for (Column element : table.getColumns()) {
+ CriteriaDesc criteria = CriteriaDesc.getCriteriaDescForColumn(
+ element, command);
+ if (criteria != null) {
+ mapCriteriaToColumn(criteria, params, crits, responses, locations);
+ }
+ }
+ this.executionInfo.setParameters(params);
+ this.executionInfo.setCriteria(crits);
+
+ String location = null;
+ for (Iterator<CriteriaDesc> iter = locations.iterator(); iter.hasNext(); ) {
+ Object o = iter.next();
+ CriteriaDesc crtierion = (CriteriaDesc)o;
+ List values = crtierion.getValues();
+ for (Iterator valuesIter = values.iterator(); valuesIter.hasNext(); ) {
+ Object oValue = valuesIter.next();
+ String value = (String)oValue;
+ if (location != null) {
+ if (!(location.equals(value))) {
+ throw new TranslatorException(XMLPlugin
+ .getString("QueryAnalyzer.multiple.locations.supplied")); //$NON-NLS-1$
+ }
+ }
+ location = value;
+ }
+ }
+ this.executionInfo.setLocation(location);
+ }
+
+ private void mapCriteriaToColumn(CriteriaDesc criteria, ArrayList<CriteriaDesc> params,
+ ArrayList<CriteriaDesc> crits, ArrayList<CriteriaDesc> responses, ArrayList<CriteriaDesc> locations) throws TranslatorException {
+ int totalColumnCount = this.executionInfo.getColumnCount();
+ //check each criteria to see which projected column it maps to
+ String criteriaColName = criteria.getColumnName();
+ boolean matchedField = false;
+ OutputXPathDesc xpath = null;
+ for (int j = 0; j < this.executionInfo.getRequestedColumns().size(); j++) {
+ xpath = (OutputXPathDesc) this.executionInfo.getRequestedColumns().get(j);
+ String projColName = xpath.getColumnName();
+ if (criteriaColName.equals(projColName)) {
+ matchedField = true;
+ criteria.setColumnNumber(j);
+ break;
+ }
+ }
+ if (criteria.isParameter() || criteria.isResponseId() && !criteria.isLocation()) {
+ params.add(criteria);
+ if (criteria.isResponseId()) {
+ responses.add(criteria);
+ }
+ } else {
+
+ // otherwise add a new column to the projected XPath list (don't
+ // worry,
+ // it will be removed later and not really projected.
+ // match not found, add to project list
+ if (!matchedField) {
+ criteria.setColumnNumber(totalColumnCount);
+ xpath = new OutputXPathDesc(criteria
+ .getElement());
+ xpath.setColumnNumber(totalColumnCount++);
+ this.executionInfo.getRequestedColumns().add(xpath);
+ }
+ if (xpath.isResponseId()) {
+ responses.add(criteria);
+ }
+ else if (xpath.isLocation()) {
+ locations.add(criteria);
+ }
+ else {
+ crits.add(criteria);
+ }
+ }
+ }
+
+ private void setProperties() throws TranslatorException {
+ this.executionInfo.setOtherProperties(table.getProperties());
+ }
+
+ public List<CriteriaDesc[]> getRequestPerms() {
+ return RequestGenerator.getRequests(this.executionInfo.getParameters());
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestGenerator.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestGenerator.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestGenerator.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,107 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+
+
+package org.teiid.translator.xml;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RequestGenerator {
+
+ // This method is misnamed. It generates cartesian products, not permutations.
+ public static List<CriteriaDesc[]> getRequests(List<CriteriaDesc> params)
+ {
+ List<CriteriaDesc[]> soFar = new ArrayList<CriteriaDesc[]>();
+
+ // Start off with a single "row" (with zero parameters)
+ soFar.add(new CriteriaDesc[]{});
+ for (CriteriaDesc desc: params){
+ soFar = RequestGenerator.createCartesionProduct(soFar, desc);
+ }
+
+ return soFar;
+ }
+
+ // Create the cartesian product of a list of CriteriaDescs, and single CriteriaDesc
+ // with (potentially) multiple values
+ static List<CriteriaDesc[]> createCartesionProduct(List<CriteriaDesc[]> permsSoFar, CriteriaDesc desc)
+ {
+ List<CriteriaDesc[]> retval = new ArrayList<CriteriaDesc[]>();
+
+ // Get the 'simple' cartesian product
+ List<List> rows = createCartesionProduct(permsSoFar, desc.getValues(), desc.isUnlimited());
+
+ // Merge the existing list of CriteriaDescs with the new value turned into a CriteriaDesc)
+ for (List row : rows) {
+ Object oOperand1 = row.get(0);
+ CriteriaDesc[] previousCriteriaDescs = (CriteriaDesc[])oOperand1;
+
+ CriteriaDesc[] newRow = new CriteriaDesc[previousCriteriaDescs.length + 1];
+ System.arraycopy(previousCriteriaDescs, 0, newRow, 0, previousCriteriaDescs.length);
+ CriteriaDesc singleValueCriteriaDesc = desc.cloneWithoutValues();
+ for (int i=1; i < row.size(); i++ ){
+ Object value = row.get(i);
+ singleValueCriteriaDesc.setValue((i - 1), value);
+ }
+ newRow[newRow.length - 1] = singleValueCriteriaDesc;
+ retval.add(newRow);
+ }
+ return retval;
+ }
+
+ // Create the cartesian product of any two lists
+ private static List<List> createCartesionProduct(List<CriteriaDesc[]> operand1, List operand2, boolean multiElem)
+ {
+ if (operand1.size() == 0) {
+ operand1 = new ArrayList<CriteriaDesc[]>();
+ operand1.add(null);
+ }
+
+ if (operand2.size() == 0) {
+ operand2 = new ArrayList();
+ operand2.add(null);
+ }
+
+
+ List<List> cartesianProduct = new ArrayList<List>();
+ for (CriteriaDesc[] operand1item : operand1) {
+ List newRow = new ArrayList();
+ if (! multiElem) {
+ for (Object operand2item : operand2 ) {
+ newRow.add(operand1item);
+ newRow.add(operand2item);
+ cartesianProduct.add(newRow);
+ }
+ } else {
+ newRow.add(operand1item);
+ for (Object operand2item : operand2 ) {
+ newRow.add(operand2item);
+ }
+ cartesianProduct.add(newRow);
+ }
+ }
+ return cartesianProduct;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestPreprocessor.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestPreprocessor.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/RequestPreprocessor.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -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.translator.xml;
+
+import org.teiid.language.Select;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+
+public interface RequestPreprocessor {
+ /**
+ *
+ * This method is used for altering the query before it enters the XML connector's processing
+ *
+ * @param query The IQuery passed from the connector
+ * @param m_logger the connector logger
+ * @param connectorEnv the connector environment
+ * @param exeContext the execution context
+ * @param m_metadata the runtime metadata
+ * @return an IQuery object representing the altered query
+ */
+ public Select preprocessQuery(Select query, RuntimeMetadata m_metadata, ExecutionContext exeContext);
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/SAXFilterProvider.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/SAXFilterProvider.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/SAXFilterProvider.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,32 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+
+
+package org.teiid.translator.xml;
+
+import org.xml.sax.helpers.XMLFilterImpl;
+
+
+public interface SAXFilterProvider {
+ XMLFilterImpl[] getExtendedFilters();
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,200 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.sql.SQLXML;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.resource.ResourceException;
+import javax.resource.cci.Connection;
+import javax.resource.cci.ConnectionFactory;
+import javax.xml.transform.Source;
+import javax.xml.ws.Dispatch;
+
+import org.teiid.language.Call;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.Select;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.FileConnection;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TranslatorProperty;
+import org.teiid.translator.xml.streaming.BaseStreamingExecution;
+
+public class XMLExecutionFactory extends ExecutionFactory {
+
+ private String saxFilterProviderClass;
+ private String encoding = "ISO-8859-1"; //$NON-NLS-1$
+ private Map<String, SQLXML> responses = new ConcurrentHashMap<String, SQLXML>();
+ private boolean logRequestResponseDocs = false;
+ private String queryPreprocessorClass;
+
+ @TranslatorProperty(description="Encoding of the XML documents", display="Encoding Scheme")
+ public String getCharacterEncodingScheme() {
+ return this.encoding;
+ }
+
+ public void setCharacterEncodingScheme(String encoding) {
+ this.encoding = encoding;
+ }
+
+ @TranslatorProperty(description="Must be extension of org.teiid.translator.xml.SAXFilterProvider class", display="SAX Filter Provider Class")
+ public String getSaxFilterProviderClass() {
+ return this.saxFilterProviderClass;
+ }
+
+ public void setSaxFilterProviderClass(String saxFilterProviderClass) {
+ this.saxFilterProviderClass = saxFilterProviderClass;
+ }
+
+ @TranslatorProperty(display="Request Preprocessor Class", description="Must be extension of org.teiid.translator.xml.RequestPreprocessor")
+ public String getRequestPreprocessorClass() {
+ return this.queryPreprocessorClass;
+ }
+
+ public void setRequestPreprocessorClass(String queryPreprocessorClass) {
+ this.queryPreprocessorClass = queryPreprocessorClass;
+ }
+
+ // Can we get rid of this?
+ private String inputStreamFilterClass;
+
+ public String getInputStreamFilterClass() {
+ return this.inputStreamFilterClass;
+ }
+
+ public void setInputStreamFilterClass(String inputStreamFilterClass) {
+ this.inputStreamFilterClass = inputStreamFilterClass;
+ }
+
+ @TranslatorProperty(description="Log the XML request/response documents", display="Log Request/Response Documents")
+ public boolean isLogRequestResponseDocs() {
+ return logRequestResponseDocs;
+ }
+
+ public void setLogRequestResponseDocs(Boolean logRequestResponseDocs) {
+ this.logRequestResponseDocs = logRequestResponseDocs;
+ }
+
+ public SQLXML getResponse(String key) {
+ return this.responses.get(key);
+ }
+
+ public void setResponse(String key, SQLXML xml) {
+ this.responses.put(key, xml);
+ }
+
+ public SQLXML removeResponse(String key) {
+ return this.responses.remove(key);
+ }
+
+
+ @Override
+ public ProcedureExecution createProcedureExecution(Call command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws TranslatorException {
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+ Connection connection = cf.getConnection();
+ if (connection instanceof FileConnection) {
+ return new FileProcedureExecution(command, this, (FileConnection)connection);
+ }
+ else if (connection instanceof Dispatch<?>) {
+ return new XMLProcedureExecution(command, metadata, executionContext, this, (Dispatch)connection);
+ }
+ else {
+ return null;
+ }
+
+ } catch (ResourceException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ @Override
+ public ResultSetExecution createResultSetExecution(QueryExpression command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connectionFactory)
+ throws TranslatorException {
+ RequestPreprocessor preProcessor = getRequestPreProcessor();
+ if (preProcessor != null) {
+ command = preProcessor.preprocessQuery((Select)command, metadata, executionContext);
+ }
+
+ try {
+ ConnectionFactory cf = (ConnectionFactory)connectionFactory;
+ Connection connection = cf.getConnection();
+ if (connection instanceof FileConnection) {
+ return new FileResultSetExecution((Select)command, this, (FileConnection)connection);
+ }
+ else if (connection instanceof Dispatch<?>) {
+ return new BaseStreamingExecution((Select)command, metadata, executionContext, this, (Dispatch)connection);
+ }
+ return null;
+ } catch (ResourceException e) {
+ throw new TranslatorException(e);
+ }
+ }
+
+ private RequestPreprocessor getRequestPreProcessor() throws TranslatorException {
+ String className = getRequestPreprocessorClass();
+ if (className == null) {
+ return null;
+ }
+ return getInstance(RequestPreprocessor.class, className, null, null);
+ }
+
+ public SAXFilterProvider getSaxFilterProvider() throws TranslatorException {
+ if (getSaxFilterProviderClass() == null) {
+ return null;
+ }
+ return getInstance(SAXFilterProvider.class, getSaxFilterProviderClass(), null, null);
+ }
+
+ public SQLXML convertToXMLType(Source value) {
+ return (SQLXML)getTypeFacility().convertToRuntimeType(value);
+ }
+
+ @Override
+ public final int getMaxInCriteriaSize() {
+ return Integer.MAX_VALUE;
+ }
+
+ @Override
+ public final List getSupportedFunctions() {
+ return Collections.EMPTY_LIST;
+ }
+
+ @Override
+ public final boolean supportsCompareCriteriaEquals() {
+ return true;
+ }
+
+ @Override
+ public final boolean supportsInCriteria() {
+ return true;
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLPlugin.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLPlugin.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLPlugin.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,43 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+import org.teiid.core.BundleUtil;
+
+public class XMLPlugin {
+
+ private static final String PLUGIN_ID = XMLPlugin.class.getPackage().getName();
+
+ public static final BundleUtil Util = new BundleUtil(PLUGIN_ID, PLUGIN_ID + ".i18n", ResourceBundle.getBundle(PLUGIN_ID + ".i18n")); //$NON-NLS-1$ //$NON-NLS-2$
+
+ public static String getString(String key) {
+ try {
+ return Util.getString(key);
+ } catch (MissingResourceException e) {
+ return '!' + key + '!';
+ }
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,137 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.io.StringReader;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.Dispatch;
+
+import org.teiid.language.Argument;
+import org.teiid.language.Call;
+import org.teiid.language.Argument.Direction;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.streaming.BaseStreamingExecution;
+
+/**
+ * A soap call executor - handles all styles doc/literal, rpc/encoded etc.
+ */
+public class XMLProcedureExecution implements ProcedureExecution {
+
+ RuntimeMetadata metadata = null;
+ ExecutionContext context;
+ private Call procedure;
+ private boolean returnedResult;
+ private SQLXML returnValue;
+ private Dispatch<Source> dispatch;
+ private XMLExecutionFactory executionFactory;
+
+ /**
+ * @param env
+ */
+ public XMLProcedureExecution(Call procedure, RuntimeMetadata metadata, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch dispatch) {
+ this.metadata = metadata;
+ this.context = context;
+ this.procedure = procedure;
+ this.dispatch = dispatch;
+ this.executionFactory = executionFactory;
+ }
+
+ /**
+ * @see org.teiid.connector.api.ProcedureExecution#execute(org.teiid.connector.language.Call, int)
+ */
+ public void execute() throws TranslatorException {
+
+ AbstractMetadataRecord metaObject = procedure.getMetadataObject();
+ String procedureName = metaObject.getNameInSource();
+ if (procedureName == null || procedureName.length() == 0) {
+ throw new TranslatorException(XMLPlugin.getString("source_name_not_supplied")); //$NON-NLS-1$
+ }
+
+ // execute the request
+ Source result = this.dispatch.invoke(buildRequest(procedureName, procedure.getArguments()));
+ this.returnValue = this.executionFactory.convertToXMLType(result);
+ if (executionFactory.isLogRequestResponseDocs()) {
+ try {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, this.returnValue.getString());
+ } catch (SQLException e) {
+ }
+ }
+
+ }
+
+ Source buildRequest(String procedureName, List<Argument> args){
+ StringBuilder sb = new StringBuilder();
+ sb.append("<tns1:").append(procedureName);
+ sb.append(" xmlns:tns1=\"").append(BaseStreamingExecution.DUMMY_NS_NAME).append("\">");
+
+ for (Argument argument:args) {
+ if (argument.getDirection() == Direction.IN ) {
+ sb.append(argument.getArgumentValue().getValue());
+ }
+ else if (argument.getDirection() == Direction.INOUT) {
+ sb.append(argument.getArgumentValue().getValue());
+ }
+ }
+
+ sb.append("</tns1:").append(procedureName).append(">");
+
+ return new StreamSource(new StringReader(sb.toString()));
+ }
+
+
+
+ @Override
+ public List<?> next() throws TranslatorException, DataNotAvailableException {
+ if (!returnedResult) {
+ returnedResult = true;
+ return Arrays.asList(this.returnValue);
+ }
+ return null;
+ }
+
+ @Override
+ public List<?> getOutputParameterValues() throws TranslatorException {
+ throw new TranslatorException(XMLPlugin.getString("No_outputs_allowed")); //$NON-NLS-1$
+ }
+
+ public void close() throws TranslatorException {
+ // no-op
+ }
+
+ public void cancel() throws TranslatorException {
+ // no-op
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,404 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml.streaming;
+
+import java.io.StringReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.handler.MessageContext;
+
+import org.jdom.Element;
+import org.jdom.output.XMLOutputter;
+import org.teiid.core.util.Assertion;
+import org.teiid.language.Select;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.Constants;
+import org.teiid.translator.xml.CriteriaDesc;
+import org.teiid.translator.xml.Document;
+import org.teiid.translator.xml.DocumentBuilder;
+import org.teiid.translator.xml.ExecutionInfo;
+import org.teiid.translator.xml.OutputXPathDesc;
+import org.teiid.translator.xml.ParameterDescriptor;
+import org.teiid.translator.xml.QueryAnalyzer;
+import org.teiid.translator.xml.RequestGenerator;
+import org.teiid.translator.xml.XMLExecutionFactory;
+import org.teiid.translator.xml.XMLPlugin;
+
+
+public class BaseStreamingExecution implements ResultSetExecution {
+ public static final String PARM_INPUT_XPATH_TABLE_PROPERTY_NAME = "XPathRootForInput"; //$NON-NLS-1$
+ public static final String PARM_INPUT_NAMESPACE_TABLE_PROPERTY_NAME = "NamespaceForDocument"; //$NON-NLS-1$
+ public final static String soapNSLabel = "SOAP-ENV"; //$NON-NLS-1$
+ public static final String soapHeader= "Header"; //$NON-NLS-1$
+ public static final String DUMMY_NS_PREFIX = "mm-dummy"; //$NON-NLS-1$
+ public static final String DUMMY_NS_NAME = "http://www.teiid.org/dummy"; //$NON-NLS-1$
+
+
+ private List<Object[]> results = new ArrayList<Object[]>();
+ private int resultIndex = 0;
+
+ // injected state
+ protected RuntimeMetadata metadata;
+ protected ExecutionContext context;
+ protected XMLExecutionFactory executionFactory;
+ Dispatch<Source> dispatch;
+ ExecutionInfo executionInfo;
+ private Source soapPayload;
+ Iterator<Document> resultsIterator;
+
+ public BaseStreamingExecution(Select command, RuntimeMetadata rtMetadata, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch<Source> dispatch) throws TranslatorException {
+ this.metadata = rtMetadata;
+ this.context = context;
+ this.executionFactory = executionFactory;
+ this.dispatch = dispatch;
+
+ QueryAnalyzer analyzer = new QueryAnalyzer(command);
+ this.executionInfo = analyzer.getExecutionInfo();
+ List<CriteriaDesc[]> requestPerms = analyzer.getRequestPerms();
+
+ for (CriteriaDesc[] criteria : requestPerms) {
+ processOutputXPathDescs(this.executionInfo.getRequestedColumns(), Arrays.asList(criteria));
+ }
+
+ if (checkIfRequestIsNeeded(this.executionInfo)) {
+ for (CriteriaDesc[] criteria : requestPerms) {
+ List<CriteriaDesc[]> parameters = RequestGenerator.getRequests(Arrays.asList(criteria));
+
+ // Build a query String for http
+ String queryString = buildQueryString(parameters);
+ this.dispatch.getRequestContext().put(MessageContext.QUERY_STRING, queryString);
+
+ String endpoint = buildAlternateEndpoint(this.executionInfo);
+ if (endpoint == null) {
+ this.dispatch.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY, endpoint);
+ }
+ else {
+ String pathInfo = buildPath(this.executionInfo);
+ if (pathInfo != null) {
+ this.dispatch.getRequestContext().put(MessageContext.PATH_INFO, pathInfo);
+ }
+ }
+ }
+
+ String soapAction = this.executionInfo.getOtherProperties().get("SOAPAction"); //$NON-NLS-1$
+ if (soapAction != null) {
+ dispatch.getRequestContext().put(Dispatch.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
+ dispatch.getRequestContext().put(Dispatch.SOAPACTION_URI_PROPERTY, soapAction);
+ }
+
+
+ try {
+ // Build XML string for HTTP
+ String xmlPayload = buildSimpleXML(requestPerms);
+ if (xmlPayload != null) {
+ Map<String, Object> map = (Map)this.dispatch.getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
+ if (map == null) {
+ map = new HashMap<String, Object>();
+ }
+ map.put("xml", xmlPayload); //$NON-NLS-1$
+ this.dispatch.getRequestContext().put(MessageContext.INBOUND_MESSAGE_ATTACHMENTS, map);
+ if (executionFactory.isLogRequestResponseDocs()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, xmlPayload);
+ }
+ }
+ } catch (TranslatorException e) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, XMLPlugin.Util.getString("failed_to_generate_xml_request")); //$NON-NLS-1$
+ }
+
+ try {
+ // Build XML for SOAP
+ String soapIn = buildSOAPInput(requestPerms);
+ if(soapIn != null) {
+ this.soapPayload = new StreamSource(new StringReader(soapIn));
+ if (executionFactory.isLogRequestResponseDocs()) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, soapIn);
+ }
+ }
+ } catch (TranslatorException e) {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, XMLPlugin.Util.getString("failed_to_generate_xml_request")); //$NON-NLS-1$
+ }
+ }
+ }
+
+ protected void initialize() {
+
+ }
+
+ private String buildQueryString(List<CriteriaDesc[]> parameters) throws TranslatorException{
+ StringBuilder sb = new StringBuilder();
+
+ for (CriteriaDesc[] query: parameters) {
+ for(CriteriaDesc cd: query) {
+ String name = (cd.getInputXpath() == null || cd.getInputXpath().length() == 0) ? cd.getColumnName() : cd.getInputXpath();
+ sb.append(name).append("=").append(cd.getCurrentIndexValue()).append("&"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ return sb.toString();
+ }
+
+
+ public void cancel() throws TranslatorException {
+ // nothing to do
+ }
+
+ private List<String> getXPaths() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ return splitter.split(this.executionInfo.getTableXPath());
+ } catch (InvalidPathException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+ /**
+ * Earlier implementations retrieved the XML in the execute method. Because this can be any
+ * number of documents of any size, this caused memory problems because the xml was
+ * completely realized in memory. In this impl the setup work is done in execute and
+ * the xml is streamed in the next function.
+ */
+ public List next() throws TranslatorException, DataNotAvailableException {
+ this.context.keepExecutionAlive(true);
+
+ List result = null;
+ if (this.resultIndex == 0) {
+ fillInResults();
+ }
+
+ if(resultIndex < results.size()) {
+ result = Arrays.asList(results.get(resultIndex));
+ ++resultIndex;
+ }
+ return result;
+ }
+
+ private void fillInResults() throws TranslatorException {
+ List<Object[]> rows;
+ StreamingResultsProducer streamProducer = new StreamingResultsProducer(this.executionInfo, this.executionFactory.getSaxFilterProvider());
+ Iterator<Document> streamIter = this.resultsIterator;
+ while (streamIter.hasNext()) {
+ Document xml = streamIter.next();
+ // TODO: add stream filter class. --rareddy
+ rows = streamProducer.getResult(xml, getXPaths());
+ if (rows.isEmpty()) {
+ continue;
+ }
+ results.addAll(rows);
+ }
+ }
+
+ protected SQLXML convertToXMLType(Source value) {
+ return (SQLXML)this.executionFactory.getTypeFacility().convertToRuntimeType(value);
+ }
+
+ @Override
+ public void close() throws TranslatorException {
+ this.executionFactory.removeResponse(this.context.getExecutionCountIdentifier());
+ }
+
+ @Override
+ public void execute() throws TranslatorException {
+ ArrayList<Document> result = new ArrayList<Document>();
+ result.add(getDocumentStream(this.executionInfo));
+ this.resultsIterator = result.iterator();
+ }
+
+ /**
+ * Examines the Query to determine if a request to a source is needed. If any of the
+ * request parameters is a ResponseIn, then we don't need to make a request because it
+ * has already been made by another call to Execution.execute()
+ */
+ static boolean checkIfRequestIsNeeded(ExecutionInfo info) throws TranslatorException {
+ List cols = info.getRequestedColumns();
+ boolean retVal = true;
+ Iterator paramIter = cols.iterator();
+ while(paramIter.hasNext()) {
+ ParameterDescriptor desc = (ParameterDescriptor) paramIter.next();
+ if(desc.getRole().equalsIgnoreCase(ParameterDescriptor.ROLE_COLUMN_PROPERTY_NAME_RESPONSE_IN)) {
+ retVal = false;
+ break;
+ }
+ }
+ return retVal;
+ }
+
+ protected String buildAlternateEndpoint(ExecutionInfo executionInfo) {
+ String location = executionInfo.getLocation();
+ if (location != null) {
+ // If the location is a URL, it replaces the full URL (first part
+ // set in the
+ // connector binding and second part set in the model).
+ try {
+ new URL(location);
+ return location;
+ } catch (MalformedURLException e) {
+ }
+ }
+ return null;
+ }
+
+ protected String buildPath(ExecutionInfo executionInfo) {
+ String location = executionInfo.getLocation();
+ if (location == null) {
+ final String tableServletCallPathProp = "ServletCallPathforURL"; //$NON-NLS-1$
+ location = executionInfo.getOtherProperties().get(tableServletCallPathProp);
+ }
+ return location;
+ }
+
+ /**
+ * Because of the structure of relational databases it is a simple and common practice
+ * to return the vaule of a critera in a result set. For instance,
+ * SELECT name, ssn from people where ssn='xxx-xx-xxxx'
+ * In a Request/Response XML scenario, there is no guarantee that ssn is in the response.
+ * In most cases it will not be. In order to meet the relational users expectation that
+ * the value for a select critera can be returned we stash the value from the parameter
+ * in the output value and then fetch it when gathering results if possible. In some cases
+ * this is not possible, and in those cases we throw a TranslatorException. Implementations
+ * of this class can override cannotProjectParameter(CriteriaDesc parmCriteria) to make the
+ * determination.
+ */
+ private void processOutputXPathDescs(final List<OutputXPathDesc> columns, final List<CriteriaDesc> parameters) throws TranslatorException {
+ for (OutputXPathDesc column:columns) {
+ if (column.isParameter() && column.getXPath() == null) {
+ int colNum = column.getColumnNumber();
+ for(CriteriaDesc cd:parameters) {
+ if (cd.getColumnNumber() == colNum) {
+ if (cannotProjectParameter(cd)) {
+ throw new TranslatorException(XMLPlugin.getString("HTTPExecutor.cannot.project.repeating.values")); //$NON-NLS-1$
+ }
+ column.setCurrentValue(cd.getCurrentIndexValue());
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ private boolean cannotProjectParameter(CriteriaDesc parmCriteria) {
+ return parmCriteria.getNumberOfValues() > 1
+ && parmCriteria.isUnlimited();
+ // this info is only available in the connection side
+ //&& !((getState()).getParameterMethod() == HTTPConnectorState.PARAMETER_NAME_VALUE);
+ }
+
+
+ private Document getDocumentStream(ExecutionInfo executionInfo) {
+ Document document;
+
+ // Is this a request part joining across a document
+ CriteriaDesc criterion = executionInfo.getResponseIDCriterion();
+ if (criterion != null) {
+ String responseid = (String) (criterion.getValues().get(0));
+ SQLXML xml = this.executionFactory.getResponse(responseid);
+ Assertion.isNotNull(xml);
+ document = new DocumentImpl(xml, responseid);
+ } else {
+ // Not a join, but might still be cached.
+ // Not cached, so make the request
+ Source result = this.dispatch.invoke(this.soapPayload);
+ SQLXML responseBody = this.executionFactory.convertToXMLType(result);
+ if (executionFactory.isLogRequestResponseDocs()) {
+ try {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, responseBody.getString());
+ } catch (SQLException e) {
+ }
+ }
+ this.executionFactory.setResponse(this.context.getExecutionCountIdentifier(), responseBody);
+ document = new DocumentImpl(responseBody, this.context.getExecutionCountIdentifier());
+ }
+ return document;
+ }
+
+
+ private String buildSOAPInput(List<CriteriaDesc[]> params) throws TranslatorException {
+ List<CriteriaDesc[]> requestPerms = RequestGenerator.getRequests(Arrays.asList(params.get(0)));
+ CriteriaDesc[] parameters = requestPerms.get(0);
+
+ List<CriteriaDesc> queryList = new ArrayList<CriteriaDesc>(Arrays.asList(parameters));
+ List<CriteriaDesc> headerParams = new ArrayList<CriteriaDesc>();
+ List<CriteriaDesc> bodyParams = new ArrayList<CriteriaDesc>();
+
+ for (CriteriaDesc desc : queryList) {
+ if (desc.getInputXpath().startsWith(soapNSLabel+ ":" + soapHeader)) { //$NON-NLS-1$
+ headerParams.add(desc);
+ } else {
+ bodyParams.add(desc);
+ }
+ }
+
+ String namespacePrefixes = this.executionInfo.getOtherProperties().get(Constants.NAMESPACE_PREFIX_PROPERTY_NAME);
+ String inputParmsXPath = this.executionInfo.getOtherProperties().get(DocumentBuilder.PARM_INPUT_XPATH_TABLE_PROPERTY_NAME);
+
+ DocumentBuilder builder = new DocumentBuilder();
+ //TODO: always set to encoded false - rareddy
+ builder.setUseTypeAttributes(false);
+ final String slash = "/"; //$NON-NLS-1$
+ final String dotSlash = "./"; //$NON-NLS-1$
+ boolean hasDummy = false;
+ if (inputParmsXPath.equals(dotSlash) || inputParmsXPath.equals(slash) || inputParmsXPath.equals("")) { //$NON-NLS-1$
+ inputParmsXPath = DUMMY_NS_PREFIX + ":dummy"; //$NON-NLS-1$
+ namespacePrefixes = namespacePrefixes + " xmlns:" + DUMMY_NS_PREFIX + "=\"" + DUMMY_NS_NAME + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ hasDummy = true;
+ }
+ org.jdom.Document doc = builder.buildDocument(Arrays.asList(parameters), inputParmsXPath, namespacePrefixes);
+ if (hasDummy) {
+ // Since there is no real root - these should all be elements
+ Element element = (Element) doc.getRootElement().getChildren().get(0);
+ element.detach();
+ doc = new org.jdom.Document(element);
+ }
+ return new XMLOutputter().outputString(doc);
+ }
+
+ private String buildSimpleXML(List<CriteriaDesc[]> params) throws TranslatorException{
+ List<CriteriaDesc[]> requestPerms = RequestGenerator.getRequests(Arrays.asList(params.get(0)));
+ CriteriaDesc[] parameters = requestPerms.get(0);
+
+ DocumentBuilder builder = new DocumentBuilder();
+ Map<String, String> props = executionInfo.getOtherProperties();
+ String inputParmsXPath = props.get(DocumentBuilder.PARM_INPUT_XPATH_TABLE_PROPERTY_NAME);
+ String namespacePrefixes = props.get(Constants.NAMESPACE_PREFIX_PROPERTY_NAME);
+
+ org.jdom.Document inputXMLDoc = builder.buildDocument(Arrays.asList(parameters), inputParmsXPath,namespacePrefixes);
+ XMLOutputter out = new XMLOutputter();
+ return out.outputString(inputXMLDoc).trim();
+ }
+
+}
\ No newline at end of file
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/DocumentImpl.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/DocumentImpl.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/DocumentImpl.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,27 @@
+package org.teiid.translator.xml.streaming;
+
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+
+public class DocumentImpl implements org.teiid.translator.xml.Document {
+
+ private SQLXML xml;
+ private String cacheKey;
+
+ public DocumentImpl(SQLXML xml, String cacheKey) {
+ this.xml = xml;
+ this.cacheKey = cacheKey;
+ }
+
+ @Override
+ public InputStream getStream() throws SQLException{
+ return xml.getBinaryStream();
+ }
+
+ @Override
+ public String getCachekey() {
+ return cacheKey;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ElementProcessor.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ElementProcessor.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ElementProcessor.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,273 @@
+package org.teiid.translator.xml.streaming;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import nu.xom.Attribute;
+import nu.xom.DocType;
+import nu.xom.Element;
+import nu.xom.Node;
+import nu.xom.ProcessingInstruction;
+import nu.xom.Text;
+
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.CriteriaDesc;
+import org.teiid.translator.xml.Document;
+import org.teiid.translator.xml.ExecutionInfo;
+import org.teiid.translator.xml.OutputXPathDesc;
+import org.teiid.translator.xml.XMLPlugin;
+
+
+/**
+ * The ElementProcessor extracts data from a Node based upon XPaths defined in
+ * an ExecutionInfo (aka columns in a query request) ro build a single result row.
+ * In this context Node is equivalent to a table in the model.
+ *
+ * The processor is also responsible putting the cacheKey in the response row,
+ * inserting projected parameters, and applying = criteria.
+ *
+ */
+public class ElementProcessor {
+
+ private ExecutionInfo info;
+ private Object[] row;
+ private Map<String, OutputXPathDesc> resultPaths;
+ private OutputXPathDesc cacheKeyColumn;
+ private Map<String, String> namespacesToPrefixMap;
+ private boolean rowExcluded = false;
+
+ public ElementProcessor(ExecutionInfo info) throws TranslatorException {
+ this.info = info;
+ resultPaths = generateXPaths(info.getRequestedColumns());
+ namespacesToPrefixMap = info.getNamespaceToPrefixMap();
+ }
+
+ /**
+ * Iterate down the element getting column data from the matching paths.
+ * @param element the Node representing the Table in the model.
+ * @return a single result row
+ */
+ public Object[] process(Node element) {
+ setRowExcluded(false);
+ row = new Object[resultPaths.size()];
+ listChildren(element, "");
+ return row;
+ }
+
+ /**
+ * Iterate over the result and insert the ResponseId in the correct column
+ * @param xml the XML Document
+ * @param result the result batch for the query
+ */
+ public void insertResponseId(Document xml, List<Object[]> result) {
+ if (null != cacheKeyColumn) {
+ Object[] aRow;
+ if (!result.isEmpty()) {
+ for (Iterator<Object[]> iter = result.iterator(); iter.hasNext();) {
+ aRow = iter.next();
+ aRow[cacheKeyColumn.getColumnNumber()] = xml.getCachekey();
+ }
+ } else {
+ aRow = new Object[resultPaths.size()];
+ aRow[cacheKeyColumn.getColumnNumber()] = xml.getCachekey();
+ result.add(aRow);
+ }
+ }
+ }
+
+ private void insertProjectedParameters() {
+ //TODO insertProjectedParameters
+ }
+
+ /**
+ * Match the current path against the Map of requested paths and add
+ * the matches to the result row.
+ * @param current
+ * @param path
+ */
+ private void listChildren(Node current, String path) {
+
+ if(current.getDocument().equals(current.getParent())) {
+ path = getLocalQName(current);
+ }
+
+ if (current instanceof Element) {
+ Element temp = (Element) current;
+ for (int i = 0; i < temp.getAttributeCount(); i++) {
+ Attribute attribute = temp.getAttribute(i);
+ String attrPath = path + "/@" + getLocalQName(attribute);
+ if(resultPaths.containsKey(attrPath)) {
+ handleNode(attribute, attrPath);
+ if(isRowExcluded()) {
+ return;
+ }
+ }
+ }
+ }
+ else if (current instanceof ProcessingInstruction) {
+ ProcessingInstruction temp = (ProcessingInstruction) current;
+ temp.getTarget();
+ }
+ else if (current instanceof DocType) {
+ DocType temp = (DocType) current;
+ path = path + '/' + temp.getRootElementName();
+ }
+ else if (current instanceof Text) {
+ String textPath = path + "/text()";
+ if(resultPaths.containsKey(textPath)) {
+ handleNode(current, textPath);
+ if(isRowExcluded()) {
+ return;
+ }
+ }
+ }
+
+ for (int i = 0; i < current.getChildCount(); i++) {
+ if(isRowExcluded()) {
+ return;
+ }
+ Node next = current.getChild(i);
+ String childPath = path;
+ if (next instanceof Element) {
+ Element temp = (Element) next;
+ if(path.isEmpty()) {
+ childPath = getLocalQName(temp);
+ } else {
+ childPath= path + '/' + getLocalQName(temp);
+ }
+ }
+ listChildren(next, childPath);
+ }
+ }
+
+ /**
+ * Get the qualified name for the Element, but replace the prefixes
+ * from the actual doc with the matching prefix from the model. Without
+ * this prefix we can't do a proper path comparison.
+ * @throws TranslatorException
+ */
+ private String getLocalQName(Node node) {
+ String namespaceURI = null;
+ String localName = null;
+ if(node instanceof Element) {
+ Element element = (Element)node;
+ namespaceURI = element.getNamespaceURI();
+ localName = element.getLocalName();
+ } else if (node instanceof Attribute) {
+ Attribute attribute = (Attribute)node;
+ namespaceURI = attribute.getNamespaceURI();
+ localName = attribute.getLocalName();
+ }
+ if(null == namespaceURI) {
+ throw new Error("namespce URI not found in model namespaces");
+ }
+ String prefix = namespacesToPrefixMap.get(namespaceURI);
+ String result;
+ if(null == prefix) {
+ result = localName;
+ } else {
+ result = prefix + ':' + localName;
+ }
+ return result;
+ }
+
+ private void handleNode(Node node, String parentPath) {
+ OutputXPathDesc columnMetadata = resultPaths.get(parentPath);
+ int columnNum = columnMetadata.getColumnNumber();
+
+ if(!passesCriteriaCheck(info.getCriteria(), node.getValue(), columnNum)) {
+ setRowExcluded(true);
+ return;
+ } else {
+ //TODO: type conversion
+ row[columnNum] = node.getValue();
+ }
+ }
+
+ /**
+ * Tests the value against the criteria to determine if the value should be
+ * included in the result set.
+ *
+ * @param criteriaPairs
+ * @param value
+ * @param colNum
+ * @return
+ * @throws TranslatorException
+ */
+ private static boolean passesCriteriaCheck(List<CriteriaDesc> criteriaPairs,
+ String value, int colNum) {
+ // Need to test this code
+ for (CriteriaDesc criteria: criteriaPairs) {
+ if (colNum == criteria.getColumnNumber()) {
+ return evaluate(value, criteria);
+ }
+ }
+ return true;
+ }
+
+ public static boolean evaluate(String currentValue,
+ CriteriaDesc criteria) {
+ // this is the criteriaq for the col
+ List values = criteria.getValues();
+ for (Object criterion: values) {
+ if (criterion.equals(currentValue)) {
+ return true;
+ }
+ }
+ return false; // no matching value
+
+ }
+
+ private Map<String, OutputXPathDesc> generateXPaths(List<OutputXPathDesc> columns) throws TranslatorException {
+ Map<String, OutputXPathDesc> xpaths = new HashMap<String, OutputXPathDesc>();
+ for (OutputXPathDesc xPathDesc: columns) {
+ String xpathString = null;
+ if (!xPathDesc.isResponseId()) {
+ xpathString = xPathDesc.getXPath();
+ if (xpathString != null) {
+ xpathString = relativizeAbsoluteXpath(xpathString);
+ }
+ } else {
+ cacheKeyColumn = xPathDesc;
+ }
+ xpaths.put(xpathString, xPathDesc);
+ }
+ return xpaths;
+ }
+
+ private String relativizeAbsoluteXpath(String xpath)
+ throws TranslatorException {
+ String retval;
+ if (xpath.indexOf('|') != -1 && xpath.indexOf('(') == -1) {
+ // We are forcing compound XPaths to have parents, first reason is
+ // that we
+ // should never produce them in the importer, second reason is that
+ // it makes
+ // this function easier to fix under our current time constraints.
+ throw new TranslatorException(XMLPlugin.getString("Executor.unsupported.compound.xpath"));//$NON-NLS-1$
+ } else if (xpath.equals("/")) {//$NON-NLS-1$
+ retval = ".";//$NON-NLS-1$
+ } else if (xpath.startsWith("/") && !(xpath.startsWith("//"))) {//$NON-NLS-1$ //$NON-NLS-2$
+ retval = xpath.substring(1);
+ } else if (xpath.startsWith("(")) {//$NON-NLS-1$
+ xpath = xpath.replaceAll("\\(/", "("); // change (/ to ( //$NON-NLS-1$ //$NON-NLS-2$
+ xpath = xpath.replaceAll("\\|/", "|"); // change |/ to | //$NON-NLS-1$ //$NON-NLS-2$
+ retval = xpath;
+ } else {
+ retval = xpath;
+ }
+ return retval;
+ }
+
+ private void setRowExcluded(boolean excluded) {
+ rowExcluded = excluded;
+ row = null;
+ }
+
+ private boolean isRowExcluded() {
+ return rowExcluded;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/InvalidPathException.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/InvalidPathException.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/InvalidPathException.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,25 @@
+package org.teiid.translator.xml.streaming;
+
+public class InvalidPathException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ public InvalidPathException() {
+ }
+
+ public InvalidPathException(String message) {
+ super(message);
+ }
+
+ public InvalidPathException(Throwable cause) {
+ super(cause);
+ }
+
+ public InvalidPathException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ReaderFactory.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ReaderFactory.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/ReaderFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,32 @@
+package org.teiid.translator.xml.streaming;
+
+import org.teiid.translator.xml.IDGeneratingXmlFilter;
+import org.teiid.translator.xml.SAXFilterProvider;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLFilter;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLFilterImpl;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+
+
+public class ReaderFactory {
+
+ static public XMLReader getXMLReader(SAXFilterProvider filterProvider) throws SAXException {
+ XMLReader reader = XMLReaderFactory.createXMLReader();
+
+ if (filterProvider != null) {
+ XMLFilterImpl[] filters = filterProvider.getExtendedFilters();
+ for(int i = 0; i < filters.length; i++) {
+ XMLFilter filter = filters[i];
+ filter.setParent(reader);
+ reader = filter;
+ }
+ }
+
+ IDGeneratingXmlFilter filter = new IDGeneratingXmlFilter("");
+ filter.setParent(reader);
+ return filter;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingMultiPathFilter.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingMultiPathFilter.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingMultiPathFilter.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,375 @@
+package org.teiid.translator.xml.streaming;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import nu.xom.Attribute;
+import nu.xom.Document;
+import nu.xom.Element;
+import nu.xom.Node;
+import nu.xom.NodeFactory;
+import nu.xom.Nodes;
+import nux.xom.pool.XOMUtil;
+import nux.xom.xquery.StreamingTransform;
+
+public class StreamingMultiPathFilter {
+
+ private PathPackages pathPackages;
+
+ public StreamingMultiPathFilter(List<String> paths, Map<String, String> prefixes)
+ throws InvalidPathException {
+
+ pathPackages = new PathPackages();
+ Iterator<String> iter = paths.iterator();
+ while(iter.hasNext()) {
+ pathPackages.addPackage(getPathPackage(iter.next(), prefixes));
+ }
+ }
+
+ private PathPackage getPathPackage(String locationPath, Map<String, String> prefixes) throws InvalidPathException {
+ if (locationPath == null)
+ throw new InvalidPathException("locationPath must not be null");
+ if (locationPath.indexOf("//") >= 0)
+ throw new InvalidPathException("DESCENDANT axis is not supported");
+
+ String path = locationPath.trim();
+ if (path.startsWith("/")) path = path.substring(1);
+ if (path.endsWith("/")) path = path.substring(0, path.length() - 1);
+ path = path.trim();
+ if (path.equals("")) path = "*:*"; // fixup "match anything"
+ String[] localNames = path.split("/");
+ String[] namespaceURIs = new String[localNames.length];
+
+ // parse prefix:localName pairs and resolve prefixes to namespaceURIs
+ for (int i = 0; i < localNames.length; i++) {
+ int k = localNames[i].indexOf(':');
+ if (k >= 0 && localNames[i].indexOf(':', k+1) >= 0)
+ throw new InvalidPathException(
+ "QName must not contain more than one colon: "
+ + "qname='" + localNames[i] + "', path='" + path + "'");
+ if (k <= 0) {
+ namespaceURIs[i] = ""; // no namespace
+ } else {
+ String prefix = localNames[i].substring(0, k).trim();
+ if (k >= localNames[i].length() - 1)
+ throw new InvalidPathException(
+ "Missing localName for prefix: " + "prefix='"
+ + prefix + "', path='" + path + "', prefixes=" + prefixes);
+ if (prefix.equals("*")) {
+ // namespace is irrelevant (does not matter)
+ namespaceURIs[i] = null;
+ } else {
+ // lookup namespace of uri
+ if (prefixes == null)
+ throw new InvalidPathException("prefixes must not be null");
+ Object uri = prefixes.get(prefix);
+ if (uri == null)
+ throw new InvalidPathException(
+ "Missing namespace for prefix: "
+ + "prefix='" + prefix + "', path='" + path
+ + "', prefixes=" + prefixes);
+ namespaceURIs[i] = uri.toString().trim();
+ }
+ } // end if
+
+ localNames[i] = localNames[i].substring(k + 1).trim();
+ //if (localNames[i].equals("*")) {
+ // localName is irrelevant (does not matter)
+ // localNames[i] = null;
+ //}
+ }
+ return new PathPackage(localNames, namespaceURIs);
+ }
+
+ public NodeFactory createNodeFactory(NodeFactory childFactory, StreamingTransform transform) {
+ if (childFactory == null)
+ childFactory = XOMUtil.getIgnoreWhitespaceOnlyTextNodeFactory();
+ return new StreamingMultiPathFilterNodeFactory(pathPackages, childFactory, transform);
+ }
+
+
+ ///////////////////////////////////////////////////////////////////////////////
+ // Nested classes:
+ ///////////////////////////////////////////////////////////////////////////////
+ private class StreamingMultiPathFilterNodeFactory extends NodeFactory {
+
+ private PathPackages pathPackages;
+ private NodeFactory child;
+ private StreamingTransform transform;
+
+ private int level; // current nesting level = current location path step
+ private Element mismatch; // last element that did not match path
+
+ private final Nodes NONE = new Nodes();
+ private static final boolean DEBUG = false;
+
+ public StreamingMultiPathFilterNodeFactory(PathPackages packages,
+ NodeFactory child, StreamingTransform transform) {
+ this.pathPackages = packages;
+ this.child = child;
+ this.transform = transform;
+ }
+
+ @Override
+ public Document startMakingDocument() {
+ // reset state
+ level = -1;
+ mismatch = null;
+ return child.startMakingDocument();
+ }
+
+ @Override
+ public Element startMakingElement(String qname, String namespaceURI) {
+ level++;
+ if (mismatch == null && level < pathPackages.longestPath) {
+ if (!pathPackages.isRequired(level,qname, namespaceURI)) {
+ mismatch = super.startMakingElement(qname, namespaceURI);
+ return mismatch;
+ }
+ }
+ if (mismatch == null) {
+ return super.startMakingElement(qname, namespaceURI);
+ } else {
+ level--;
+ return null;
+ }
+ }
+
+ @Override
+ public Nodes finishMakingElement(Element elem) {
+ if (level == 0) {
+ // check for / match
+ if (pathPackages.isMatch(level,elem.getQualifiedName(), elem.getNamespaceURI())) {
+ return transformMatch(elem);
+ } //causes nu.xom.WellformednessException: Factory attempted to remove the root element on the request
+ mismatch = null;
+ level--;
+ return super.finishMakingElement(elem);
+ }
+ if (elem == mismatch) {
+ mismatch = null;
+ level--;
+ return NONE;
+ }
+ if (pathPackages.isMatch(level,elem.getQualifiedName(), elem.getNamespaceURI())) {
+ return transformMatch(elem);
+ }
+
+ level--;
+ if (level < pathPackages.getLongestPath() -1 && !hasChildElements(elem)) {
+ return NONE;
+ }
+ return super.finishMakingElement(elem);
+ }
+
+ private Nodes transformMatch(Element elem) {
+ level--;
+ if (transform == null) return super.finishMakingElement(elem);
+ Nodes results = transform.transform(elem);
+
+ if(results.size() == 0) {
+ results = new Nodes(elem);
+ } else {
+ for (int i = results.size(); --i >= 0; ) {
+ Node node = results.get(i);
+ if (node != elem) node.detach();
+ }
+ }
+ return results;
+ }
+
+ private boolean hasChildElements(Element elem) {
+ for (int i = elem.getChildCount(); --i >= 0;) {
+ if (elem.getChild(i) instanceof Element) return true;
+ }
+ return false;
+ }
+
+ @Override
+ public Nodes makeComment(String data) {
+ return mismatch == null ? child.makeComment(data) : NONE;
+ }
+
+ @Override
+ public Nodes makeText(String data) {
+ if (mismatch == null) {
+ if (level == 0 && isWhitespaceOnly(data))
+ return NONE; // avoid accumulating whitespace garbage in root element (i.e. avoid hidden memory leak)
+ else
+ return child.makeText(data);
+ }
+ return NONE;
+ }
+
+ @Override
+ public Nodes makeAttribute(String qname, String URI, String value, Attribute.Type type) {
+ return mismatch == null ? child.makeAttribute(qname, URI, value, type) : NONE;
+ }
+
+ @Override
+ public Nodes makeProcessingInstruction(String target, String data) {
+ return mismatch == null ? child.makeProcessingInstruction(target, data) : NONE;
+ }
+
+ @Override
+ public Nodes makeDocType(String rootElementName, String publicID, String systemID) {
+ return child.makeDocType(rootElementName, publicID, systemID);
+ }
+
+ @Override
+ public void finishMakingDocument(Document document) {
+ child.finishMakingDocument(document);
+ }
+
+ /** see XML spec */
+ private boolean isWhitespace(char c) {
+ switch (c) {
+ case '\t': return true;
+ case '\n': return true;
+ case '\r': return true;
+ case ' ' : return true;
+ default : return false;
+ }
+ }
+
+ private boolean isWhitespaceOnly(String str) {
+ for (int i=str.length(); --i >= 0; ) {
+ if (!isWhitespace(str.charAt(i))) return false;
+ }
+ return true;
+ }
+
+ }
+
+ /**
+ * Contains matched XML local names and namespace URIs for a single path.
+ *
+ *
+ */
+ private class PathPackage {
+
+ String[] localNames;
+ String[] namespaceURIs;
+
+ public PathPackage(String[] localNames, String[] namespaceURIs) {
+ this.localNames = localNames;
+ this.namespaceURIs = namespaceURIs;
+ }
+
+ /**
+ *
+ * @return the length of the path in local names.
+ */
+ public int getPathLength() {
+ return localNames.length;
+ }
+
+ /**
+ * Determines if an element is in the hierarchy of matching elements.
+ * @param level
+ * @param localName
+ * @param namespaceURI
+ * @return
+ */
+ public boolean isRequired(int level, String localName, String namespaceURI) {
+ String name = localNames[level];
+ String uri = namespaceURIs[level];
+ if(level == 0 && name.equals("*")) {
+ return true;
+ } else {
+ return
+ (name == null || name.equals(localName)) &&
+ (uri == null || uri.equals(namespaceURI));
+ }
+ }
+
+ public boolean hasLevelMatch(int level) {
+ return level == localNames.length -1;
+ }
+
+ public boolean isMatch(int level, String localName, String namespaceURI) {
+ if(level < getPathLength()) {
+ if(level == localNames.length -1) {
+ return isRequired(level, localName, namespaceURI);
+ }
+ }
+ return false;
+ }
+
+ }
+
+ private class PathPackages {
+
+ private List<PathPackage> packages;
+ private int longestPath = 0;
+
+ public PathPackages() {
+ packages = new ArrayList<PathPackage>();
+ }
+
+ public boolean isMatch(int level, String qname,
+ String namespaceURI) {
+ int i = qname.indexOf(':') + 1;
+ String localName = qname.substring(i);
+ Iterator<PathPackage> iter = packages.iterator();
+ while (iter.hasNext()) {
+ PathPackage pack = iter.next();
+ if(pack.isMatch(level, localName, namespaceURI)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasMatch(Element elem) {
+ return false;
+ }
+
+ public boolean hasLevelMatch(int level) {
+ Iterator<PathPackage> iter = packages.iterator();
+ while (iter.hasNext()) {
+ PathPackage pack = iter.next();
+ if(pack.hasLevelMatch(level)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * * Determines if an element is in the hierarchy of matching elements.
+ * @param level
+ * @param qname
+ * @param namespaceURI
+ * @return
+ */
+ public boolean isRequired(int level, String qname, String namespaceURI) {
+ int i = qname.indexOf(':') + 1;
+ String localName = qname.substring(i);
+ Iterator<PathPackage> iter = packages.iterator();
+ while (iter.hasNext()) {
+ PathPackage pack = iter.next();
+ if(level < pack.getPathLength() && pack.isRequired(level, localName, namespaceURI)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ PathPackages addPackage(PathPackage pack) {
+ if(null != pack) {
+ packages.add(pack);
+ if(pack.getPathLength() > longestPath) {
+ longestPath = pack.getPathLength();
+ }
+ }
+ return this;
+ }
+
+ public int getLongestPath() {
+ return longestPath;
+ }
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingResultsProducer.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingResultsProducer.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingResultsProducer.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,77 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml.streaming;
+
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.Document;
+import org.teiid.translator.xml.ExecutionInfo;
+import org.teiid.translator.xml.SAXFilterProvider;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+
+/**
+ * Converts a XML InputStream into an List containing results based upon data
+ * from ExecutionInfo. Elements of the List are Lists that represent rows in the table.
+ *
+ */
+public class StreamingResultsProducer {
+
+ private StreamingRowCollector collector;
+ private ElementProcessor elementProcessor;
+
+ public StreamingResultsProducer(ExecutionInfo info, SAXFilterProvider filter) throws TranslatorException {
+
+ Map<String, String> namespace = info.getPrefixToNamespacesMap();
+ XMLReader reader;
+ try {
+ reader = ReaderFactory.getXMLReader(filter);
+ } catch (SAXException e) {
+ throw new TranslatorException(e);
+ }
+
+ elementProcessor = new ElementProcessor(info);
+ collector = new StreamingRowCollector(namespace, reader, elementProcessor);
+ }
+
+ /**
+ *
+ * @param xml the xml Document
+ * @param xpaths the paths defined at the table level
+ * @return result set rows
+ * @throws TranslatorException
+ */
+ public List<Object[]> getResult(Document xml, List<String> xpaths) throws TranslatorException {
+
+ List<Object[]> rows;
+ try {
+ rows = collector.getElements(xml, xpaths);
+ } catch (InvalidPathException e) {
+ throw new TranslatorException(e);
+ }
+
+ return rows;
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingRowCollector.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingRowCollector.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/StreamingRowCollector.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,78 @@
+package org.teiid.translator.xml.streaming;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import nu.xom.Builder;
+import nu.xom.Element;
+import nu.xom.Nodes;
+import nux.xom.xquery.StreamingTransform;
+
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.Document;
+import org.xml.sax.XMLReader;
+
+
+
+/*
+ * StreamingRowCollector builds result rows from a single XML file for List of XPath
+ * like paths.
+ */
+public class StreamingRowCollector {
+
+ private Map<String, String> namespaces;
+ private ArrayList<Object[]> result;
+ private XMLReader reader;
+ private ElementProcessor elemProcessor;
+
+ public StreamingRowCollector(Map<String, String> namespaces, XMLReader reader, ElementProcessor elemProcessor) {
+ this.namespaces = namespaces;
+ this.reader = reader;
+ this.elemProcessor = elemProcessor;
+ this.result = new ArrayList<Object[]>();
+ }
+
+ /**
+ * Builds a list of rows from an InputStream
+ * @param xml
+ * @param xPaths
+ * @return
+ * @throws TranslatorException
+ * @throws InvalidPathException
+ */
+ public List<Object[]> getElements(Document xml, List<String> xPaths)
+ throws TranslatorException, InvalidPathException {
+ result.clear();
+ StreamingTransform myTransform = new StreamingTransform() {
+ public Nodes transform(Element item) {
+ if (item != null) {
+ parseRow(item);
+ }
+ return new Nodes();
+ // mark current element as subject to garbage collection
+ }
+ };
+
+ Builder builder = new Builder(reader, false, new StreamingMultiPathFilter(xPaths, namespaces).createNodeFactory(null, myTransform));
+ try {
+ builder.build(xml.getStream());
+ } catch (Exception e) {
+ throw new TranslatorException(e);
+ }
+ elemProcessor.insertResponseId(xml, result);
+ return result;
+ }
+
+ /**
+ * Create a result row from the element.
+ * @param item
+ */
+ private void parseRow(Element item) {
+ Object[] row = elemProcessor.process(item);
+ if(null != row && !Arrays.asList(row).isEmpty()) {
+ this.result.add(row);
+ }
+ }
+}
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/XPathSplitter.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/XPathSplitter.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/XPathSplitter.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,62 @@
+package org.teiid.translator.xml.streaming;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+
+
+
+public class XPathSplitter {
+
+ List<String> result;
+ char[] pathChars;
+
+ public List<String> split(String paths) throws InvalidPathException {
+ if(!validate(paths)) {
+ throw new InvalidPathException("This path is not valid: " + paths);
+ }
+ result = new ArrayList<String>();
+ if(-1 == paths.indexOf('(') || -1 == paths.indexOf(')')) {
+ result.add(paths);
+ } else {
+ pathChars = paths.toCharArray();
+ split(pathChars.length -1, "");
+ }
+ return new ArrayList<String>(new HashSet<String>(result));
+ }
+
+ private int split(int start, String suffix) {
+ boolean suffixSeek = true;
+ int end = start;
+ int index = start;
+ while (index >= 0) {
+ if(pathChars[index] == ')') {
+ if(end - index != 0 && pathChars[end] != ')' && suffixSeek) {
+ suffix = new String(pathChars, index +1, end - index).trim()
+ + suffix.trim();
+ }
+ suffixSeek = false;
+ index = end = split(index-1, suffix);
+ } else if(pathChars[index] == '(') {
+ if(pathChars[end] != ')' && end - index > 1) {
+ String path = new String(pathChars, index+1, end - index);
+ if (null != suffix && !suffix.isEmpty()) {
+ path = path.trim() + suffix.trim();
+ }
+ result.add(path);
+ }
+ //appendSuffix(suffix);
+ return index-1;
+ } else if(pathChars[index] == '|') {
+ end = index -1;
+ }
+ index--;
+ }
+ return index;
+ }
+
+ private static boolean validate(String paths) {
+ //TODO: add validation here
+ return true;
+ }
+}
Added: trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml (rev 0)
+++ trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+ <bean name="${project.artifactId}-${project.version}" class="org.teiid.templates.TranslatorDeploymentTemplate">
+ <property name="info"><inject bean="${project.artifactId}-templateinfo"/></property>
+ <property name="managedObjectFactory"><inject bean="ManagedObjectFactory"/></property>
+ </bean>
+
+ <bean name="${project.artifactId}-templateinfo" class="org.teiid.templates.TranslatorTemplateInfo">
+ <constructor factoryMethod="createTemplateInfo">
+ <factory bean="TranslatorDeploymentTemplateInfoFactory"/>
+ <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+ <parameter class="java.lang.Class">org.teiid.translator.xml.base.XMLExecutionFactory</parameter>
+ <parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
+ <parameter class="java.lang.String">${project.description}</parameter>
+ </constructor>
+ </bean>
+
+</deployment>
\ No newline at end of file
Property changes on: trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/xml/i18n.properties
===================================================================
--- trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/xml/i18n.properties (rev 0)
+++ trunk/connectors/translator-xml/src/main/resources/org/teiid/translator/xml/i18n.properties 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,76 @@
+#
+# JBoss, Home of Professional Open Source.
+# See the COPYRIGHT.txt file distributed with this work for information
+# regarding copyright ownership. Some portions may be licensed
+# to Red Hat, Inc. under one or more contributor license agreements.
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+# 02110-1301 USA.
+#
+
+XMLConnection.update.not.supported=XML update is not supported at this time
+XMLConnection.no.xml.procedures=XML procedures are not supported at this time
+XMLConnection.invalid.execution.mode=Invalid execution mode
+XMLConnector.state.not.set=Cannot create a Connection if the Connector's state is not set
+CriteriaDesc.value.not.found.for.param=Value not found for parameter
+CriteriaDesc.property.not.defaulted=Property value is not properly defaulted. System error.
+CriteriaDesc.allow.empty.not.defaulted=Property value for allowing empty values is not defaulted. System error.
+CriteriaDesc.input.xpath.not.defaulted=Property value for input XPath is not properly defaulted. System error.
+CriteriaDesc.parent.attribute.not.defaulted=Property value for parent attribute flag is not properly defaulted. System error.
+CriteriaDesc.attribute.name.not.defaulted=Property value for attribute name is not properly defaulted. System error.
+Executor.name.in.source.required=Name in source is required for all XMLRequest tables
+Executor.xml.docs.not.found=no XML documents found for processing
+Executor.saxpath.error.on.column=SAXPath error on column-level XPath for column {0}
+Executor.jaxen.error.on.selectsinglenode=Jaxen error on column-level selectSingleNode for column {0}
+Executor.saxpath.error.on.group=SAXPath error on group-level XPath
+Executor.jaxen.error.on.selectnodes=Jaxen error on group-level selectNodes
+Executor.jaxen.error.on.namespace.pairs=Jaxen error on namespace pairs {0} {1}
+Executor.unsupported.compound.xpath=Compound XPaths containing union operators (|) must be delimited by parentheses.
+Executor.default.namespace.not.allowed.in.xpath=Default namespaces not allowed in xpath queries; consider using an explicit prefix (see XPath spec section 2.3)
+Executor.IdTransform.xsl.not.found=Unable to find IdTransform.xsl file for unique ID generation
+Executor.unknown.document.producer=The DocumentProduce is an unknown type. Type is {0}
+OutputXPathDesc.name.in.source.required.on.column=Missing 'name in source' property for output column {0}
+OutputXPathDesc.property.value.not.defaulted=Property value is not properly defaulted. System error.
+XMLConnector.could.not.create.state=could not create state class
+XMLExecution.type.conversion.failure=Data value {0} cannot be converted to {1}. Processing will be terminated.
+XMLExecution.invalid.comparison=The following criteria cannot be executed because values are of different types: {0} = {1}
+DocumentBuilder.could.not.parse.namespaces=could not parse namespaces
+ValueReferenceImpl.ValueChunk.class.not.compatible=Unable to find implementation of ValueChunk for creating a CLOB
+HTTPExecutor.error.building.column=Error building input parameters
+QueryAnalyzer.multiple.responseid.supplied=Multiple different values for Response In field(s) supplied
+QueryAnalyzer.multiple.locations.supplied=Multiple different values for Location field(s) supplied
+document.expired.can.not.recreate=The cached document has expired and the connection factory is set to not recreate it
+HTTPExecutor.root.element.required=All XML requests require a root input element.
+Executor.error.decoding.request.id=Unable to decode request id
+Executor.unable.to.encode.response.id=Unable to encode response id
+HTTPExecutor.unable.to.recreate.request=Unable to recreate the request
+HTTPExecutor.dot.notation.not.allowed=Illegal use of dot notation in input XPaths
+Executor.unable.to.encode.response.id=Unable to serialize request object
+XMLConnector.NoLicense=License not found for XML Connectors
+DocumentBuilder.encoding.type.required=Native types are required when using RPC-encoded or Document-Encoded messages
+document.expired.can.not.recreate=The target document has expired from the cache.
+SecureConnectorState.error.loading.trust.deserializer=An error occured loading the Trust Deserializer class.
+SecureConnectorState.empty.trust.deserializer=The Trust Deserializer field in the connection factory is null or empty.
+SOAPConnectorStateImpl.empty.ENCODING_STYLE_PROPERTY_NAME=The Encoding Style in the connection factory is null or empty.
+SOAPConnectorStateImpl.invalid.ENCODING_STYLE_PROPERTY_NAME=The Encoding Style in the connection factory is not one of the expected values: {0}, {1}, {2}, {3}.
+SOAPConnectorStateImpl.empty.AUTH_USER_PROPERTY_NAME=Authentication is enabled but the Authentication User Name is null or empty.
+SOAPConnectorStateImpl.empty.AUTH_PASSWORD_PROPERTY_NAME=Authentication is enabled but the Authentication Password is null or empty.
+SOAPConnectorStateImpl.empty.CONNECTOR_EXCEPTION_ON_SOAP_FAULT=The Exception On Intra-Query Cache Expiration field in the connection factory is null or empty.
+InputStream_reset_not_supported=Mark/Reset are not supported on the InputStreamFilterClass
+No_outputs_allowed=No output parameter variables are allowed in the xml source connectors.
+source_name_not_supplied=Name In the Source property is not specified for the operation "{0}"; Failed to execute.
+executing_procedure=executing the procedure "{0}"
+file_not_supplied=XML file not found "{0}" for procedure execution "{1}"
+failed_to_generate_xml_request=Failed to generate the XML request input for the execution.
\ No newline at end of file
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/MockQueryPreprocessor.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/MockQueryPreprocessor.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/MockQueryPreprocessor.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+
+
+package org.teiid.translator.xml;
+
+import org.teiid.language.Select;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.xml.RequestPreprocessor;
+
+public class MockQueryPreprocessor implements RequestPreprocessor {
+
+ public MockQueryPreprocessor() {
+ super();
+ }
+
+ public Select preprocessQuery(Select query, RuntimeMetadata m_metadata, ExecutionContext exeContext) {
+ return query;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/ProxyObjectFactory.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/ProxyObjectFactory.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/ProxyObjectFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,215 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.io.File;
+import java.io.StringReader;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import org.jdom.Document;
+import org.jdom.input.SAXBuilder;
+import org.mockito.Mockito;
+import org.teiid.language.Select;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.ExecutionContext;
+
+import com.metamatrix.cdk.api.TranslationUtility;
+/**
+ *
+ */
+public class ProxyObjectFactory {
+
+ public static final String JMS_DESTINATION = "dynamicQueues/topic1";
+ public static final String INITIAL_CONTEXT_FACTORY = "org.apache.activemq.jndi.ActiveMQInitialContextFactory";
+ private static String docFolder = null;
+
+
+ private ProxyObjectFactory() {
+
+ }
+
+
+// public static HTTPManagedConnectionFactory getHTTPTestConnectorEnvironment(Properties props) {
+// if (props == null) {
+// props = getDefaultHTTPProps();
+// }
+// HTTPManagedConnectionFactory env = new HTTPManagedConnectionFactory();
+// PropertiesUtils.setBeanProperties(env, props, null);
+// return env;
+// }
+
+ public static ExecutionContext getDefaultSecurityContext() {
+ return Mockito.mock(ExecutionContext.class);
+ }
+
+ public static ExecutionContext getDefaultExecutionContext() {
+ ExecutionContext ec = Mockito.mock(ExecutionContext.class);
+ Mockito.stub(ec.getRequestIdentifier()).toReturn("request");
+ Mockito.stub(ec.getPartIdentifier()).toReturn("testPartId");
+
+ return ec;
+ }
+
+ public static ExecutionContext getExecutionContext(String requestID, String partId) {
+ ExecutionContext ec = Mockito.mock(ExecutionContext.class);
+ Mockito.stub(ec.getRequestIdentifier()).toReturn(requestID);
+ Mockito.stub(ec.getPartIdentifier()).toReturn(partId);
+
+ return ec;
+ }
+
+
+//
+// public static Properties getDefaultHTTPProps() {
+// Properties testHTTPProps = new Properties();
+// testHTTPProps.setProperty(XMLConnectorStateImpl.CACHE_ENABLED, Boolean.TRUE.toString());
+// testHTTPProps.setProperty(HTTPConnectorState.URI, "http://localhost:8673"); //$NON-NLS-1$
+// testHTTPProps.setProperty(HTTPConnectorState.REQUEST_TIMEOUT, "60"); //$NON-NLS-1$
+// testHTTPProps.setProperty(XMLConnectorState.STATE_CLASS_PROP, "com.metamatrix.connector.xml.http.HTTPConnectorState"); //$NON-NLS-1$
+// testHTTPProps.setProperty(HTTPConnectorState.HTTP_BASIC_USER, "");
+// testHTTPProps.setProperty(HTTPConnectorState.HTTP_BASIC_PASSWORD, "");
+// testHTTPProps.setProperty(SecureConnectorState.SECURITY_DESERIALIZER_CLASS, "com.metamatrix.connector.xml.http.DefaultTrustDeserializer");
+// testHTTPProps.setProperty(HTTPConnectorState.PARAMETER_METHOD, HTTPConnectorState.PARAMETER_NAME_VALUE);
+// testHTTPProps.setProperty(HTTPConnectorState.ACCESS_METHOD, HTTPConnectorState.GET);
+// return testHTTPProps;
+// }
+
+
+//
+// public static Properties getDefaultNameValueRequestProps() {
+// Properties defaultHTTPProps = getDefaultHttpProps();
+// defaultHTTPProps.setProperty(HTTPConnectorState.PARAMETER_METHOD, HTTPConnectorState.PARAMETER_NAME_VALUE);
+// return defaultHTTPProps;
+// }
+
+// public static Properties getDefaultHttpProps() {
+// Properties testHTTPProps = new Properties();
+// testHTTPProps.put(XMLConnectorStateImpl.CACHE_ENABLED, Boolean.TRUE);
+// testHTTPProps.put(XMLConnectorStateImpl.CONNECTOR_CAPABILITES, "com.metamatrix.connector.xml.base.XMLCapabilities");
+// testHTTPProps.setProperty(XMLConnectorState.STATE_CLASS_PROP, "com.metamatrix.connector.xml.http.HTTPConnectorState");
+// testHTTPProps.setProperty(XMLConnectorStateImpl.QUERY_PREPROCESS_CLASS, "com.metamatrix.connector.xml.base.NoQueryPreprocessing");
+// testHTTPProps.setProperty(XMLConnectorStateImpl.SAX_FILTER_PROVIDER_CLASS, "com.metamatrix.connector.xml.base.NoExtendedFilters");
+// testHTTPProps.setProperty(HTTPConnectorState.ACCESS_METHOD, HTTPConnectorState.GET);
+// testHTTPProps.setProperty(HTTPConnectorState.PARAMETER_METHOD, HTTPConnectorState.PARAMETER_XML_REQUEST);
+// testHTTPProps.setProperty(HTTPConnectorState.URI, "http://0.0.0.0:8673");
+// //testHTTPProps.setProperty(HTTPConnectorState.PROXY_URI, "http://0.0.0.0:8673");
+// testHTTPProps.setProperty(HTTPConnectorState.REQUEST_TIMEOUT, "60");
+// testHTTPProps.setProperty(HTTPConnectorState.XML_PARAMETER_NAME, "XMLRequest");
+// testHTTPProps.setProperty(HTTPConnectorState.HTTP_BASIC_USER, "");
+// testHTTPProps.setProperty(HTTPConnectorState.HTTP_BASIC_PASSWORD, "");
+// testHTTPProps.setProperty(SecureConnectorState.SECURITY_DESERIALIZER_CLASS, "com.metamatrix.connector.xml.http.DefaultTrustDeserializer");
+// return testHTTPProps;
+// }
+
+
+
+
+// public static XMLConnector getDefaultXMLConnector() {
+// XMLConnector conn;
+// try {
+// conn = new XMLConnector();
+// conn.initialize(getDefaultTestConnectorEnvironment());
+// } catch (ConnectorException ce) {
+// ce.printStackTrace();
+// conn = null;
+// }
+// return conn;
+// }
+
+// public static XMLConnector getDefaultHTTPConnector(Properties props) {
+// XMLConnector conn;
+// try {
+// conn = new XMLConnector();
+// conn.initialize(getHTTPTestConnectorEnvironment(props));
+// } catch (ConnectorException ce) {
+// ce.printStackTrace();
+// conn = null;
+// }
+// return conn;
+// }
+//
+// public static XMLConnectionImpl getDefaultXMLConnection() {
+// XMLConnectionImpl connection;
+// try {
+// ExecutionContext ctx = getDefaultSecurityContext();
+// connection = (XMLConnectionImpl) getDefaultXMLConnector().getConnection();
+// } catch (ConnectorException ce) {
+// connection = null;
+// } catch (NullPointerException ne) {
+// connection = null;
+// }
+// return connection;
+// }
+//
+// private static XMLConnectionImpl getHTTPXMLConnection(Properties props) {
+// XMLConnectionImpl connection;
+// try {
+// ExecutionContext ctx = getDefaultSecurityContext();
+// connection = (XMLConnectionImpl) getDefaultHTTPConnector(props).getConnection();
+// } catch (ConnectorException ce) {
+// connection = null;
+// } catch (NullPointerException ne) {
+// connection = null;
+// }
+// return connection;
+// }
+
+
+ public static Select getDefaultIQuery(String vdbPath, String queryString) {
+ TranslationUtility transUtil = new TranslationUtility(vdbPath);
+ Select query = (Select) transUtil.parseCommand(queryString);
+ return query;
+ }
+
+ public static RuntimeMetadata getDefaultRuntimeMetadata(String vdbPath) {
+ TranslationUtility transUtil = new TranslationUtility(vdbPath);
+ RuntimeMetadata meta = transUtil.createRuntimeMetadata();
+ return meta;
+ }
+
+ public static Document getDefaultDocument() throws Exception {
+ Document doc = null;
+ SAXBuilder builder = new SAXBuilder();
+ StringReader reader = new StringReader("<foo><bar>baz</bar></foo>");
+ doc = builder.build(reader);
+ return doc;
+ }
+
+ public static String getStateCollegeVDBLocation() {
+ return getDocumentsFolder() + "/UnitTests.vdb";
+ }
+
+ public static String getDocumentsFolder() {
+ //is the test running locally or in CruiseControl?
+ if (docFolder == null) {
+ URL url = ProxyObjectFactory.class.getClassLoader().getResource("documents");
+ try {
+ docFolder = new File(url.toURI()).toString();
+ } catch (URISyntaxException e) {
+ }
+ }
+ return docFolder;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCriteriaDesc.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCriteriaDesc.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCriteriaDesc.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,608 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.BaseInCondition;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Condition;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.LanguageUtil;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.CriteriaDesc;
+
+
+/**
+ *
+ */
+public class TestCriteriaDesc extends TestCase {
+
+ private static String vdbPath;
+ private static final String QUERY = "select RequiredDefaultedParam from CriteriaDescTable " //$NON-NLS-1$
+ + "where RequiredDefaultedParam in ('foo') order by RequiredDefaultedParam"; //$NON-NLS-1$
+ private static final String VALUE = "value1"; //$NON-NLS-1$
+
+
+
+ static {
+ vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ }
+
+ public void testGetCriteriaDescForColumn() throws Exception {
+ //case 1: values provided
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where RequiredDefaultedParam in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnDefaultedValue() throws Exception {
+ //case 2: param, required, defaulted
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnNoCriteria() throws Exception {
+ //case 3: param, not required, not defaulted, not allowed empty
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select OptionalNotAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNull("CriteriaDesc is not null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnAllowEmpty() throws Exception {
+ //case 4: param, not required, not defaulted, allowed empty
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select OptionalAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ final int colLocation = 0;
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnError() {
+ //case 5: param, required, not defaulted
+ try {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredUndefaultedParam from CriteriaDescTable"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ fail("exception not thrown"); //$NON-NLS-1$
+ } catch (TranslatorException ce) {
+ }
+ }
+
+ public void testGetCriteriaDescForColumnNotParam() throws Exception {
+ //case 6: not a param
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select OutputColumn from CriteriaDescTable"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNull("CriteriaDesc is not null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnCompare() throws Exception {
+ //case 7: compare criteria
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where RequiredDefaultedParam = 'foo'"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+
+ public void testGetCriteriaDescForColumnMultiElement() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select MultiElementParam from CriteriaDescTable where MultiElementParam in ('foo','bar')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ String multiplicityStr = elem.getProperties().get(
+ CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnDelimited() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select DelimitedParam from CriteriaDescTable where DelimitedParam in ('foo','bar')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ String multiplicityStr = elem.getProperties().get(
+ CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnLikeSearchable() {
+ try {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select LikeSearchableParam from CriteriaDescTable where LikeSearchableParam in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ String multiplicityStr = elem.getProperties().get(
+ CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ fail("should not be able to handle default value"); //$NON-NLS-1$
+ } catch (TranslatorException ce) {
+ }
+ }
+
+ public void testGetCriteriaDescForColumnUnlikeSearchable() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select UnlikeSearchableParam from CriteriaDescTable where UnlikeSearchableParam in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ String multiplicityStr = elem.getProperties().get(
+ CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ }
+
+ public void testGetCriteriaDescForColumnUnsearchable() {
+ try {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select UnsearchableParam from CriteriaDescTable where UnsearchableParam in ('foo','bar')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ String multiplicityStr = elem.getProperties().get(
+ CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME);
+ CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ fail("should not be able to handle default value"); //$NON-NLS-1$
+ } catch (TranslatorException ce) {
+ }
+ }
+
+ public void testGetCriteriaDescForColumnLike() throws Exception {
+ //case 1: values provided
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where RequiredDefaultedParam like 'foo'"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnNotEquals() throws Exception {
+ //case 1: values provided
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where RequiredDefaultedParam != 'foo'"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnLiteral() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where concat(RequiredDefaultedParam, 'bar') in('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnNameMatchFailure() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where AttributeParam in('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+
+ public void testGetCriteriaDescForColumnLeftLiteral() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable " //$NON-NLS-1$
+ + "where concat('bar', 'foo') = concat('bar', RequiredDefaultedParam)"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnTwoElements() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where OutputColumn = RequiredDefaultedParam"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnLeftElementEqualsLiteral() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where AttributeParam = 'foo'"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetCriteriaDescForColumnLeftElementEqualsNonLiteral() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where" //$NON-NLS-1$
+ + " RequiredDefaultedParam = concat('foo', OutputColumn)"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertNotNull("CriteriaDesc is null", desc); //$NON-NLS-1$
+ }
+
+ public void testGetInputXPathNoXpath() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select BadNoInputXpath from CriteriaDescTable where BadNoInputXpath in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertEquals(desc.getColumnName(), desc.getInputXpath());
+ }
+
+
+ public void testGetInputXPathEmptyXpath() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select BadEmptyInputXPath from CriteriaDescTable where BadEmptyInputXPath in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertEquals(desc.getColumnName(), desc.getInputXpath());
+ }
+
+ public void testGetDataAttributeNameEmptyName() throws Exception {
+ assertNotNull("vdb path is null", vdbPath); //$NON-NLS-1$
+ String query = "select BadNoDataAttributeName from CriteriaDescTable where BadNoDataAttributeName in ('foo')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertEquals("", desc.getDataAttributeName()); //$NON-NLS-1$
+ }
+
+ public void testGetInputXpath() throws TranslatorException {
+ String query = "select RequiredDefaultedParam from CriteriaDescTable"; //$NON-NLS-1$
+ String inputXPath = "/req/default/value"; //$NON-NLS-1$
+ CriteriaDesc desc = createCriteriaDesc(query);
+ assertNotNull("CriteriaDesc is null", desc.getInputXpath()); //$NON-NLS-1$
+ assertEquals(inputXPath, desc.getInputXpath());
+ }
+
+ public void testIsUnlimited() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertFalse("Criteria is flagged as unlimited", desc.isUnlimited()); //$NON-NLS-1$
+ }
+
+ public void testIsAutoIncrement() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertFalse("criterion is flagged as autoIncrement", desc.isAutoIncrement()); //$NON-NLS-1$
+ }
+
+ public void testIsParentAttribute() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ //before its inited
+ assertFalse("criterion is flagged as an attribute", desc.isParentAttribute()); //$NON-NLS-1$
+ //and after for code coverage
+ assertFalse("criterion is flagged as an attribute", desc.isParentAttribute()); //$NON-NLS-1$
+ }
+
+ public void testIsEnumeratedAttribute() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertFalse("criterion is an enumerated attribute", desc.isEnumeratedAttribute()); //$NON-NLS-1$
+ }
+
+ public void testAllowEmptyValueFalse() throws TranslatorException {
+ String query = "select OptionalNotAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ CriteriaDesc desc = createCriteriaDesc(query);
+ assertFalse("criterion should not allow for empty values", desc.allowEmptyValue()); //$NON-NLS-1$
+ }
+
+ public void testAllowEmptyValueTrue() throws TranslatorException {
+ String query = "select OptionalAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ CriteriaDesc desc = createCriteriaDesc(query);
+ //before init
+ assertTrue("criterion should allow for empty values", desc.allowEmptyValue()); //$NON-NLS-1$
+ //and after for code coverage
+ assertTrue("criterion should allow for empty values", desc.allowEmptyValue()); //$NON-NLS-1$
+ }
+
+ public void testIsDataInAttributeFalse() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertFalse("criterion is flagged as data in attribute", desc.isDataInAttribute()); //$NON-NLS-1$
+ }
+
+ public void testIsDataInAttributeTrue() throws TranslatorException {
+ String query = "select AttributeParam from CriteriaDescTable where AttributeParam in ('foo')"; //$NON-NLS-1$
+ CriteriaDesc desc = createCriteriaDesc(query);
+ assertTrue("criterion is not flagged as data in attribute", desc.isDataInAttribute()); //$NON-NLS-1$
+ }
+
+ public void testGetDataAttributeName() throws TranslatorException {
+ String query = "select AttributeColumn from TestTable where AttributeColumn in ('foo')"; //$NON-NLS-1$
+ Column elem = getElement(query);
+ String attributeName = "myAttribute"; //$NON-NLS-1$
+ ArrayList list = new ArrayList();
+ list.add(VALUE);
+ CriteriaDesc desc = new CriteriaDesc(elem, list);
+ assertNotNull("CriteriaDesc is null", desc.getDataAttributeName()); //$NON-NLS-1$
+ assertTrue("column name mismatch - expected " + attributeName //$NON-NLS-1$
+ + " returned " + desc.getDataAttributeName(), //$NON-NLS-1$
+ desc.getDataAttributeName().equals(attributeName));
+ }
+
+ public void testGetValues() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ List values = desc.getValues();
+ assertNotNull("Values list is null", values); //$NON-NLS-1$
+ assertEquals(values.get(0), VALUE);
+ }
+
+ public void testGetNumberOfValues() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertEquals(1, desc.getNumberOfValues());
+ }
+
+ public void testGetCurrentIndexValue() throws TranslatorException {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ assertEquals(VALUE, desc.getCurrentIndexValue());
+ }
+
+ public void testGetCurrentIndexValueEnumerated() throws Exception {
+ String query = "select DelimitedParam from CriteriaDescTable where DelimitedParam in ('foo', 'bar')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertEquals("There should be two values" , 2, desc.getNumberOfValues()); //$NON-NLS-1$
+ assertEquals("foo", desc.getCurrentIndexValue()); //$NON-NLS-1$
+ desc.incrementIndex();
+ assertEquals("bar", desc.getCurrentIndexValue()); //$NON-NLS-1$
+ }
+
+ public void testIncrementIndexEnumerated() throws Exception {
+ String query = "select DelimitedParam from CriteriaDescTable where DelimitedParam in ('foo', 'bar')"; //$NON-NLS-1$
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ RuntimeMetadata metadata = ProxyObjectFactory.getDefaultRuntimeMetadata(vdbPath);
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, iquery);
+ assertTrue("We should be able to increment this CriteriaDesc", desc.incrementIndex()); //$NON-NLS-1$
+ }
+
+ public void testGetCurrentIndexValueNoValue() throws Exception {
+ final String query = "select OptionalAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ Column elem = getElement(query);
+ ArrayList list = new ArrayList();
+ CriteriaDesc desc = new CriteriaDesc(elem, list);
+ assertEquals("", desc.getCurrentIndexValue()); //$NON-NLS-1$
+ }
+
+ public void testGetCurrentIndexValueNoValueNotEmpty() throws Exception {
+ final String query = "select OptionalNotAllowedEmptyParam from CriteriaDescTable"; //$NON-NLS-1$
+ Column elem = getElement(query);
+ ArrayList list = new ArrayList();
+ CriteriaDesc desc = new CriteriaDesc(elem, list);
+ assertNull(desc.getCurrentIndexValue());
+ }
+
+ public void testIncrementIndex() throws Exception {
+ final String value2 = "value2"; //$NON-NLS-1$
+ String query = "select MultiCol from MultiTable where MultiCol in ('" + VALUE + "', '" + value2 + "')"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Column elem = getElement(query);
+ ArrayList list = new ArrayList();
+ list.add(VALUE);
+ list.add(value2);
+ CriteriaDesc desc = new CriteriaDesc(elem, list);
+ assertEquals(VALUE, desc.getCurrentIndexValue());
+ assertTrue("index increment failed", desc.incrementIndex()); //$NON-NLS-1$
+ assertEquals(value2, desc.getCurrentIndexValue());
+ assertFalse("index went beyond number of values", desc.incrementIndex()); //$NON-NLS-1$
+ }
+
+ public void testResetIndex() throws Exception {
+ CriteriaDesc desc = createCriteriaDesc(QUERY);
+ desc.resetIndex();
+ }
+
+ public void testNameMatch() {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ Condition crit = query.getWhere();
+ List criteriaList = LanguageUtil.separateCriteriaByAnd(crit);
+ Iterator criteriaIter = criteriaList.iterator();
+ Expression expr = null;
+ while (criteriaIter.hasNext()) {
+ Condition criteriaSeg = (Condition) criteriaIter.next();
+ if (criteriaSeg instanceof Comparison) {
+ Comparison compCriteria = (Comparison) criteriaSeg;
+ expr = compCriteria.getLeftExpression();
+ break;
+ } else if (criteriaSeg instanceof BaseInCondition) {
+ expr = ((BaseInCondition) criteriaSeg).getLeftExpression();
+ break;
+ }
+ }
+ final String column = "CriteriaDescTable.RequiredDefaultedParam"; //$NON-NLS-1$
+ assertTrue("column name mismatch - expected " + column + " returned " + expr, //$NON-NLS-1$ //$NON-NLS-2$
+ CriteriaDesc.nameMatch(expr, column));
+ }
+
+ public void testStringifyCriteria() {
+ String withQuotes = "'foodle doodle'"; //$NON-NLS-1$
+ String withoutQuotes = "foodle doodle"; //$NON-NLS-1$
+ assertEquals("stringify failed", withoutQuotes, CriteriaDesc.stringifyCriteria(withQuotes)); //$NON-NLS-1$
+ }
+
+ public void testStringifyCriteriaDoubleQuotes() {
+ String control = "foodle doodle"; //$NON-NLS-1$
+ String test = "\"foodle doodle\""; //$NON-NLS-1$
+ assertEquals("stringify failed", control, CriteriaDesc.stringifyCriteria(test)); //$NON-NLS-1$
+ }
+
+ public void testStringifyCriteriaSingleQuote() {
+ String test = "'ello govnor."; //$NON-NLS-1$
+ assertEquals("stringify failed", test, CriteriaDesc.stringifyCriteria(test)); //$NON-NLS-1$
+ }
+
+ public void testStringifyCriteriaSingleDoubleQuote() {
+ String test = "\"ello govnor."; //$NON-NLS-1$
+ assertEquals("stringify failed", test, CriteriaDesc.stringifyCriteria(test)); //$NON-NLS-1$
+ }
+
+
+ public void testBadTableSelect() throws TranslatorException {
+ String tempVdbpath = vdbPath;
+ vdbPath = ProxyObjectFactory.getDocumentsFolder() + "/UnitTests.vdb"; //$NON-NLS-1$
+ try {
+ createCriteriaDesc("select BadCol1 from BadTable"); //$NON-NLS-1$
+ } finally {
+ vdbPath = tempVdbpath;
+ }
+ }
+
+ public void testElementAllowsEmpty() throws TranslatorException {
+ String tempVdbpath = vdbPath;
+ vdbPath = ProxyObjectFactory.getDocumentsFolder() + "/UnitTests.vdb"; //$NON-NLS-1$
+ String strQuery = "Select Balance from Response"; //$NON-NLS-1$
+ try {
+ Column elem = getElement(strQuery);
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ CriteriaDesc desc = CriteriaDesc.getCriteriaDescForColumn(elem, query);
+ } finally {
+ vdbPath = tempVdbpath;
+ }
+ }
+
+
+ private CriteriaDesc createCriteriaDesc(String query) throws TranslatorException {
+ Column elem = getElement(query);
+ ArrayList list = new ArrayList();
+ list.add(VALUE);
+ CriteriaDesc desc = new CriteriaDesc(elem, list);
+ return desc;
+ }
+
+ private Column getElement(String query) throws TranslatorException {
+ return getElement(query, 0);
+ }
+
+ private Column getElement(String query, int colLocation)
+ throws TranslatorException {
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ Column elem = ((ColumnReference) expr).getMetadataObject();
+ return elem;
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestElementCollector.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestElementCollector.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestElementCollector.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,84 @@
+package org.teiid.translator.xml;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLXML;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import org.teiid.core.types.InputStreamFactory;
+import org.teiid.core.types.SQLXMLImpl;
+import org.teiid.language.Select;
+import org.teiid.translator.xml.Document;
+import org.teiid.translator.xml.streaming.DocumentImpl;
+import org.teiid.translator.xml.streaming.ElementProcessor;
+import org.teiid.translator.xml.streaming.ReaderFactory;
+import org.teiid.translator.xml.streaming.StreamingRowCollector;
+
+
+@SuppressWarnings("nls")
+public class TestElementCollector extends TestCase {
+
+ StreamingRowCollector builder;
+ String filename = ProxyObjectFactory.getDocumentsFolder() + "/purchaseOrders.xml";
+ String vdbPath = ProxyObjectFactory.getDocumentsFolder() + "/File/purchase_orders.vdb";
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ Map prefixes = new HashMap<String, String>();
+ prefixes.put("po", "http://www.example.com/PO1");
+ prefixes.put("xsd", "http://www.w3.org/2001/XMLSchema");
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, "SELECT * FROM po_list.ITEM");
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ ExecutionInfo info = analyzer.getExecutionInfo();
+ ElementProcessor processor = new ElementProcessor(info);
+ builder = new StreamingRowCollector(prefixes, ReaderFactory.getXMLReader(null), processor);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ builder = null;
+ }
+
+ public void testGetTables1() {
+ String path = "/po:purchaseOrders/order/items/item";
+ int itemCount = 5968;
+ try {
+ Document doc = new DocumentImpl(getSQLXML(new FileInputStream(filename)), "foo");
+ List result = builder.getElements(doc, Arrays.asList(path));
+ assertEquals(itemCount, result.size());
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testGetRoot() {
+ String path = "/";
+ int itemCount = 1;
+ try {
+ Document doc = new DocumentImpl(getSQLXML(new FileInputStream(filename)), "foo");
+ List result = builder.getElements(doc, Arrays.asList(path));
+ assertEquals(itemCount, result.size());
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ }
+
+ SQLXML getSQLXML(final InputStream in) {
+ InputStreamFactory isf = new InputStreamFactory("ISO-8859-1") {
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return in;
+ }
+ };
+ return new SQLXMLImpl(isf);
+ }
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestExecutionInfo.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestExecutionInfo.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestExecutionInfo.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,191 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.Select;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.ExecutionInfo;
+import org.teiid.translator.xml.QueryAnalyzer;
+
+/**
+ *
+ */
+public class TestExecutionInfo extends TestCase {
+
+ /**
+ * Constructor for ExecutionInfoTest.
+ * @param arg0
+ */
+
+ private static final String QUERY = "select Company_id from Company where Company_id = 'MetaMatrix' order by Company_id";
+
+ private ExecutionInfo m_info;
+
+ //removing hansel while testing clover
+/*
+ public static Test suite() {
+ return new CoverageDecorator(ExecutionInfoTest.class, new Class[] {ExecutionInfo.class});
+
+ }
+*/
+
+ public TestExecutionInfo(String arg0) {
+ super(arg0);
+ }
+
+ @Override
+ public void setUp() throws TranslatorException {
+ String vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ m_info = analyzer.getExecutionInfo();
+
+ }
+
+ @Override
+ public void tearDown() {
+ m_info = null;
+ }
+
+ public void testExecutionInfo() {
+ ExecutionInfo info = new ExecutionInfo();
+ assertNotNull("ExecutionInfo is null", info);
+ assertEquals(0, info.getColumnCount());
+ assertNotNull(info.getCriteria());
+ assertNotNull(info.getOtherProperties());
+ assertNotNull(info.getParameters());
+ assertNotNull(info.getRequestedColumns());
+ assertNotNull(info.getTableXPath());
+ }
+
+ public void testGetTableXPath() {
+ assertEquals("/Mydata/company", m_info.getTableXPath());
+ }
+
+ public void testGetRequestedColumns() {
+ List columns = m_info.getRequestedColumns();
+ assertNotNull("requestedColumns list is null", columns);
+ assertEquals(1, columns.size());
+ }
+
+ public void testGetColumnCount() {
+ assertEquals(1, m_info.getColumnCount());
+ }
+
+ public void testGetParameters() {
+ List params = m_info.getParameters();
+ assertNotNull("Param list is null", params);
+ assertEquals(0, params.size());
+ }
+
+ public void testGetCriteria() {
+ String vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ //String query = "Select AttributeColumn from TestTable where AttributeColumn in ('foo')";
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(iquery);
+ analyzer.analyze();
+ ExecutionInfo info = analyzer.getExecutionInfo();
+ List crits = info.getCriteria();
+ assertNotNull("Criteria list is null", crits);
+ assertEquals(1, crits.size());
+ } catch (TranslatorException ce) {
+ ce.printStackTrace();
+ fail(ce.getMessage());
+ }
+ }
+
+ public void testGetOtherProperties() throws TranslatorException {
+ String vdbPath = ProxyObjectFactory.getDocumentsFolder() + "/UnitTests.vdb";
+ String strQuery = "select * from Response";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ ExecutionInfo info = analyzer.getExecutionInfo();
+ Map<String, String> props = info.getOtherProperties();
+ assertFalse("properties are empty", props.isEmpty());
+ info.setOtherProperties(null);
+ assertNotNull(info.getOtherProperties());
+ }
+
+ public void testSetTableXPath() {
+ String xpath = "/new/path";
+ m_info.setTableXPath(xpath);
+ assertEquals(xpath, m_info.getTableXPath());
+ m_info.setTableXPath("");
+ assertNull(m_info.getTableXPath());
+ }
+
+ public void testSetRequestedColumns() {
+ String reqCol = "Company_id";
+ ArrayList reqCols = new ArrayList();
+ reqCols.add(reqCol);
+ m_info.setRequestedColumns(reqCols);
+ assertEquals(reqCol, m_info.getRequestedColumns().get(0));
+ }
+
+ public void testSetColumnCount() {
+ final int count = 3;
+ m_info.setColumnCount(count);
+ assertEquals(count, m_info.getColumnCount());
+
+ }
+
+ public void testSetParameters() {
+ String param = "[Company_id]";
+ ArrayList params = new ArrayList();
+ params.add(param);
+ m_info.setParameters(params);
+ assertEquals(param, m_info.getParameters().get(0));
+ }
+
+ public void testSetCriteria() {
+ String crit = "Company_id";
+ ArrayList crits = new ArrayList();
+ crits.add(crit);
+ m_info.setParameters(crits);
+ assertEquals(crit, m_info.getParameters().get(0));
+ }
+
+ public void testSetOtherProperties() {
+ String prop = "myProp";
+ String key = "foo";
+ Map<String, String> props = new HashMap<String, String>();
+ props.put(key, prop);
+ m_info.setOtherProperties(props);
+ assertEquals(prop, m_info.getOtherProperties().get(key));
+
+ m_info.setOtherProperties(null);
+ assertNotNull("OtherProerties was set to null", m_info.getOtherProperties());
+ assertEquals(0, m_info.getOtherProperties().size());
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestOutputXPathDesc.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestOutputXPathDesc.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestOutputXPathDesc.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,172 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Condition;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.LanguageUtil;
+import org.teiid.language.Literal;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.OutputXPathDesc;
+
+
+/**
+ *
+ */
+public class TestOutputXPathDesc extends TestCase {
+
+
+ private static String vdbPath;
+ private static final String QUERY = "select OutputColumn from CriteriaDescTable where"
+ + " OutputColumn in ('foo') order by OutputColumn";
+
+ static {
+ vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ }
+
+// removing hansel while testing clover
+
+/*
+ public static Test suite() {
+ return new CoverageDecorator(OutputXPathDescTest.class, new Class[] {OutputXPathDesc.class});
+ }
+*/
+
+ /**
+ * Constructor for OutputXPathDescTest.
+ * @param arg0
+ */
+ public TestOutputXPathDesc(String arg0) {
+ super(arg0);
+ }
+
+ /*
+ * Class under test for void OutputXPathDesc(Element)
+ */
+ public void testOutputXPathDescElement() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ OutputXPathDesc desc = new OutputXPathDesc(element);
+ assertNull(desc.getCurrentValue());
+ assertNotNull(desc.getDataType());;
+ }
+
+ public void testOutputXPathDescParam() throws Exception {
+ String query = "select RequiredDefaultedParam from CriteriaDescTable where RequiredDefaultedParam in ('foo')";
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ OutputXPathDesc desc = new OutputXPathDesc(element);
+ assertNotNull("OutputXPathDesc is null", desc);
+ }
+
+
+ public void testOutputXPathDescNoXPath() throws Exception {
+ try {
+ String query = "select OutputColumnNoXPath from CriteriaDescTable";
+ Select iquery = ProxyObjectFactory.getDefaultIQuery(vdbPath, query);
+ final int colLocation = 0;
+ DerivedColumn symbol = (DerivedColumn) iquery.getDerivedColumns().get(colLocation);
+ Expression expr = symbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ OutputXPathDesc desc = new OutputXPathDesc(element);
+ fail("should not be able to create OuputXPathDesc with no XPath");
+ } catch (TranslatorException ce) {
+ return;
+ }
+ }
+ /*
+ * Class under test for void OutputXPathDesc(ILiteral)
+ */
+ public void testOutputXPathDescILiteral() throws Exception {
+ String strLiteral = "MetaMatrix";
+ String strQuery = "Select Company_id from Company where Company_id = '" + strLiteral + "'";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ Condition crits = query.getWhere();
+ List criteriaList = LanguageUtil.separateCriteriaByAnd(crits);
+ Comparison compCriteria = (Comparison) criteriaList.get(0);
+ Literal literal = (Literal) compCriteria.getRightExpression();
+ OutputXPathDesc desc = new OutputXPathDesc(literal);
+ assertNotNull(desc);
+ assertEquals(strLiteral, desc.getCurrentValue().toString());
+ assertEquals(strLiteral.getClass(), desc.getDataType());
+ }
+
+ public void testOutputXPathDescILiteralNullValue() throws Exception {
+ String strLiteral = "MetaMatrix";
+ String strQuery = "Select Company_id from Company where Company_id = '" + strLiteral + "'";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ Condition crits = query.getWhere();
+ List criteriaList = LanguageUtil.separateCriteriaByAnd(crits);
+ Comparison compCriteria = (Comparison) criteriaList.get(0);
+ Literal literal = (Literal) compCriteria.getRightExpression();
+ literal.setValue(null);
+ OutputXPathDesc desc = new OutputXPathDesc(literal);
+ assertNotNull(desc);
+ assertNull(desc.getCurrentValue());
+ assertEquals(strLiteral.getClass(), desc.getDataType());
+ }
+
+ public void testSetAndGetCurrentValue() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ OutputXPathDesc desc = new OutputXPathDesc(element);
+ String myVal = "myValue";
+ desc.setCurrentValue(myVal);
+ assertEquals(myVal, desc.getCurrentValue());
+ }
+
+ public void testGetDataType() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ OutputXPathDesc desc = new OutputXPathDesc(element);
+ assertNotNull(desc.getDataType());
+ assertEquals(String.class, desc.getDataType());
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestParameterDescriptor.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestParameterDescriptor.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestParameterDescriptor.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,200 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.ColumnReference;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.Select;
+import org.teiid.metadata.Column;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.ParameterDescriptor;
+
+
+/**
+ *
+ */
+public class TestParameterDescriptor extends TestCase {
+
+ private static String vdbPath;
+ private static final String QUERY = "select OutputColumn from CriteriaDescTable where"
+ + " OutputColumn in ('MetaMatrix') order by OutputColumn";
+
+
+ static {
+ vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ }
+
+
+// removing hansel while testing clover
+/*
+ public static Test suite() {
+ return new CoverageDecorator(ParameterDescriptorTest.class, new Class[] {ParameterDescriptor.class});
+ }
+
+*/
+ /**
+ * Constructor for ParameterDescriptorTest.
+ * @param arg0
+ */
+ public TestParameterDescriptor(String arg0) {
+ super(arg0);
+ }
+
+ /*
+ * Class under test for void ParameterDescriptor(Element)
+ */
+ public void testParameterDescriptorElement() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ ParameterDescriptor desc = new ParameterDescriptorImpl(element);
+ assertNotNull(desc);
+ }
+
+
+ public void testParameterDescriptorElementParameter() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, "select RequiredDefaultedParam from CriteriaDescTable");
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ ParameterDescriptor desc = new ParameterDescriptorImpl(element);
+ assertNotNull(desc);
+ }
+
+
+
+ public void testParameterDescriptorElementSpaceXPath() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, "select OutputColumnSpaceXPath from CriteriaDescTable");
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ ParameterDescriptor desc = new ParameterDescriptorImpl(element);
+ assertNotNull(desc);
+ }
+
+ /*
+ * Class under test for void ParameterDescriptor(ILiteral)
+ */
+ public void testParameterDescriptor() {
+ ParameterDescriptor desc = new ParameterDescriptorImpl();
+ assertNotNull(desc);
+ assertNull(desc.getXPath());
+ assertFalse(desc.isParameter());
+ assertNull(desc.getColumnName());
+ }
+
+ public void testSetGetXPath() throws Exception {
+ ParameterDescriptor desc = getParameterDescriptor();
+ String xpath = "/foo";
+ desc.setXPath(xpath);
+ assertEquals(xpath, desc.getXPath());
+ }
+
+ public void testSetIsParameter() throws Exception {
+ ParameterDescriptor desc = getParameterDescriptor();
+ boolean is = !desc.isParameter();
+ desc.setIsParameter(is);
+ assertEquals(is, desc.isParameter());
+ }
+
+ public void testSetGetColumnName() throws Exception {
+ ParameterDescriptor desc = getParameterDescriptor();
+ String name = "myColumn";
+ desc.setColumnName(name);
+ assertEquals(name, desc.getColumnName());
+ }
+
+ public void testSetGetColumnNumber() throws Exception {
+ ParameterDescriptor desc = getParameterDescriptor();
+ int number = desc.getColumnNumber() + 1;
+ desc.setColumnNumber(number);
+ assertEquals(number, desc.getColumnNumber());
+ }
+
+ public void testGetElement() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ ParameterDescriptor desc = new ParameterDescriptorImpl(element);
+ assertEquals(element, desc.getElement());
+ }
+
+ public void testTestForParam() throws Exception {
+ String trueQuery = "select EmptyCol from EmptyTable where EmptyCol = 'foo'";
+ String falseQuery = "select Company_id from Company";
+
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, trueQuery);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ assertTrue(ParameterDescriptor.testForParam(element));
+
+ query = ProxyObjectFactory.getDefaultIQuery(vdbPath, falseQuery);
+ symbols = query.getDerivedColumns();
+ selectSymbol = (DerivedColumn) symbols.get(0);
+ expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ element = ((ColumnReference) expr).getMetadataObject();
+ assertFalse(ParameterDescriptor.testForParam(element));
+ }
+
+ private ParameterDescriptor getParameterDescriptor() throws Exception {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ List symbols = query.getDerivedColumns();
+ DerivedColumn selectSymbol = (DerivedColumn) symbols.get(0);
+ Expression expr = selectSymbol.getExpression();
+ assertTrue(expr instanceof ColumnReference);
+ Column element = ((ColumnReference) expr).getMetadataObject();
+ ParameterDescriptor desc = new ParameterDescriptorImpl(element);
+ assertNotNull(desc);
+ return desc;
+ }
+
+ private class ParameterDescriptorImpl extends ParameterDescriptor {
+ public ParameterDescriptorImpl() {
+ super();
+ }
+
+ public ParameterDescriptorImpl(Column element) throws TranslatorException {
+ super(element);
+ }
+
+ }
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestQueryAnalyzer.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestQueryAnalyzer.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestQueryAnalyzer.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,165 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml;
+
+
+
+import junit.framework.TestCase;
+
+import org.teiid.language.Select;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.ExecutionInfo;
+import org.teiid.translator.xml.QueryAnalyzer;
+
+/**
+ *
+ */
+public class TestQueryAnalyzer extends TestCase {
+
+ private static String vdbPath;
+ private static final String QUERY = "select SimpleOutput from SimpleTable where SimpleOutput = 'MetaMatrix' order by SimpleOutput";
+
+ static {
+ vdbPath = ProxyObjectFactory.getStateCollegeVDBLocation();
+ }
+
+// removing hansel while testing clover
+/*
+ public static Test suite() {
+ return new CoverageDecorator(QueryAnalyzerTest.class, new Class[] {QueryAnalyzer.class});
+ }
+
+*/
+ /**
+ * Constructor for QueryAnalyzerTest.
+ * @param arg0
+ */
+ public TestQueryAnalyzer(String arg0) {
+ super(arg0);
+ }
+
+ public void testQueryAnalyzer() {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ assertNotNull("analyzer is null", analyzer);
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyze() {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeSimpleSelect() {
+ String strQuery = "select SimpleOutput from SimpleTable";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeLiteralSelect() {
+ String strQuery = "select SimpleOutput, 'foo' from SimpleTable";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeFunctionSelect() {
+ String strQuery = "select concat(SimpleOutput, 'foo') from SimpleTable";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeParameterSelect() {
+ String strQuery = "select SimpleParam from SimpleInput where SimpleParam in ('foo')";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeComplexQuery() {
+ String strQuery = "select SimpleOut from SimpleInput where SimpleParam in ('foo')";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testAnalyzeComplexQuery2() {
+ String strQuery = "select SimpleOut from SimpleInput where SimpleParam in ('foo') and OtherOut in ('bar')";
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, strQuery);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ analyzer.analyze();
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testGetExecutionInfo() {
+ Select query = ProxyObjectFactory.getDefaultIQuery(vdbPath, QUERY);
+ try {
+ QueryAnalyzer analyzer = new QueryAnalyzer(query);
+ assertNotNull("analyzer is null", analyzer);
+ ExecutionInfo base = analyzer.getExecutionInfo();
+ assertEquals(1, base.getColumnCount());
+ analyzer.analyze();
+ ExecutionInfo post = analyzer.getExecutionInfo();
+ assertTrue(post.getColumnCount() > 0);
+ assertEquals(1, post.getCriteria().size());
+ assertEquals(1, post.getRequestedColumns().size());
+ assertNotNull(post.getTableXPath());
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+
+ }
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLCapabilities.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLCapabilities.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLCapabilities.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,195 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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.xml;
+
+import org.teiid.translator.xml.XMLExecutionFactory;
+
+import junit.framework.TestCase;
+
+
+/**
+ *
+ */
+public class TestXMLCapabilities extends TestCase {
+
+
+ private XMLExecutionFactory m_caps = null;
+ /**
+ * Constructor for XMLCapabilitiesTest.
+ * @param arg0
+ */
+ public TestXMLCapabilities(String arg0) {
+ super(arg0);
+ }
+
+ @Override
+ public void setUp() {
+ m_caps = new XMLExecutionFactory();
+
+ }
+
+ public void testGetMaxInCriteriaSize() {
+ assertEquals(Integer.MAX_VALUE, m_caps.getMaxInCriteriaSize());
+ }
+
+ public void testSupportsCompareCriteriaEquals() {
+ assertTrue(m_caps.supportsCompareCriteriaEquals());
+ }
+
+ public void testSupportsInCriteria() {
+ assertTrue(m_caps.supportsInCriteria());
+ }
+
+ public void testXMLCapabilities() {
+ XMLExecutionFactory caps = new XMLExecutionFactory();
+ assertNotNull(caps);
+ }
+
+ /*
+ * Class under test for List getSupportedFunctions()
+ */
+ public void testGetSupportedFunctions() {
+ assertNotNull(m_caps.getSupportedFunctions());
+ }
+
+ public void testSupportsSelectDistinct() {
+ assertFalse(m_caps.supportsSelectDistinct());
+ }
+
+ public void testSupportsAliasedGroup() {
+ assertFalse(m_caps.supportsAliasedTable());
+ }
+
+ public void testSupportsJoins() {
+ assertFalse(m_caps.supportsInnerJoins());
+ }
+
+ public void testSupportsSelfJoins() {
+ assertFalse(m_caps.supportsSelfJoins());
+ }
+
+ public void testSupportsOuterJoins() {
+ assertFalse(m_caps.supportsOuterJoins());
+ }
+
+ public void testSupportsFullOuterJoins() {
+ assertFalse(m_caps.supportsFullOuterJoins());
+ }
+
+ public void testSupportsBetweenCriteria() {
+ assertFalse(m_caps.supportsBetweenCriteria());
+ }
+
+ public void testSupportsLikeCriteria() {
+ assertFalse(m_caps.supportsLikeCriteria());
+ }
+
+ public void testSupportsLikeCriteriaEscapeCharacter() {
+ assertFalse(m_caps.supportsLikeCriteriaEscapeCharacter());
+ }
+
+ public void testSupportsInCriteriaSubquery() {
+ assertFalse(m_caps.supportsInCriteriaSubquery());
+ }
+
+ public void testSupportsIsNullCriteria() {
+ assertFalse(m_caps.supportsIsNullCriteria());
+ }
+
+ public void testSupportsOrCriteria() {
+ assertFalse(m_caps.supportsOrCriteria());
+ }
+
+ public void testSupportsNotCriteria() {
+ assertFalse(m_caps.supportsNotCriteria());
+ }
+
+ public void testSupportsExistsCriteria() {
+ assertFalse(m_caps.supportsExistsCriteria());
+ }
+
+ public void testSupportsQuantifiedCompareCriteriaSome() {
+ assertFalse(m_caps.supportsQuantifiedCompareCriteriaSome());
+ }
+
+ public void testSupportsQuantifiedCompareCriteriaAll() {
+ assertFalse(m_caps.supportsQuantifiedCompareCriteriaAll());
+ }
+
+ public void testSupportsOrderBy() {
+ assertFalse(m_caps.supportsOrderBy());
+ }
+
+ public void testSupportsAggregatesSum() {
+ assertFalse(m_caps.supportsAggregatesSum());
+ }
+
+ public void testSupportsAggregatesAvg() {
+ assertFalse(m_caps.supportsAggregatesAvg());
+ }
+
+ public void testSupportsAggregatesMin() {
+ assertFalse(m_caps.supportsAggregatesMin());
+ }
+
+ public void testSupportsAggregatesMax() {
+ assertFalse(m_caps.supportsAggregatesMax());
+ }
+
+ public void testSupportsAggregatesCount() {
+ assertFalse(m_caps.supportsAggregatesCount());
+ }
+
+ public void testSupportsAggregatesCountStar() {
+ assertFalse(m_caps.supportsAggregatesCountStar());
+ }
+
+ public void testSupportsAggregatesDistinct() {
+ assertFalse(m_caps.supportsAggregatesDistinct());
+ }
+
+ public void testSupportsScalarSubqueries() {
+ assertFalse(m_caps.supportsScalarSubqueries());
+ }
+
+ public void testSupportsCorrelatedSubqueries() {
+ assertFalse(m_caps.supportsCorrelatedSubqueries());
+ }
+
+ public void testSupportsCaseExpressions() {
+ assertFalse(m_caps.supportsCaseExpressions());
+ }
+
+ public void testSupportsSearchedCaseExpressions() {
+ assertFalse(m_caps.supportsSearchedCaseExpressions());
+ }
+
+ public void testSupportsInlineViews() {
+ assertFalse(m_caps.supportsInlineViews());
+ }
+
+ public void testSupportsUnions() {
+ assertFalse(m_caps.supportsUnions());
+ }
+
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLReaderFactory.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLReaderFactory.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXMLReaderFactory.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,19 @@
+package org.teiid.translator.xml;
+
+import junit.framework.TestCase;
+
+import org.teiid.translator.xml.streaming.ReaderFactory;
+import org.xml.sax.XMLReader;
+
+
+public class TestXMLReaderFactory extends TestCase {
+
+ public void testGetSAXBuilder() {
+ try {
+ XMLReader reader = ReaderFactory.getXMLReader(null);
+ assertNotNull(reader);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ }
+}
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXPathSplitter.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXPathSplitter.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestXPathSplitter.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,88 @@
+package org.teiid.translator.xml;
+
+import java.util.List;
+
+import org.teiid.translator.xml.streaming.InvalidPathException;
+import org.teiid.translator.xml.streaming.XPathSplitter;
+
+import junit.framework.TestCase;
+
+
+public class TestXPathSplitter extends TestCase {
+
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ /**
+ * ((((/po:purchaseOrder) | (/po:purchaseOrders/order))/items) | (/po:purchaseOrder/items3) | (/po:purchaseOrders/order/items4))/item
+ *
+ * becomes
+ * /po:purchaseOrder/items/item
+ * /po:purchaseOrders/order/items/item
+ * /po:purchaseOrder/items/item
+ * /po:purchaseOrders/order/items/item
+ * becomes
+ *
+ * /po:purchaseOrder/items/item
+ * /po:purchaseOrders/order/items/item
+ */
+ public void testSplit() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ List paths = splitter.split("((((/po:purchaseOrder) | (/po:purchaseOrders/order))/items) | (/po:purchaseOrder/items) | (/po:purchaseOrders/order/items))/item");
+ assertEquals(2, paths.size());
+ } catch (InvalidPathException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testSplitSimple() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ List paths = splitter.split("/po:purchaseOrders/order/items/item");
+ assertEquals(1, paths.size());
+ } catch (InvalidPathException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testSplitCompund() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ List paths = splitter.split("(/po:purchaseOrders/order/items/item)|(/po:purchaseOrders/order/items)");
+ assertEquals(2, paths.size());
+ } catch (InvalidPathException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ public void testSplitCompund2() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ List paths = splitter.split("(/po:purchaseOrders/order/items/item)|((/po:purchaseOrders/order/items)|(/po:purchaseOrders/order/item))");
+ assertEquals(3, paths.size());
+ } catch (InvalidPathException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ /**
+ * ((/po:purchaseOrders/order/items)|(/po:purchaseOrders/order/item))|((/po:purchaseOrders/order/items)|(/po:purchaseOrders/order/item))
+ *
+ * /po:purchaseOrders/order/items
+ * /po:purchaseOrders/order/item
+ *
+ */
+ public void testSplitCompund3() {
+ XPathSplitter splitter = new XPathSplitter();
+ try {
+ List paths = splitter.split("((/po:purchaseOrders/order/items)|(/po:purchaseOrders/order/item))|((/po:purchaseOrders/order/items)|(/po:purchaseOrders/order/item))");
+ assertEquals(2, paths.size());
+ } catch (InvalidPathException e) {
+ fail(e.getMessage());
+ }
+ }
+}
Copied: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestCachingFileConnectorLong.java (from rev 2125, trunk/connectors/connector-xml-file/src/test/java/org/teiid/connector/xml/file/TestCachingFileConnectorLong.java)
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestCachingFileConnectorLong.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestCachingFileConnectorLong.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,90 @@
+package org.teiid.translator.xml.file;
+
+
+import java.io.File;
+import java.util.List;
+
+import javax.resource.ResourceException;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.FileConnection;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.XMLExecutionFactory;
+
+import com.metamatrix.cdk.api.ConnectorHost;
+
+@SuppressWarnings("nls")
+public class TestCachingFileConnectorLong extends TestCase {
+
+ ConnectorHost host;
+
+ @Override
+ public void setUp() throws Exception {
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+ BasicConnectionFactory cf = new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new FileImpl(UnitTestUtil.getTestDataPath()+"/documents/purchaseOrders.xml");
+ }
+
+ };
+
+ String vdbPath = UnitTestUtil.getTestDataPath()+"/documents/purchase_orders.vdb";
+ host = new ConnectorHost(factory, cf, vdbPath);
+ ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ host.setExecutionContext(context);
+ }
+
+ /**
+ * This primes the cache with the response docs, then gets them from the cache
+ */
+ public void testSelectFromCache() {
+ try {
+ List result = host.executeCommand("SELECT * FROM file_po_list.ITEM");
+ assertEquals(5968, result.size());
+
+ result = host.executeCommand("SELECT * FROM file_po_list.ITEM");
+ assertEquals(5968, result.size());
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ static class FileImpl extends BasicConnection implements FileConnection{
+ File file;
+ public FileImpl(String file) {
+ this.file = new File(file);
+ }
+
+ @Override
+ public File[] getFiles(String path) {
+
+ File f = null;
+ if (path != null) {
+ f = new File(file, path);
+ }
+ else {
+ f = file;
+ }
+
+ if (!f.exists()) {
+ return null;
+ }
+ if (f.isDirectory()) {
+ return file.listFiles();
+ }
+ return new File[] {f};
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ }
+ }
+
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestCachingFileConnectorLong.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileConnector.java (from rev 2125, trunk/connectors/connector-xml-file/src/test/java/org/teiid/connector/xml/file/TestFileConnector.java)
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileConnector.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileConnector.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,47 @@
+package org.teiid.translator.xml.file;
+
+
+import java.util.List;
+
+import javax.resource.ResourceException;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.xml.XMLExecutionFactory;
+import org.teiid.translator.xml.file.TestCachingFileConnectorLong.FileImpl;
+
+import com.metamatrix.cdk.api.ConnectorHost;
+
+@SuppressWarnings("nls")
+public class TestFileConnector extends TestCase {
+
+ public void testSelect() throws Exception{
+
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+ BasicConnectionFactory cf = new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new FileImpl(UnitTestUtil.getTestDataPath()+"/documents/purchaseOrdersShort.xml");
+ }
+
+ };
+
+ String vdbPath = UnitTestUtil.getTestDataPath()+"/documents/purchase_orders.vdb";
+ ConnectorHost host = new ConnectorHost(factory, cf, vdbPath);
+ ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ host.setExecutionContext(context);
+
+ try {
+ List result = host.executeCommand("SELECT * FROM file_po_list.ITEM");
+ assertEquals(2, result.size());
+ } catch (TranslatorException e) {
+ fail(e.getMessage());
+ }
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileConnector.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileExecution.java (from rev 2125, trunk/connectors/connector-xml-file/src/test/java/org/teiid/connector/xml/file/TestFileExecution.java)
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileExecution.java 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,122 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.translator.xml.file;
+
+import java.io.File;
+import java.sql.SQLXML;
+import java.util.List;
+
+import javax.resource.ResourceException;
+
+import junit.framework.TestCase;
+
+import org.mockito.Mockito;
+import org.teiid.core.util.ObjectConverterUtil;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.language.Call;
+import org.teiid.language.LanguageFactory;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.RuntimeMetadata;
+import org.teiid.resource.spi.BasicConnection;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ProcedureExecution;
+import org.teiid.translator.xml.XMLExecutionFactory;
+import org.teiid.translator.xml.file.TestCachingFileConnectorLong.FileImpl;
+
+
+/**
+ */
+@SuppressWarnings("nls")
+public class TestFileExecution extends TestCase {
+
+ public void testGoodFile() throws Exception {
+
+
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+ BasicConnectionFactory cf = new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new FileImpl(UnitTestUtil.getTestDataPath());
+ }
+
+ };
+
+ RuntimeMetadata metadata = Mockito.mock(RuntimeMetadata.class);
+
+ LanguageFactory fact = factory.getLanguageFactory();
+ Call procedure = fact.createCall("GetXMLFile", null, createMockProcedureMetadata("BookCollection.xml")); //$NON-NLS-1$
+
+ ProcedureExecution exec = factory.createProcedureExecution(procedure, Mockito.mock(ExecutionContext.class), metadata, cf); //$NON-NLS-1$ //$NON-NLS-2$
+
+ exec.execute();
+
+ List<?> result = exec.next();
+ assertNotNull(result);
+ assertNull(exec.next());
+ try {
+ exec.getOutputParameterValues();
+ fail("should have thrown error in returning a return"); //$NON-NLS-1$
+ }catch(Exception e) {
+ }
+ SQLXML xmlSource = (SQLXML)result.get(0);
+ assertNotNull(xmlSource);
+ String xml = xmlSource.getString();
+
+ String fileContents = ObjectConverterUtil.convertFileToString(new File(UnitTestUtil.getTestDataPath()+"/BookCollection.xml")); //$NON-NLS-1$
+ fileContents = fileContents.replaceAll("\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
+ //System.out.println(fileContents);
+
+ assertEquals(fileContents, xml);
+ }
+
+ public void testBadFile() throws Exception {
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+ BasicConnectionFactory cf = new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ return new FileImpl(UnitTestUtil.getTestDataPath());
+ }
+
+ };
+
+ RuntimeMetadata metadata = Mockito.mock(RuntimeMetadata.class);
+
+ LanguageFactory fact = factory.getLanguageFactory();
+ Call procedure = fact.createCall("GetXMLFile", null, createMockProcedureMetadata("nofile.xml")); //$NON-NLS-1$
+
+ ProcedureExecution exec = factory.createProcedureExecution(procedure, Mockito.mock(ExecutionContext.class), metadata, cf); //$NON-NLS-1$ //$NON-NLS-2$
+
+ try {
+ exec.execute();
+ fail("should have thrown error in returning a return"); //$NON-NLS-1$
+ }catch(Exception e) {
+ }
+ }
+
+ public static Procedure createMockProcedureMetadata(String nameInSource) {
+ Procedure rm = Mockito.mock(Procedure.class);
+ Mockito.stub(rm.getNameInSource()).toReturn(nameInSource);
+ return rm;
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/file/TestFileExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-xml/src/test/resources/BookCollection.xml (from rev 2125, trunk/connectors/connector-xml-file/src/test/resources/BookCollection.xml)
===================================================================
--- trunk/connectors/translator-xml/src/test/resources/BookCollection.xml (rev 0)
+++ trunk/connectors/translator-xml/src/test/resources/BookCollection.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,543 @@
+<?xml version="1.0" encoding="UTF-8"?><Books:bookCollection xmlns:Books="http://www.metamatrix.com/XMLSchema/DataSets/Books">
+<!--
+
+ JBoss, Home of Professional Open Source.
+ See the COPYRIGHT.txt file distributed with this work for information
+ regarding copyright ownership. Some portions may be licensed
+ to Red Hat, Inc. under one or more contributor license agreements.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+-->
+
+ <book isbn="0-7356-0877-7">
+ <title>After the Gold Rush</title>
+ <subtitle>Creating a True Profession of Software Engineering</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>McConnell</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Microsoft Press</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-55615-484-4">
+ <title>Code Complete</title>
+ <subtitle>A Practical Handbook of Software Construction</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>McConnell</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Microsoft Press</publisher>
+ <publishDate>1993</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-556-15900-5">
+ <title>Rapid Development</title>
+ <subtitle>Taming Wild Software Schedules</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>McConnell</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Microsoft Press</publisher>
+ <publishDate>1996</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-7356-0631-5">
+ <title>Software Requirements</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Wiegers</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Microsoft Press</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-57231-621-7">
+ <title>Software Project Survival Guide</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>McConnell</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Microsoft Press</publisher>
+ <publishDate>1998</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-43287-0">
+ <title>Automated Software Testing</title>
+ <subtitle>Introduction, Management, and Performance</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Dustin</author>
+ <author>Rashka</author>
+ <author>Paul</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-31000-7">
+ <title>Inside Java 2 Security</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Gong</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="020130998X">
+ <title>The Unified Modeling Language Reference Manual</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Rumbaugh</author>
+ <author>Jacobson</author>
+ <author>Booch</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1998</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-70225-8">
+ <title>Writing Effective Use Cases</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Cockburn</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>2001</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0201877562">
+ <title>Software Testing in the Real World</title>
+ <subtitle>Improving the Process</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Kit</author>
+ <author>Finzi</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1995</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-43336-2">
+ <title>SQL Queries for Mere Mortals</title>
+ <subtitle>A Hands-on Guide to Data Manipulation in SQL</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Hernandez</author>
+ <author>Viescas</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-65758-9">
+ <title>LDAP Programming with Java</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Weltman</author>
+ <author>Dahbura</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-44787-8">
+ <title>The Practical SQL Handbook</title>
+ <subtitle>Using Structured Query Language</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Bowman</author>
+ <author>Emerson</author>
+ <author>Darnovsky</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1996</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-10088-6">
+ <title>Compilers</title>
+ <subtitle>Principles, Techniques, and Tools</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Aho</author>
+ <author>Sethi</author>
+ <author>Ullman</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>1985</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-201-31009-0">
+ <title>Concurrent Programming in Java</title>
+ <subtitle>Design Principles and Patterns</subtitle>
+ <edition>2</edition>
+ <authors>
+ <author>Lea</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Addison-Wesley</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-471-98710-7">
+ <title>Concurrency State Models & Java Programs</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Kramer</author>
+ <author>Magee</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Wiley</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-471355232">
+ <title>Building and Managing the Meta Data Repository</title>
+ <subtitle>A Full Life-Cycle Guide</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Marco</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Wiley</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-7897-2271-2">
+ <title>Complete Idiot's Guide to Project Management with Microsoft Project 2000</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Black</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Que</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-932633-33-1">
+ <title>Creating a Software Engineering Culture</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Wiegers</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Dorset House Publishing</publisher>
+ <publishDate>1996</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-932633-43-9">
+ <title>Peopleware</title>
+ <subtitle>Productive Projects and Teams</subtitle>
+ <edition>2</edition>
+ <authors>
+ <author>DeMarco</author>
+ <author>Lister</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Dorset House Publishing</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1558605150">
+ <title>Database Design for Smarties</title>
+ <subtitle>Using UML for Data Modeling</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Muller</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Morgan Kaufman</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-558-60190-2">
+ <title>Transaction Processing</title>
+ <subtitle>Concepts and Techniques</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Gray</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Morgan Kaufman</publisher>
+ <publishDate>1992</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-55860-415-4">
+ <title>Principles of Transaction Processing</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Bernstein</author>
+ <author>Newcomer</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Morgan Kaufman</publisher>
+ <publishDate>1997</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1558605231">
+ <title>Readings in Database Systems</title>
+ <subtitle/>
+ <edition>3</edition>
+ <authors>
+ <author>Stonebraker</author>
+ <author>Hellerstein</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Morgan Kaufman</publisher>
+ <publishDate>1998</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-13-239856-7">
+ <title>How to Run Successful Projects II</title>
+ <subtitle/>
+ <edition>2</edition>
+ <authors>
+ <author>O'Connell</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Prentice Hall</publisher>
+ <publishDate>1996</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-13-014714-1">
+ <title>The XML Handbook</title>
+ <subtitle/>
+ <edition>2</edition>
+ <authors>
+ <author>Goldfarb</author>
+ <author>Prescod</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Prentice Hall</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0130273635">
+ <title>Thinking in Java</title>
+ <subtitle/>
+ <edition>2</edition>
+ <authors>
+ <author>Eckel</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Prentice Hall</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="130402648">
+ <title>Database System Implementation</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Ullman</author>
+ <author>Garcia-Molina</author>
+ <author>Widom</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Prentice Hall</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-596-00016-2">
+ <title>Java and XML</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>McLaughlin</author>
+ <author>Loukides</author>
+ </authors>
+ <publishingInformation>
+ <publisher>O'Reilly</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-56592-487-8">
+ <title>Java in a Nutshell</title>
+ <subtitle/>
+ <edition>3</edition>
+ <authors>
+ <author>Flanagan</author>
+ </authors>
+ <publishingInformation>
+ <publisher>O'Reilly</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-56592-483-5">
+ <title>Java Enterprise in a Nutshell</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Flanagan</author>
+ </authors>
+ <publishingInformation>
+ <publisher>O'Reilly</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-672-31602-1">
+ <title>Java Security Handbook</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Jaworski</author>
+ <author>Perrone</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Sams</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-672-31983-7">
+ <title>Software Testing</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Patton</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Sams</publisher>
+ <publishDate>2001</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-861002-77-7">
+ <title>Professional Java Server Programming</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Ayers</author>
+ <author>Bergsten</author>
+ <author>Diamond</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Wrox</publisher>
+ <publishDate>1999</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-861-00506-7">
+ <title>XSLT Programmer's Reference</title>
+ <subtitle/>
+ <edition>2</edition>
+ <authors>
+ <author>Kay</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Wrox</publisher>
+ <publishDate>2001</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-861-00312-9">
+ <title>XSLT Programmer's Reference</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Kay</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Wrox</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-818-68300-7">
+ <title>The Software Project Manager's Handbook</title>
+ <subtitle>Principles that Work</subtitle>
+ <edition>1</edition>
+ <authors>
+ <author>Phillips</author>
+ </authors>
+ <publishingInformation>
+ <publisher>IEEE Computer Society</publisher>
+ <publishDate>1998</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-884777-84-8">
+ <title>Swing</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Robinson</author>
+ <author>Vorobiev</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Manning</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-893115-10-0">
+ <title>Taming Java Threads</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Holub</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Apress</publisher>
+ <publishDate>2000</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="1-57870-070-1">
+ <title>Understanding and Deploying LDAP Directory Services</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Howes</author>
+ <author>Smith</author>
+ <author>Good</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Macmillan</publisher>
+ <publishDate>1990</publishDate>
+ </publishingInformation>
+ </book>
+ <book isbn="0-7821-1148-3">
+ <title>SQL Instant Reference</title>
+ <subtitle/>
+ <edition>1</edition>
+ <authors>
+ <author>Gruber</author>
+ </authors>
+ <publishingInformation>
+ <publisher>Sybex</publisher>
+ <publishDate>1993</publishDate>
+ </publishingInformation>
+ </book>
+</Books:bookCollection>
\ No newline at end of file
Property changes on: trunk/connectors/translator-xml/src/test/resources/BookCollection.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Copied: trunk/connectors/translator-xml/src/test/resources/documents/purchaseOrdersShort.xml (from rev 2125, trunk/connectors/connector-xml-file/src/test/resources/documents/purchaseOrdersShort.xml)
===================================================================
--- trunk/connectors/translator-xml/src/test/resources/documents/purchaseOrdersShort.xml (rev 0)
+++ trunk/connectors/translator-xml/src/test/resources/documents/purchaseOrdersShort.xml 2010-05-17 22:19:02 UTC (rev 2132)
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<po:purchaseOrders xmlns:po="http://www.example.com/PO1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/PO1 po.xsd ">
+ <order orderDate="2001-01-01">
+ <shipTo country="US">
+ <name>name</name>
+ <street>street</street>
+ <city>city</city>
+ <state>state</state>
+ <zip>0.0</zip>
+ </shipTo>
+ <billTo country="US">
+ <name>name</name>
+ <street>street</street>
+ <city>city</city>
+ <state>state</state>
+ <zip>0.0</zip>
+ </billTo>
+ <po:comment>po:comment</po:comment>
+ <items>
+ <item partNum="872-AA">
+ <productName>productName</productName>
+ <quantity>1</quantity>
+ <USPrice>0.0</USPrice>
+ <po:comment>po:comment</po:comment>
+ <shipDate>2001-01-01</shipDate>
+ </item>
+ </items>
+ </order>
+ <order orderDate="2001-01-01">
+ <shipTo country="US">
+ <name>name</name>
+ <street>street</street>
+ <city>city</city>
+ <state>state</state>
+ <zip>0.0</zip>
+ </shipTo>
+ <billTo country="US">
+ <name>name</name>
+ <street>street</street>
+ <city>city</city>
+ <state>state</state>
+ <zip>0.0</zip>
+ </billTo>
+ <po:comment>po:comment</po:comment>
+ <items>
+ <item partNum="872-AA">
+ <productName>productName</productName>
+ <quantity>1</quantity>
+ <USPrice>0.0</USPrice>
+ <po:comment>po:comment</po:comment>
+ <shipDate>2001-01-01</shipDate>
+ </item>
+ </items>
+ </order>
+</po:purchaseOrders>
Property changes on: trunk/connectors/translator-xml/src/test/resources/documents/purchaseOrdersShort.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
14 years, 7 months
teiid SVN: r2131 - trunk/runtime/src/test/java/org/teiid/deployers.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-17 18:13:10 -0400 (Mon, 17 May 2010)
New Revision: 2131
Modified:
trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java
Log:
TEIID-1056 refining connector changes to remove capabilities interface. also ensuring that property annotation processing is simplified
Modified: trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java
===================================================================
--- trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java 2010-05-17 22:09:08 UTC (rev 2130)
+++ trunk/runtime/src/test/java/org/teiid/deployers/TestTranslatorDeployer.java 2010-05-17 22:13:10 UTC (rev 2131)
@@ -36,7 +36,7 @@
TranslatorMetaData tm = new TranslatorMetaData();
tm.setXaCapable(true);
- tm.addProperty("my-property", "correctly-assigned");
+ tm.addProperty("MyProperty", "correctly-assigned");
TranslatorDeployer td = new TranslatorDeployer();
MyTranslator my = (MyTranslator)td.buildTranslator(MyTranslator.class.getName(), tm);
@@ -48,7 +48,7 @@
public static class MyTranslator extends ExecutionFactory {
String mine;
- @TranslatorProperty(name="my-property")
+ @TranslatorProperty(display="my-property")
public String getMyProperty() {
return mine;
}
14 years, 7 months