teiid SVN: r2145 - in trunk/console: src/main/java/org/teiid/rhq/plugin and 5 other directories.
by teiid-commits@lists.jboss.org
Author: tejones
Date: 2010-05-19 19:20:03 -0400 (Wed, 19 May 2010)
New Revision: 2145
Added:
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyListAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyMapAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertySimpleAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapterFactory.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/AbstractPropertyMapToCompositeValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToCollectionValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToCompositeValueSupportAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToGenericValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToMapCompositeValueSupportAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToPropertiesValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToTableValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToEnumValueAdapter.java
trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToSimpleValueAdapter.java
Removed:
trunk/console/src/main/java/org/teiid/rhq/plugin/QueriesComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/SessionComponent.java
Modified:
trunk/console/pom.xml
trunk/console/src/main/java/org/teiid/rhq/plugin/Facet.java
trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java
trunk/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
trunk/console/src/main/resources/META-INF/rhq-plugin.xml
Log:
TEIID-807: Added Translator creation logic
Modified: trunk/console/pom.xml
===================================================================
--- trunk/console/pom.xml 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/pom.xml 2010-05-19 23:20:03 UTC (rev 2145)
@@ -159,6 +159,28 @@
</dependency> -->
</dependencies>
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
</project>
\ No newline at end of file
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/Facet.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/Facet.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/Facet.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -29,13 +29,22 @@
import java.util.Map;
import java.util.Set;
+import javax.naming.NamingException;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
import org.jboss.deployers.spi.management.deploy.DeploymentManager;
import org.jboss.deployers.spi.management.deploy.DeploymentProgress;
import org.jboss.deployers.spi.management.deploy.DeploymentStatus;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.profileservice.spi.NoSuchDeploymentException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
import org.rhq.core.domain.content.PackageDetailsKey;
import org.rhq.core.domain.content.PackageType;
import org.rhq.core.domain.content.transfer.DeployPackageStep;
@@ -45,13 +54,13 @@
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.content.version.PackageVersions;
import org.rhq.core.domain.resource.CreateResourceStatus;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
import org.rhq.core.pluginapi.content.ContentFacet;
import org.rhq.core.pluginapi.content.ContentServices;
+import org.rhq.core.pluginapi.content.version.PackageVersions;
import org.rhq.core.pluginapi.inventory.CreateChildResourceFacet;
import org.rhq.core.pluginapi.inventory.CreateResourceReport;
import org.rhq.core.pluginapi.inventory.DeleteResourceFacet;
@@ -104,22 +113,23 @@
* C:/opt/jboss-5.0.0.GA/server/default/deploy/foo.vdb).
*/
protected String deploymentName;
-
+
private PackageVersions versions = null;
-
- /**
- * Name of the backing package type that will be used when discovering packages. This corresponds to the name of the
- * package type defined in the plugin descriptor. For simplicity, the package type for VDBs is called "vdb". This is
- * still unique within the context of the parent resource type and lets this class use the same package type name in
- * both cases.
- */
- private static final String PKG_TYPE_VDB = "vdb";
- /**
- * Architecture string used in describing discovered packages.
- */
- private static final String ARCHITECTURE = "noarch";
+ /**
+ * Name of the backing package type that will be used when discovering
+ * packages. This corresponds to the name of the package type defined in the
+ * plugin descriptor. For simplicity, the package type for VDBs is called
+ * "vdb". This is still unique within the context of the parent resource
+ * type and lets this class use the same package type name in both cases.
+ */
+ private static final String PKG_TYPE_VDB = "vdb";
+ /**
+ * Architecture string used in describing discovered packages.
+ */
+ private static final String ARCHITECTURE = "noarch";
+
abstract String getComponentType();
/**
@@ -299,7 +309,6 @@
// this simulates the plugin taking the new configuration and
// reconfiguring the managed resource
resourceConfiguration = report.getConfiguration().deepCopy();
-
report.setStatus(ConfigurationUpdateStatus.SUCCESS);
}
@@ -346,7 +355,7 @@
File deploymentFile = null;
if (this.deploymentName != null) {
- deploymentFile = new File(deploymentName.substring(7));
+ deploymentFile = new File(deploymentName.substring(7));
}
if (!deploymentFile.exists())
@@ -374,7 +383,7 @@
if (!deploymentFile.isDirectory())
packageDetails.setFileSize(deploymentFile.length());
packageDetails.setFileCreatedDate(null); // TODO: get created date via
- // SIGAR
+ // SIGAR
Set<ResourcePackageDetails> packages = new HashSet<ResourcePackageDetails>();
packages.add(packageDetails);
@@ -398,9 +407,107 @@
return null;
}
+
+ protected static Configuration getDefaultPluginConfiguration(
+ ResourceType resourceType) {
+ ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
+ .getPluginConfigurationDefinition().getDefaultTemplate();
+ return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
+ .createConfiguration()
+ : new Configuration();
+ }
+
+
+
+ /* (non-Javadoc)
+ * @see org.rhq.core.pluginapi.inventory.CreateChildResourceFacet#createResource(org.rhq.core.pluginapi.inventory.CreateResourceReport)
+ */
@Override
- public CreateResourceReport createResource(
+ public CreateResourceReport createResource(CreateResourceReport report) {
+ ResourceType resourceType = report.getResourceType();
+ if (resourceType.getName().equals("Translators")){
+ createConfigurationBasedResource(report);
+ }else{
+ createContentBasedResource(report);
+ }
+
+ return report;
+ }
+
+ private CreateResourceReport createConfigurationBasedResource(
CreateResourceReport createResourceReport) {
+ ResourceType resourceType = createResourceReport.getResourceType();
+ Configuration defaultPluginConfig =
+ getDefaultPluginConfiguration(resourceType);
+ Configuration resourceConfig = createResourceReport
+ .getResourceConfiguration();
+ String resourceName = getResourceName(defaultPluginConfig,
+ resourceConfig);
+ ComponentType componentType = ProfileServiceUtil
+ .getComponentType(resourceType);
+ ManagementView managementView = null;;
+ try {
+ managementView = ProfileServiceUtil.getManagementView(
+ ProfileServiceUtil.getProfileService(), true);
+ } catch (NamingException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ if (ProfileServiceUtil.isManagedComponent(managementView,
+ resourceName, componentType)) {
+ createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+ createResourceReport.setErrorMessage("A " + resourceType.getName()
+ + " named '" + resourceName + "' already exists.");
+ return createResourceReport;
+ }
+
+ createResourceReport.setResourceName(resourceName);
+ String resourceKey = getResourceKey(resourceType, resourceName);
+ createResourceReport.setResourceKey(resourceKey);
+
+ PropertySimple templateNameProperty = resourceConfig
+ .getSimple(TranslatorComponent.Config.TEMPLATE_NAME);
+ String templateName = templateNameProperty.getStringValue();
+
+ DeploymentTemplateInfo template;
+ Set templateNamesSet = managementView.getTemplateNames();
+ try {
+ template = managementView.getTemplate(templateName);
+ Map<String, ManagedProperty> managedProperties = template
+ .getProperties();
+
+ ProfileServiceUtil.convertConfigurationToManagedProperties(
+ managedProperties, resourceConfig, resourceType);
+
+ LOG.debug("Applying template [" + templateName
+ + "] to create ManagedComponent of type [" + componentType
+ + "]...");
+ try {
+ managementView.applyTemplate(resourceName, template);
+ managementView.process();
+ createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
+ } catch (Exception e) {
+ LOG.error("Unable to apply template [" + templateName
+ + "] to create ManagedComponent of type "
+ + componentType + ".", e);
+ createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+ createResourceReport.setException(e);
+ }
+ } catch (NoSuchDeploymentException e) {
+ LOG.error("Unable to find template [" + templateName + "].", e);
+ createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+ createResourceReport.setException(e);
+ } catch (Exception e) {
+ LOG.error("Unable to process create request", e);
+ createResourceReport.setStatus(CreateResourceStatus.FAILURE);
+ createResourceReport.setException(e);
+ }
+ return createResourceReport;
+ }
+
+ protected void createContentBasedResource(
+ CreateResourceReport createResourceReport) {
+
ResourcePackageDetails details = createResourceReport
.getPackageDetails();
PackageDetailsKey key = details.getKey();
@@ -417,7 +524,7 @@
createResourceReport
.setErrorMessage("Incorrect extension specified on filename ["
+ archivePath + "]");
- return createResourceReport;
+
}
DeploymentManager deploymentManager = ProfileServiceUtil
@@ -437,9 +544,29 @@
createResourceReport.setException(t);
}
- return createResourceReport;
-
}
+
+ private static String getResourceName(Configuration pluginConfig, Configuration resourceConfig)
+ {
+ PropertySimple resourceNameProp = pluginConfig.getSimple(TranslatorComponent.Config.RESOURCE_NAME);
+ if (resourceNameProp == null || resourceNameProp.getStringValue() == null)
+ throw new IllegalStateException("Property [" + TranslatorComponent.Config.RESOURCE_NAME
+ + "] is not defined in the default plugin configuration.");
+ String resourceNamePropName = resourceNameProp.getStringValue();
+ PropertySimple propToUseAsResourceName = resourceConfig.getSimple(resourceNamePropName);
+ if (propToUseAsResourceName == null)
+ throw new IllegalStateException("Property [" + resourceNamePropName
+ + "] is not defined in initial Resource configuration.");
+ return propToUseAsResourceName.getStringValue();
+ }
+
+ private String getResourceKey(ResourceType resourceType, String resourceName)
+ {
+ ComponentType componentType = ProfileServiceUtil.getComponentType(resourceType);
+ if (componentType == null)
+ throw new IllegalStateException("Unable to map " + resourceType + " to a ComponentType.");
+ return componentType.getType() + ":" + componentType.getSubtype() + ":" + resourceName;
+ }
/**
* Returns an instantiated and loaded versions store access point.
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/PlatformComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -35,6 +35,7 @@
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
import org.teiid.rhq.admin.DQPManagementView;
import org.teiid.rhq.plugin.util.PluginConstants;
import org.teiid.rhq.plugin.util.ProfileServiceUtil;
@@ -174,6 +175,7 @@
}
}
+
@Override
public void stop() {
@@ -181,4 +183,6 @@
super.stop();
}
+
+
}
\ No newline at end of file
Deleted: trunk/console/src/main/java/org/teiid/rhq/plugin/QueriesComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/QueriesComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/QueriesComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -1,130 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.teiid.rhq.comm.ConnectionConstants.ComponentType.Runtime.Queries;
-import org.teiid.rhq.comm.ConnectionConstants.ComponentType.Runtime.Queries.Query;
-import org.teiid.rhq.plugin.objects.ExecutedResourceConfigurationResultImpl;
-
-
-/**
- * MetaMatrix Connector component class
- *
- */
-public class QueriesComponent extends Facet {
-
- private final Log LOG = LogFactory.getLog(QueriesComponent.class);
-
-
- private ExecutedResourceConfigurationResultImpl getQueries = null;
-
- /**
- * @see org.teiid.rhq.plugin.Facet#getComponentType()
- * @since 1.0
- */
- @Override
- String getComponentType() {
- return Queries.TYPE;
- }
-
- public void start(ResourceContext context) {
- super.start(context);
-
- Map defns = context.getResourceType().getResourceConfigurationDefinition().getPropertyDefinitions();
-
- getQueries = new ExecutedResourceConfigurationResultImpl(
- this.getComponentType(),
- Query.GET_QUERIES,
- defns);
- }
-
- protected void setOperationArguments(String name, Configuration configuration,
- Map argumentMap) {
-
-
- }
-
- @Override
- public AvailabilityType getAvailability() {
- return AvailabilityType.UP;
-
- }
-
- @Override
- public void getValues(MeasurementReport arg0,
- Set<MeasurementScheduleRequest> arg1) throws Exception {
- // TODO Auto-generated method stub
-
- }
-
-
- /**
- * The plugin container will call this method and it needs to obtain the
- * current configuration of the managed resource. Your plugin will obtain
- * the managed resource's configuration in your own custom way and populate
- * the returned Configuration object with the managed resource's
- * configuration property values.
- *
- * @see ConfigurationFacet#loadResourceConfiguration()
- *
- */
- @Override
- public Configuration loadResourceConfiguration() {
- // here we simulate the loading of the managed resource's configuration
- Configuration config = this.getResourceConfiguration() ;
- if (config == null) {
- // for this example, we will create a simple dummy configuration to
- // start with.
- // note that it is empty, so we're assuming there are no required
- // configs in the plugin descriptor.
- config = new Configuration();
-
-
- }
-
- getQueries.reset();
-
- execute(getQueries, new HashMap());
-
-
- config.put( (PropertyList) getQueries.getResult());
-
-
- this.setResourceConfiguration(config);
- return this.getResourceConfiguration();
- }
-
-
-}
\ No newline at end of file
Deleted: trunk/console/src/main/java/org/teiid/rhq/plugin/SessionComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/SessionComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/SessionComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -1,154 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-package org.teiid.rhq.plugin;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.rhq.core.domain.configuration.Configuration;
-import org.rhq.core.domain.configuration.PropertyList;
-import org.rhq.core.domain.measurement.AvailabilityType;
-import org.rhq.core.domain.measurement.MeasurementReport;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import org.rhq.core.pluginapi.inventory.ResourceContext;
-import org.teiid.rhq.comm.ConnectionConstants.ComponentType.Runtime.Session;
-import org.teiid.rhq.comm.ConnectionConstants.ComponentType.Runtime.Session.Query;
-import org.teiid.rhq.plugin.objects.ExecutedResourceConfigurationResultImpl;
-
-
-/**
- * MetaMatrix Connector component class
- *
- */
-public class SessionComponent extends Facet {
-
- private final Log LOG = LogFactory.getLog(SessionComponent.class);
-
-
- private ExecutedResourceConfigurationResultImpl getSessions = null;
-
- /**
- * @see org.teiid.rhq.plugin.Facet#getComponentType()
- * @since 1.0
- */
- @Override
- String getComponentType() {
- return Session.TYPE;
- }
-
- public void start(ResourceContext context) {
- super.start(context);
-
- Map defns = context.getResourceType().getResourceConfigurationDefinition().getPropertyDefinitions();
-
- getSessions = new ExecutedResourceConfigurationResultImpl(
- this.getComponentType(),
- Query.GET_SESSIONS,
- defns);
- }
-
- protected void setOperationArguments(String name, Configuration configuration,
- Map argumentMap) {
-
-
- }
-
- @Override
- public AvailabilityType getAvailability() {
- return AvailabilityType.UP;
-
- }
-
- @Override
- public void getValues(MeasurementReport arg0,
- Set<MeasurementScheduleRequest> arg1) throws Exception {
- // TODO Auto-generated method stub
-
- }
-
-
- /**
- * The plugin container will call this method and it needs to obtain the
- * current configuration of the managed resource. Your plugin will obtain
- * the managed resource's configuration in your own custom way and populate
- * the returned Configuration object with the managed resource's
- * configuration property values.
- *
- * @see ConfigurationFacet#loadResourceConfiguration()
- *
- */
- @Override
- public Configuration loadResourceConfiguration() {
- // here we simulate the loading of the managed resource's configuration
- Configuration config = this.getResourceConfiguration() ;
- if (config == null) {
- // for this example, we will create a simple dummy configuration to
- // start with.
- // note that it is empty, so we're assuming there are no required
- // configs in the plugin descriptor.
- config = new Configuration();
-
-
- }
-
- getSessions.reset();
-
- execute(getSessions, new HashMap());
-
-
- config.put( (PropertyList) getSessions.getResult());
-
-
- this.setResourceConfiguration(config);
- return this.getResourceConfiguration();
- }
-
-
-// class SessionComparable implements Comparator {
-//
-// public int compare(Object arg0, Object arg1) {
-// // TODO Auto-generated method stub
-// Component a = (Component) arg0;
-// Component b = (Component) arg1;
-//
-// if ( a == null && b == null ) {
-// return 0;
-// }
-// if ( a != null && b == null ) {
-// return 1;
-// }
-// if ( a == null && b != null ) {
-// return -1;
-// }
-// int result = a.get.compareTo(b.getDisplayName());
-// return result;
-// }
-
-
-
- // }
-
-}
\ No newline at end of file
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -21,42 +21,56 @@
*/
package org.teiid.rhq.plugin;
-import java.util.Iterator;
import java.util.Map;
-import java.util.Properties;
import java.util.Set;
+import javax.naming.NamingException;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.jboss.deployers.spi.management.ManagementView;
+import org.jboss.managed.api.ComponentType;
+import org.jboss.managed.api.DeploymentTemplateInfo;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.profileservice.spi.NoSuchDeploymentException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
import org.rhq.core.domain.measurement.MeasurementDataNumeric;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
-import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
+import org.rhq.core.domain.resource.CreateResourceStatus;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
import org.rhq.core.pluginapi.measurement.MeasurementFacet;
import org.teiid.rhq.comm.ConnectionConstants;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
-
/**
* Component class for the MetaMatrix Host Controller process.
*
*/
public class TranslatorComponent extends Facet {
- private final Log LOG = LogFactory
- .getLog(TranslatorComponent.class);
+ private final Log LOG = LogFactory.getLog(TranslatorComponent.class);
+ public static interface Config {
+ String COMPONENT_TYPE = "componentType";
+ String COMPONENT_SUBTYPE = "componentSubtype";
+ String COMPONENT_NAME = "componentName";
+ String TEMPLATE_NAME = "template-name";
+ String RESOURCE_NAME = "resourceName";
+ }
- /**
- * @see org.teiid.rhq.plugin.Facet#getComponentType()
- * @since 1.0
- */
- @Override
- String getComponentType() {
- return ConnectionConstants.ComponentType.Resource.Model.TYPE;
- }
-
- /**
+ /**
+ * @see org.teiid.rhq.plugin.Facet#getComponentType()
+ * @since 1.0
+ */
+ @Override
+ String getComponentType() {
+ return ConnectionConstants.ComponentType.Resource.Model.TYPE;
+ }
+
+ /**
* The plugin container will call this method when your resource component
* has been scheduled to collect some measurements now. It is within this
* method that you actually talk to the managed resource and collect the
@@ -75,8 +89,8 @@
// actually need to collect
try {
Number value = new Integer(1); // dummy measurement value -
- // this should come from the
- // managed resource
+ // this should come from the
+ // managed resource
report.addData(new MeasurementDataNumeric(request, value
.doubleValue()));
} catch (Exception e) {
@@ -88,14 +102,17 @@
return;
}
- protected void setOperationArguments(String name, Configuration configuration,
- Map argumentMap) {
+ protected void setOperationArguments(String name,
+ Configuration configuration, Map argumentMap) {
- if (name.equals(ConnectionConstants.ComponentType.Operation.GET_PROPERTIES)){
+ if (name
+ .equals(ConnectionConstants.ComponentType.Operation.GET_PROPERTIES)) {
String key = ConnectionConstants.IDENTIFIER;
argumentMap.put(key, getComponentIdentifier());
}
-
- }
+
+ }
+
+
}
\ No newline at end of file
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/TranslatorDiscoveryComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -31,7 +31,6 @@
import org.jboss.managed.api.ManagedComponent;
import org.jboss.managed.api.ManagedProperty;
import org.jboss.metatype.api.types.MetaType;
-import org.jboss.metatype.api.values.CollectionValueSupport;
import org.jboss.metatype.api.values.MetaValue;
import org.jboss.metatype.api.values.MetaValueFactory;
import org.rhq.core.domain.configuration.Configuration;
@@ -42,7 +41,6 @@
import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
-import org.teiid.adminapi.impl.PropertyMetadata;
import org.teiid.rhq.plugin.util.PluginConstants;
import org.teiid.rhq.plugin.util.ProfileServiceUtil;
@@ -66,8 +64,6 @@
for (ManagedComponent translator : translators) {
- Map<String, ManagedProperty> managedPropertyMap = translator
- .getProperties();
String translatorKey = translator.getName();
String translatorName = ProfileServiceUtil.getSimpleValue(
translator, "name", String.class);
@@ -82,8 +78,7 @@
translatorName, // Resource Name
null, // Version
PluginConstants.ComponentType.Translator.DESCRIPTION, // Description
- discoveryContext.getDefaultPluginConfiguration(), // Plugin
- // Config
+ discoveryContext.getDefaultPluginConfiguration(), // Plugin config
null // Process info from a process scan
);
@@ -92,25 +87,34 @@
PropertyMap propMap = null;
c.put(list);
- for (ManagedProperty prop : managedPropertyMap.values()) {
- propMap = new PropertyMap("translatorMap");
- String name = prop.getName();
- if (name.equals("translator-property")) {
- getTranslatorValues(prop.getValue(), propMap, list);
- } else {
- propMap.put(new PropertySimple("name", name));
- propMap.put(new PropertySimple("value", ProfileServiceUtil
- .stringValue(prop.getValue())));
- propMap.put(new PropertySimple("description", prop
- .getDescription()));
- list.add(propMap);
- }
- }
+ // First get translator specific properties
+ ManagedProperty translatorProps = translator
+ .getProperty("translator-property");
+ getTranslatorValues(translatorProps.getValue(), propMap, list);
+ // Now get common properties
+ c.put(new PropertySimple("name", translatorName));
+ c.put(new PropertySimple("execution-factory-class",
+ ProfileServiceUtil.getSimpleValue(translator,
+ "execution-factory-class", String.class)));
+ c.put(new PropertySimple("immutable", ProfileServiceUtil
+ .getSimpleValue(translator, "immutable", Boolean.class)));
+ c.put(new PropertySimple("xa-capable", ProfileServiceUtil
+ .getSimpleValue(translator, "xa-capable", Boolean.class)));
+ c.put(new PropertySimple("exception-on-max-rows",
+ ProfileServiceUtil.getSimpleValue(translator,
+ "exception-on-max-rows", Boolean.class)));
+ c.put(new PropertySimple("max-result-rows", ProfileServiceUtil
+ .getSimpleValue(translator, "max-result-rows",
+ Integer.class)));
+ c.put(new PropertySimple("template-name", ProfileServiceUtil
+ .getSimpleValue(translator, "template-name",
+ String.class)));
+
detail.setPluginConfiguration(c);
// Add to return values
discoveredResources.add(detail);
- log.info("Discovered Teiid Translator: " + translatorName);
+ log.debug("Discovered Teiid Translator: " + translatorName);
}
return discoveredResources;
@@ -119,29 +123,22 @@
public static <T> void getTranslatorValues(MetaValue pValue,
PropertyMap map, PropertyList list) {
MetaType metaType = pValue.getMetaType();
- PropertyMetadata unwrappedvalue = null;
- if (metaType.isCollection()) {
- for (MetaValue value : ((CollectionValueSupport) pValue)
- .getElements()) {
- if (value.getMetaType().isComposite()) {
- map = new PropertyMap("translatorMap");
- unwrappedvalue = (PropertyMetadata) MetaValueFactory
- .getInstance().unwrap(value);
- map
- .put(new PropertySimple("name", unwrappedvalue
- .getName()));
- map.put(new PropertySimple("value", unwrappedvalue
- .getValue()));
- map
- .put(new PropertySimple("description",
- "Custom property"));
- list.add(map);
- } else {
- throw new IllegalStateException(pValue
- + " is not a Composite type");
- }
+ Map<String, T> unwrappedvalue = null;
+ if (metaType.isComposite()) {
+ unwrappedvalue = (Map<String, T>) MetaValueFactory
+ .getInstance().unwrap(pValue);
+
+ for (String key : unwrappedvalue.keySet()) {
+ map = new PropertyMap("translator-properties");
+ map.put(new PropertySimple("name", key));
+ map.put(new PropertySimple("value", unwrappedvalue.get(key)));
+ map.put(new PropertySimple("description", "Custom property"));
+ list.add(map);
}
+ } else {
+ throw new IllegalStateException(pValue + " is not a Composite type");
}
+
}
}
\ No newline at end of file
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/VDBComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -43,6 +43,7 @@
import org.jboss.metatype.api.values.SimpleValue;
import org.jboss.metatype.api.values.SimpleValueSupport;
import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
import org.rhq.core.domain.configuration.PropertyList;
import org.rhq.core.domain.configuration.PropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
@@ -51,6 +52,10 @@
import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.measurement.MeasurementReport;
import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
+import org.rhq.core.pluginapi.configuration.ConfigurationUpdateReport;
+import org.rhq.core.pluginapi.inventory.CreateResourceReport;
import org.rhq.core.pluginapi.inventory.ResourceContext;
import org.teiid.rhq.admin.DQPManagementView;
import org.teiid.rhq.comm.ConnectionConstants;
@@ -218,6 +223,21 @@
return PluginConstants.ComponentType.VDB.NAME;
}
+ /**
+ * The plugin container will call this method when it has a new
+ * configuration for your managed resource. Your plugin will re-configure
+ * the managed resource in your own custom way, setting its configuration
+ * based on the new values of the given configuration.
+ *
+ * @see ConfigurationFacet#updateResourceConfiguration(ConfigurationUpdateReport)
+ */
+ public void updateResourceConfiguration(ConfigurationUpdateReport report) {
+ // this simulates the plugin taking the new configuration and
+ // reconfiguring the managed resource
+ resourceConfiguration = report.getConfiguration().deepCopy();
+ report.setStatus(ConfigurationUpdateStatus.SUCCESS);
+ }
+
@Override
public Configuration loadResourceConfiguration() {
@@ -251,7 +271,15 @@
return configuration;
}
+
+ @Override
+ public CreateResourceReport createResource(
+ CreateResourceReport createResourceReport) {
+ createContentBasedResource(createResourceReport);
+ return createResourceReport;
+ }
+
/**
* @param mcVdb
* @param configuration
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/VDBDiscoveryComponent.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -239,7 +239,7 @@
list.add(map);
MetaType metaType = pValue.getMetaType();
if (metaType.isCollection()) {
- for (MetaValue value : ((CollectionValueSupport) pValue)
+ for (MetaValue value : ((CollectionValueSupport) pValue)
.getElements()) {
GenericValueSupport genValue = ((GenericValueSupport) value);
ManagedObject mo = (ManagedObject) genValue.getValue();
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyListAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyListAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyListAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -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.rhq.plugin.adapter.api;
+
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * A base class for PropertyList <-> ???MetaValue adapters.
+ *
+ */
+public abstract class AbstractPropertyListAdapter implements PropertyAdapter<PropertyList, PropertyDefinitionList>
+{
+ public PropertyList convertToProperty(MetaValue metaValue, PropertyDefinitionList propDefList)
+ {
+ PropertyList propList = new PropertyList(propDefList.getName());
+ populatePropertyFromMetaValue(propList, metaValue, propDefList);
+ return propList;
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyMapAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyMapAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertyMapAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.api;
+
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * A base class for PropertyMap <-> ???MetaValue adapters.
+ *
+ */
+public abstract class AbstractPropertyMapAdapter implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ public PropertyMap convertToProperty(MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ PropertyMap propMap = new PropertyMap(propDefMap.getName());
+ populatePropertyFromMetaValue(propMap, metaValue, propDefMap);
+ return propMap;
+ }
+}
\ No newline at end of file
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertySimpleAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertySimpleAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/AbstractPropertySimpleAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -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.rhq.plugin.adapter.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * A base class for {@link PropertySimple} <-> ???MetaValue adapters.
+ *
+ */
+public abstract class AbstractPropertySimpleAdapter implements PropertyAdapter<PropertySimple, PropertyDefinitionSimple>
+{
+ private final Log log = LogFactory.getLog(this.getClass());
+
+ public PropertySimple convertToProperty(MetaValue metaValue, PropertyDefinitionSimple propDefSimple)
+ {
+ PropertySimple propSimple = new PropertySimple(propDefSimple.getName(), null);
+ populatePropertyFromMetaValue(propSimple, metaValue, propDefSimple);
+ return propSimple;
+ }
+
+ public void populateMetaValueFromProperty(PropertySimple propSimple, MetaValue metaValue,
+ PropertyDefinitionSimple propDefSimple)
+ {
+ if (metaValue == null)
+ throw new IllegalArgumentException("MetaValue to be populated is null.");
+ String value;
+ if (propSimple == null || propSimple.getStringValue() == null)
+ {
+ // Value is null (i.e. prop is unset) - figure out what to use as a default value.
+ String defaultValue = propDefSimple.getDefaultValue();
+ if (defaultValue != null)
+ {
+ log.debug("Simple property '" + propDefSimple.getName()
+ + "' has a null value - setting inner value of corresponding ManagedProperty's MetaValue to plugin-specified default ('"
+ + defaultValue + "')...");
+ value = defaultValue;
+ }
+ else
+ {
+ if (metaValue.getMetaType().isPrimitive())
+ // If it's a primitive, don't mess with the MetaValue - just let it keep whatever inner value it
+ // currently has.
+ return;
+ // It's a non-primitive - set its value to null. In most cases, this should tell the managed resource
+ // to use its internal default.
+ log.debug("Simple property '" + propDefSimple.getName()
+ + "' has a null value - setting inner value of corresponding ManagedProperty's MetaValue to null...");
+ value = null;
+ }
+ }
+ else
+ {
+ value = propSimple.getStringValue();
+ }
+ setInnerValue(value, metaValue, propDefSimple);
+ }
+
+ protected abstract void setInnerValue(String propSimpleValue, MetaValue metaValue, PropertyDefinitionSimple propDefSimple);
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,34 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.rhq.plugin.adapter.api;
+
+import org.rhq.core.domain.measurement.MeasurementDefinition;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
+
+import org.jboss.metatype.api.values.MetaValue;
+
+public interface MeasurementAdapter {
+ public void setMeasurementData(MeasurementReport report, MetaValue metaValue, MeasurementScheduleRequest request,
+ MeasurementDefinition measurementDefinition);
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapterFactory.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapterFactory.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/MeasurementAdapterFactory.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,99 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.api;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.metatype.api.types.MetaType;
+
+public class MeasurementAdapterFactory
+{
+
+ private static final Log LOG = LogFactory.getLog(MeasurementAdapterFactory.class);
+
+ private static Map<String, String> customAdapters = new HashMap<String, String>();
+
+ {
+ // Add customAdapters to the map
+ customAdapters.put("NoClasses", "NoClasses");
+ }
+
+ public static MeasurementAdapter getMeasurementPropertyAdapter(MetaType metaType)
+ {
+ MeasurementAdapter measurementAdapter = null;
+ if (metaType.isSimple())
+ {
+ // measurementAdapter = new SimpleMetaValueMeasurementAdapter();
+ }
+ else if (metaType.isGeneric())
+ {
+ measurementAdapter = null;
+ }
+ else if (metaType.isComposite())
+ {
+ measurementAdapter = null;
+ }
+ else if (metaType.isTable())
+ {
+ measurementAdapter = null;
+ }
+ else if (metaType.isCollection())
+ {
+ measurementAdapter = null;
+ }
+ else if (metaType.isArray())
+ {
+ measurementAdapter = null;
+ }
+
+ return measurementAdapter;
+ }
+
+ public static MeasurementAdapter getCustomMeasurementPropertyAdapter(String measurementName)
+ {
+ MeasurementAdapter measurementAdapter = null;
+ String adapterClassName = customAdapters.get(measurementName);
+ if (adapterClassName != null && !adapterClassName.equals(""))
+ {
+ try
+ {
+ measurementAdapter = (MeasurementAdapter)Class.forName(adapterClassName).newInstance();
+ }
+ catch (InstantiationException e)
+ {
+ LOG.error("Cannot instantiate adapter class called " + adapterClassName, e);
+ }
+ catch (IllegalAccessException e)
+ {
+ LOG.error("Cannot access adapter class called " + adapterClassName, e);
+ }
+ catch (ClassNotFoundException e)
+ {
+ LOG.error("Cannot find adapter class called " + adapterClassName, e);
+ }
+ }
+ return measurementAdapter;
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,87 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.api;
+
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * An adapter that can convert back and forth between a specific type of {@link MetaValue} and a specific type of {@link
+ * Property}.
+ *
+ * @author Mark Spritzler
+ * @author Ian Springer
+ */
+public interface PropertyAdapter<P extends Property, D extends PropertyDefinition>
+{
+ /**
+ * Given a {@link Property} and its {@link PropertyDefinition}, as well as a {@link MetaValue}, populate that
+ * MetaValue so it corresponds to the Property. If the Property is a list or a map, all descendant Property's should
+ * be added as descendants of the MetaValue.
+ *
+ * @param property the property to be copied
+ * @param metaValue the MetaValue to be populated; should not be null
+ * @param propertyDefinition the property's definition
+ */
+ public void populateMetaValueFromProperty(P property, MetaValue metaValue, D propertyDefinition);
+
+ /**
+ * Given a {@link Property} and its {@link PropertyDefinition}, create and return a corresponding {@link MetaValue}
+ * with the specified {@link MetaType}. If the Property is a list or a map, all descendant Property's should be
+ * represented as descendants of the returned MetaValue. Generally this method can simply create an empty MetaValue
+ * object and then delegate the population of the guts of the object to {@link #populateMetaValueFromProperty(Property,
+ * MetaValue, PropertyDefinition)}.
+ *
+ * @param property the property to be converted
+ * @param propertyDefinition the property's definition
+ * @param metaType the type of MetaValue that should be created and returned
+ * @return the MetaValue representation of the given Property
+ */
+ public MetaValue convertToMetaValue(P property, D propertyDefinition, MetaType metaType);
+
+ /**
+ * Given a {@link Property} and its {@link PropertyDefinition}, as well as a {@link MetaValue}, populate the
+ * Property so it corresponds to the MetaValue. If the MetaValue is a from of list or map, all descendant
+ * MetaValue's should be added as descendants of the Property.
+ *
+ * @param property the property to be populated; should not be null
+ * @param metaValue the MetaValue to be copied
+ * @param propertyDefinition the property's definition
+ */
+ public void populatePropertyFromMetaValue(P property, MetaValue metaValue, D propertyDefinition);
+
+ /**
+ * Given a {@link MetaValue}, create and return a corresponding {@link Property} with the specified {@link
+ * PropertyDefinition}. If the MetaValue is a form of list or map, all descendant MetaValue's should be represented
+ * as descendants of the returned Property. Generally this method can simply create an empty Property object and
+ * then delegate the population of the guts of the object to {@link #populatePropertyFromMetaValue(Property,
+ * MetaValue, PropertyDefinition)}.
+ *
+ * @param metaValue the metaValue to be converted
+ * @param propertyDefinition the definition of the property to be created and returned
+ * @return the Property representation of the given MetaValue
+ */
+ public P convertToProperty(MetaValue metaValue, D propertyDefinition);
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/api/PropertyAdapterFactory.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,124 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.PropertiesMetaType;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.teiid.rhq.plugin.adapter.impl.PropertyListToArrayValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyListToCollectionValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToCompositeValueSupportAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToGenericValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToMapCompositeValueSupportAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToPropertiesValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertyMapToTableValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToEnumValueAdapter;
+import org.teiid.rhq.plugin.adapter.impl.PropertySimpleToSimpleValueAdapter;
+
+import com.sun.istack.Nullable;
+
+/**
+ * @author Mark Spritzler
+ */
+public class PropertyAdapterFactory
+{
+ private static final Log LOG = LogFactory.getLog(PropertyAdapterFactory.class);
+
+ public static PropertyAdapter getPropertyAdapter(MetaValue metaValue)
+ {
+ if (metaValue == null)
+ {
+ LOG.debug("The MetaValue passed in is null.");
+ return null;
+ }
+ MetaType metaType = metaValue.getMetaType();
+ return getPropertyAdapter(metaType);
+ }
+
+ public static PropertyAdapter getPropertyAdapter(MetaType metaType)
+ {
+ PropertyAdapter propertyAdapter = null;
+ if (metaType.isSimple())
+ {
+ propertyAdapter = new PropertySimpleToSimpleValueAdapter();
+ }
+ else if (metaType.isGeneric())
+ {
+ propertyAdapter = new PropertyMapToGenericValueAdapter();
+ }
+ else if (metaType.isComposite())
+ {
+ if (metaType instanceof MapCompositeMetaType)
+ propertyAdapter = new PropertyMapToMapCompositeValueSupportAdapter();
+ else
+ propertyAdapter = new PropertyMapToCompositeValueSupportAdapter();
+ }
+ else if (metaType.isTable())
+ {
+ propertyAdapter = new PropertyMapToTableValueAdapter();
+ }
+ else if (metaType.isCollection())
+ {
+ propertyAdapter = new PropertyListToCollectionValueAdapter();
+ }
+ else if (metaType.isArray())
+ {
+ propertyAdapter = new PropertyListToArrayValueAdapter();
+ }
+ else if (metaType.isEnum())
+ {
+ propertyAdapter = new PropertySimpleToEnumValueAdapter();
+ }
+ else if (metaType instanceof PropertiesMetaType)
+ {
+ propertyAdapter = new PropertyMapToPropertiesValueAdapter();
+ }
+ else
+ {
+ LOG.warn("Unsupported MetaType: " + metaType);
+ }
+ return propertyAdapter;
+ }
+
+ @Nullable
+ public static PropertyAdapter getCustomPropertyAdapter(PropertySimple customProp)
+ {
+ if (customProp == null)
+ return null;
+ String adapterClassName = customProp.getStringValue();
+ PropertyAdapter propertyAdapter = null;
+ try
+ {
+ Class adapterClass = Class.forName(adapterClassName);
+ propertyAdapter = (PropertyAdapter)adapterClass.newInstance();
+ }
+ catch (Exception e)
+ {
+ LOG.error("Unable to create custom adapter class for " + customProp + ".", e);
+ }
+ return propertyAdapter;
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/AbstractPropertyMapToCompositeValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/AbstractPropertyMapToCompositeValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/AbstractPropertyMapToCompositeValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,119 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyMapAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.CompositeValue;
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertyMap} and a {@link CompositeValue}.
+ * Subclasses exist for the two different implementations of <code>CompositeValue</code>.
+ *
+ */
+public abstract class AbstractPropertyMapToCompositeValueAdapter extends AbstractPropertyMapAdapter
+ implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ private final Log log = LogFactory.getLog(this.getClass());
+
+ public void populateMetaValueFromProperty(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ CompositeValue compositeValue = (CompositeValue)metaValue;
+ for (String mapMemberPropName : propMap.getMap().keySet())
+ {
+ Property mapMemberProp = propMap.get(mapMemberPropName);
+ PropertyDefinition mapMemberPropDef = propDefMap.get(mapMemberPropName);
+ MetaType mapMemberMetaType = compositeValue.getMetaType().getType(mapMemberPropName);
+ if (mapMemberMetaType == null)
+ {
+ // this will occur when new map properties are added since they are not present
+ // in the original metaValue which we are using
+ mapMemberMetaType = SimpleMetaType.STRING;
+ }
+ PropertyAdapter adapter = PropertyAdapterFactory.getPropertyAdapter(mapMemberMetaType);
+ MetaValue mapMemberMetaValue = adapter.convertToMetaValue(mapMemberProp, mapMemberPropDef, mapMemberMetaType);
+ putValue(compositeValue, mapMemberPropName, mapMemberMetaValue);
+ }
+ }
+
+ public MetaValue convertToMetaValue(PropertyMap propMap, PropertyDefinitionMap propDefMap, MetaType metaType)
+ {
+ CompositeValue compositeValue = createCompositeValue(propDefMap, metaType);
+ populateMetaValueFromProperty(propMap, compositeValue, propDefMap);
+ return compositeValue;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ if (metaValue == null)
+ return;
+ CompositeValue compositeValue = (CompositeValue)metaValue;
+ Set<String> mapMemberPropNames = compositeValue.getMetaType().keySet();
+ // There won't be any keys when loading a Configuration for the first time.
+ for (String mapMemberPropName : mapMemberPropNames)
+ {
+ Property mapMemberProp = propMap.get(mapMemberPropName);
+ MetaValue mapMemberMetaValue = compositeValue.get(mapMemberPropName);
+ MetaType mapMemberMetaType = compositeValue.getMetaType().getType(mapMemberPropName);
+ PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(mapMemberMetaType);
+ PropertyDefinition mapMemberPropDef = propDefMap.get(mapMemberPropName);
+ if (mapMemberProp == null)
+ {
+ if (mapMemberPropDef != null)
+ mapMemberProp = propertyAdapter.convertToProperty(mapMemberMetaValue, mapMemberPropDef);
+ else
+ {
+ // If the member prop has no associated prop def, this is an "open map".
+ if (!mapMemberMetaType.isSimple() && !mapMemberMetaType.isEnum())
+ {
+ log.debug("Map member prop [" + mapMemberMetaType + "] is not a simple type - skipping...");
+ continue;
+ }
+ // Create a PropertySimple and populate it.
+ mapMemberProp = new PropertySimple(mapMemberPropName, null);
+ // NOTE: It's ok that the propDef is null - PropertySimple*Adapter.populatePropertyFromMetaValue()
+ // doesn't use it for anything.
+ propertyAdapter.populatePropertyFromMetaValue(mapMemberProp, mapMemberMetaValue, mapMemberPropDef);
+ }
+ propMap.put(mapMemberProp);
+ }
+ }
+ }
+
+ protected abstract void putValue(CompositeValue compositeValue, String key, MetaValue value);
+
+ protected abstract CompositeValue createCompositeValue(PropertyDefinitionMap propDefMap, MetaType metaType);
+}
\ No newline at end of file
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToArrayValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyListAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.ArrayValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.MetaValueFactory;
+
+/**
+ *
+ */
+public class PropertyListToArrayValueAdapter extends AbstractPropertyListAdapter implements PropertyAdapter<PropertyList, PropertyDefinitionList>
+{
+ //@todo need to implement this like the other List to Collection, but not until there is an actual property that needs this
+ public void populateMetaValueFromProperty(PropertyList property, MetaValue metaValue, PropertyDefinitionList propertyDefinition)
+ {
+ PropertyDefinition memberDefinition = propertyDefinition.getMemberDefinition();
+ List<Property> properties = property.getList();
+ if (metaValue != null)
+ {
+ ArrayValueSupport valueSupport = (ArrayValueSupport)metaValue;
+ MetaType listMetaType = valueSupport.getMetaType().getElementType();
+ List<MetaValue> values = new ArrayList<MetaValue>(properties.size());
+ for (Property propertyWithinList : properties)
+ {
+ MetaValue value = MetaValueFactory.getInstance().create(null);
+ PropertyAdapter<Property, PropertyDefinition> propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMetaType);
+ propertyAdapter.populateMetaValueFromProperty(propertyWithinList, value, memberDefinition);
+ values.add(value);
+ }
+ valueSupport.setValue(values.toArray());
+ }
+ }
+
+ //@todo need to implement this like the other List to Collection, but not until there is an actual property that needs this
+ public MetaValue convertToMetaValue(PropertyList property, PropertyDefinitionList propertyDefinition, MetaType type)
+ {
+ return null;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyList property, MetaValue metaValue, PropertyDefinitionList propertyDefinition)
+ {
+ PropertyDefinition memberDefinition = propertyDefinition.getMemberDefinition();
+ List<Property> properties = property.getList();
+
+ // Since we want to load the PropertyList with fresh values, we want it cleared out
+ properties.clear();
+
+ if (metaValue != null)
+ {
+ ArrayValueSupport valueSupport = (ArrayValueSupport)metaValue;
+ MetaType listMetaType = valueSupport.getMetaType().getElementType();
+ MetaValue[] metaValues = (MetaValue[])valueSupport.getValue();
+ PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMetaType);
+ for (MetaValue value : metaValues)
+ {
+ Property propertyToAddToList = propertyAdapter.convertToProperty(value, memberDefinition);
+ properties.add(propertyToAddToList);
+ }
+ }
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToCollectionValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToCollectionValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyListToCollectionValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,98 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.metatype.api.types.CollectionMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.CollectionValue;
+import org.jboss.metatype.api.values.CollectionValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyListAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+
+/**
+ *
+ */
+public class PropertyListToCollectionValueAdapter extends AbstractPropertyListAdapter implements PropertyAdapter<PropertyList, PropertyDefinitionList>
+{
+ private static final Log LOG = LogFactory.getLog(PropertyListToCollectionValueAdapter.class);
+
+ public void populateMetaValueFromProperty(PropertyList property, MetaValue metaValue, PropertyDefinitionList propertyDefinition)
+ {
+ PropertyDefinition listMemberPropDef = propertyDefinition.getMemberDefinition();
+ List<Property> listMemberProps = property.getList();
+ CollectionValueSupport collectionValue = (CollectionValueSupport)metaValue;
+ MetaType listMemberMetaType = collectionValue.getMetaType().getElementType();
+ MetaValue[] listMemberValues = new MetaValue[listMemberProps.size()];
+ PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMemberMetaType);
+ int memberIndex = 0;
+ for (Property listMemberProp : listMemberProps)
+ {
+ MetaValue listMemberValue = propertyAdapter.convertToMetaValue(listMemberProp, listMemberPropDef, listMemberMetaType);
+ listMemberValues[memberIndex++] = listMemberValue;
+ }
+ // Replace the existing elements with the new ones.
+ collectionValue.setElements(listMemberValues);
+ }
+
+ public MetaValue convertToMetaValue(PropertyList propertyList, PropertyDefinitionList propertyListDefinition, MetaType metaType)
+ {
+ LOG.debug("GetMetaValue for property: " + propertyList.getName() + " values: " + propertyList.getList().toString());
+ CollectionMetaType collectionMetaType = (CollectionMetaType)metaType;
+ MetaType memberMetaType = collectionMetaType.getElementType();
+ CollectionMetaType collectionType = new CollectionMetaType(propertyListDefinition.getName(), memberMetaType);
+ CollectionValue collectionValue = new CollectionValueSupport(collectionType);
+ populateMetaValueFromProperty(propertyList, collectionValue, propertyListDefinition);
+ return collectionValue;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyList propList, MetaValue metaValue, PropertyDefinitionList propDefList)
+ {
+ PropertyDefinition memberPropDef = propDefList.getMemberDefinition();
+ if (propList != null)
+ {
+ // Since we want to load the PropertyList with fresh values, we want it cleared out.
+ propList.getList().clear();
+ if (metaValue != null)
+ {
+ CollectionValue collectionValue = (CollectionValue)metaValue;
+ MetaType listMemberMetaType = collectionValue.getMetaType().getElementType();
+ MetaValue[] listMemberValues = collectionValue.getElements();
+ PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(listMemberMetaType);
+ for (MetaValue listMemberValue : listMemberValues)
+ {
+ Property listMemberProp = propertyAdapter.convertToProperty(listMemberValue, memberPropDef);
+ propList.add(listMemberProp);
+ }
+ }
+ }
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToCompositeValueSupportAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToCompositeValueSupportAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToCompositeValueSupportAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,75 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.CompositeValue;
+import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.plugins.types.MutableCompositeMetaType;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertyMap} and a {@link CompositeValueSupport}.
+ * A <code>CompositeValueSupport</code> is a {@link CompositeValue} implementation that contains items that may be of
+ * different types.
+ *
+ */
+public class PropertyMapToCompositeValueSupportAdapter extends AbstractPropertyMapToCompositeValueAdapter
+ implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ protected void putValue(CompositeValue compositeValue, String key, MetaValue value)
+ {
+ CompositeValueSupport compositeValueSupport = (CompositeValueSupport)compositeValue;
+ compositeValueSupport.set(key, value);
+ }
+
+ protected CompositeValue createCompositeValue(PropertyDefinitionMap propDefMap, MetaType metaType)
+ {
+ MutableCompositeMetaType compositeMetaType;
+ if (metaType != null)
+ compositeMetaType = (MutableCompositeMetaType)metaType;
+ else
+ {
+ // TODO: See if this else block is actually necessary (I think it is needed for creates).
+ String name = (propDefMap != null) ?
+ propDefMap.getName() : "CompositeMetaType";
+ String desc = (propDefMap != null && propDefMap.getDescription() != null) ?
+ propDefMap.getDescription() : "none";
+ compositeMetaType = new MutableCompositeMetaType(name, desc);
+ if (propDefMap != null)
+ {
+ for (PropertyDefinition mapMemberPropDef : propDefMap.getPropertyDefinitions().values())
+ {
+ String mapMemberDesc = (propDefMap.getDescription() != null) ? propDefMap.getDescription() : "none";
+ MetaType mapMemberMetaType = ProfileServiceUtil.convertPropertyDefinitionToMetaType(mapMemberPropDef);
+ compositeMetaType.addItem(mapMemberPropDef.getName(), mapMemberDesc, mapMemberMetaType);
+ }
+ }
+ }
+ return new CompositeValueSupport(compositeMetaType);
+ }
+}
\ No newline at end of file
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToGenericValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToGenericValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToGenericValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,135 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.managed.api.ManagedObject;
+import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.plugins.ManagedObjectImpl;
+import org.jboss.managed.plugins.ManagedPropertyImpl;
+import org.jboss.metatype.api.types.GenericMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.values.GenericValue;
+import org.jboss.metatype.api.values.GenericValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyMapAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+import org.teiid.rhq.plugin.util.ProfileServiceUtil;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertyMap} and a {@link GenericValue}. The
+ * GenericValue's value is assumed to be a {@link ManagedObject}.
+ *
+ */
+public class PropertyMapToGenericValueAdapter extends AbstractPropertyMapAdapter
+ implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ private final Log log = LogFactory.getLog(this.getClass());
+
+ public void populateMetaValueFromProperty(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ GenericValue genericValue = (GenericValue)metaValue;
+ if (!(genericValue.getValue() instanceof ManagedObject))
+ {
+ log.error("GenericValue's value [" + genericValue.getValue() + "] is not a ManagedObject - not supported!");
+ return;
+ }
+ ManagedObject managedObject = (ManagedObject)genericValue.getValue();
+ for (String propName : propMap.getMap().keySet())
+ {
+ Property mapMemberProp = propMap.get(propName);
+ ManagedProperty managedProp = managedObject.getProperty(propName);
+ MetaType metaType = managedProp.getMetaType();
+ PropertyAdapter propertyAdapter = PropertyAdapterFactory.getPropertyAdapter(metaType);
+ PropertyDefinition mapMemberPropDef = propDefMap.get(propName);
+ if (managedProp.getValue() == null)
+ {
+ MetaValue managedPropMetaValue = propertyAdapter.convertToMetaValue(mapMemberProp, mapMemberPropDef, metaType);
+ managedProp.setValue(managedPropMetaValue);
+ }
+ else
+ {
+ MetaValue managedPropMetaValue = (MetaValue)managedProp.getValue();
+ propertyAdapter.populateMetaValueFromProperty(mapMemberProp, managedPropMetaValue, mapMemberPropDef);
+ }
+ }
+ }
+
+ public MetaValue convertToMetaValue(PropertyMap propMap, PropertyDefinitionMap propDefMap, MetaType metaType)
+ {
+ //GenericMetaType genericMetaType = (GenericMetaType)metaType;
+ ManagedObjectImpl managedObject = new ManagedObjectImpl(propDefMap.getName());
+ for (PropertyDefinition mapMemberPropDef : propDefMap.getPropertyDefinitions().values())
+ {
+ ManagedPropertyImpl managedProp = new ManagedPropertyImpl(mapMemberPropDef.getName());
+ MetaType managedPropMetaType = ProfileServiceUtil.convertPropertyDefinitionToMetaType(mapMemberPropDef);
+ managedProp.setMetaType(managedPropMetaType);
+ managedProp.setManagedObject(managedObject);
+ managedObject.getProperties().put(managedProp.getName(), managedProp);
+ }
+ GenericValue genericValue = new GenericValueSupport(new GenericMetaType(propDefMap.getName(),
+ propDefMap.getDescription()), managedObject);
+ populateMetaValueFromProperty(propMap, genericValue, propDefMap);
+ return genericValue;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ GenericValue genericValue = (GenericValue)metaValue;
+ ManagedObject managedObject = (ManagedObject)genericValue.getValue();
+ for (String propName : propDefMap.getPropertyDefinitions().keySet())
+ {
+ ManagedProperty managedProp = managedObject.getProperty(propName);
+ if (managedProp != null)
+ {
+ MetaType metaType = managedProp.getMetaType();
+ Object value;
+ if (metaType.isSimple())
+ {
+ SimpleValue simpleValue = (SimpleValue)managedProp.getValue();
+ value = simpleValue.getValue();
+ }
+ else if (metaType.isEnum())
+ {
+ EnumValue enumValue = (EnumValue)managedProp.getValue();
+ value = enumValue.getValue();
+ }
+ else
+ {
+ log.error("Nested ManagedProperty's value [" + managedProp.getValue()
+ + "] is not a SimpleValue or EnumValue - unsupported!");
+ continue;
+ }
+ propMap.put(new PropertySimple(propName, value));
+ }
+ }
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToMapCompositeValueSupportAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToMapCompositeValueSupportAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToMapCompositeValueSupportAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+
+import org.jboss.metatype.api.types.MapCompositeMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.CompositeValue;
+import org.jboss.metatype.api.values.MapCompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertyMap} and a {@link
+ * MapCompositeValueSupport}. A <code>MapCompositeValueSupport</code> is a {@link CompositeValue} implementation that
+ * contains items that are all of the same type; there is no predefined list of valid keys, so it maps nicely to an
+ * "open" PropertyMap.
+ *
+ */
+public class PropertyMapToMapCompositeValueSupportAdapter extends AbstractPropertyMapToCompositeValueAdapter implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ @Override
+ public void populateMetaValueFromProperty(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ MapCompositeValueSupport mapCompositeValueSupport = (MapCompositeValueSupport)metaValue;
+ // First clear out all existing values from the MapCompositeValue.
+ for (String key : mapCompositeValueSupport.getMetaType().keySet())
+ {
+ mapCompositeValueSupport.remove(key);
+ }
+ // Now re-populate it with the values from the PropertyMap.
+ super.populateMetaValueFromProperty(propMap, metaValue, propDefMap);
+ }
+
+ protected void putValue(CompositeValue compositeValue, String key, MetaValue value)
+ {
+ MapCompositeValueSupport mapCompositeValueSupport = (MapCompositeValueSupport)compositeValue;
+ mapCompositeValueSupport.put(key, value);
+ }
+
+ protected CompositeValue createCompositeValue(PropertyDefinitionMap propDefMap, MetaType metaType)
+ {
+ MapCompositeMetaType mapCompositeMetaType = (MapCompositeMetaType)metaType;
+ MetaType mapMemberMetaType = mapCompositeMetaType.getValueType();
+ return new MapCompositeValueSupport(mapMemberMetaType);
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToPropertiesValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToPropertiesValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToPropertiesValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,86 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.PropertiesMetaValue;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyMapAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertyMap} and a {@link PropertiesMetaValue}. A
+ * <code>PropertiesMetaValue</code> extends java.util.Properties. Its associated PropertiesMetaType may or may not
+ * define member property names; since the RHQ Configuration system assumes a PropertyDefinitionMap either defines none
+ * of its member properties (i.e. an "open map") or defines all of them, we just ignore the PropertiesMetaType and
+ * always map to an open map.
+ *
+ */
+public class PropertyMapToPropertiesValueAdapter extends AbstractPropertyMapAdapter
+ implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ public void populateMetaValueFromProperty(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ PropertiesMetaValue propertiesValue = (PropertiesMetaValue)metaValue;
+ for (String mapMemberPropName : propMap.getMap().keySet())
+ {
+ Property mapMemberProp = propMap.get(mapMemberPropName);
+ propertiesValue.setProperty(mapMemberProp.getName(), ((PropertySimple)mapMemberProp).getStringValue());
+ }
+ }
+
+ public MetaValue convertToMetaValue(PropertyMap propMap, PropertyDefinitionMap propDefMap, MetaType metaType)
+ {
+ PropertiesMetaValue propertiesValue = new PropertiesMetaValue();
+ populateMetaValueFromProperty(propMap, propertiesValue, propDefMap);
+ return propertiesValue;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyMap propMap, MetaValue metaValue, PropertyDefinitionMap propDefMap)
+ {
+ if (metaValue == null)
+ return;
+ PropertiesMetaValue propertiesValue = (PropertiesMetaValue)metaValue;
+ Set<String> mapMemberPropNames = new HashSet();
+ for (Object key : propertiesValue.keySet())
+ mapMemberPropNames.add((String)key);
+ // There won't be any keys when loading a Configuration for the first time.
+ for (String mapMemberPropName : mapMemberPropNames)
+ {
+ // We assume the PropertyMap is an "open map", since that's what PropertiesMetaValue maps to.
+ PropertySimple mapMemberProp = propMap.getSimple(mapMemberPropName);
+ // Create a PropertySimple and populate it.
+ if (mapMemberProp == null)
+ {
+ mapMemberProp = new PropertySimple(mapMemberPropName, propertiesValue.getProperty(mapMemberPropName));
+ propMap.put(mapMemberProp);
+ }
+ }
+ }
+}
\ No newline at end of file
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToTableValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToTableValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertyMapToTableValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,92 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.CompositeValue;
+import org.jboss.metatype.api.values.CompositeValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+import org.jboss.metatype.api.values.TableValueSupport;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertyMapAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+
+/**
+ *
+ */
+public class PropertyMapToTableValueAdapter extends AbstractPropertyMapAdapter implements PropertyAdapter<PropertyMap, PropertyDefinitionMap>
+{
+ public PropertyMap convertToProperty(MetaValue metaValue, PropertyDefinitionMap propertyDefinition)
+ {
+ PropertyMap property = new PropertyMap();
+ populatePropertyFromMetaValue(property, metaValue, propertyDefinition);
+ return property;
+ }
+
+ //@todo need to implement this like the other Map to Composite, but not until there is an actual property that needs this
+ public void populateMetaValueFromProperty(PropertyMap property, MetaValue metaValue, PropertyDefinitionMap propertyDefinition)
+ {
+ if (metaValue != null)
+ {
+ TableValueSupport tableValueSupport = (TableValueSupport)metaValue;
+ Map<String, PropertyDefinition> map = propertyDefinition.getPropertyDefinitions();
+ Map<String, Property> properties = property.getMap();
+ for (String key : map.keySet())
+ {
+ PropertyDefinition definition = map.get(key);
+ MetaValue[] getKey = new MetaValue[]{SimpleValueSupport.wrap(key)};
+ MetaValue value = tableValueSupport.get(getKey);
+ Property innerProperty = properties.get(key);
+ PropertyAdapter adapter = PropertyAdapterFactory.getPropertyAdapter(value);
+ adapter.populateMetaValueFromProperty(innerProperty, value, definition);
+ }
+ }
+ }
+
+ //@todo need to implement this like the other Map to Composite, but not until there is an actual property that needs this
+ public MetaValue convertToMetaValue(PropertyMap property, PropertyDefinitionMap propertyDefinition, MetaType type)
+ {
+ return null;
+ }
+
+ public void populatePropertyFromMetaValue(PropertyMap property, MetaValue metaValue, PropertyDefinitionMap propertyDefinition)
+ {
+ // Not important at this moment to implement as there sin't a need for this mapping yet.
+ if (metaValue != null)
+ {
+ TableValueSupport valueSupport = (TableValueSupport)metaValue;
+ Collection<CompositeValue> values = valueSupport.values();
+ for (CompositeValue value : values)
+ {
+ CompositeValueSupport support = (CompositeValueSupport)value;
+ }
+ }
+ }
+}
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToEnumValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToEnumValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToEnumValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,58 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import org.jboss.metatype.api.types.EnumMetaType;
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.values.EnumValue;
+import org.jboss.metatype.api.values.EnumValueSupport;
+import org.jboss.metatype.api.values.MetaValue;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertySimpleAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertySimple} and an {@link EnumValueSupport}.
+ *
+ */
+public class PropertySimpleToEnumValueAdapter extends AbstractPropertySimpleAdapter implements PropertyAdapter<PropertySimple, PropertyDefinitionSimple>
+{
+ public void populatePropertyFromMetaValue(PropertySimple propSimple, MetaValue metaValue, PropertyDefinitionSimple propDefSimple)
+ {
+ Object value = (metaValue != null) ? ((EnumValue)metaValue).getValue() : null;
+ propSimple.setValue(value);
+ }
+
+ public MetaValue convertToMetaValue(PropertySimple propSimple, PropertyDefinitionSimple propDefSimple, MetaType metaType)
+ {
+ EnumValue enumValue = new EnumValueSupport((EnumMetaType)metaType, propSimple.getStringValue());
+ populateMetaValueFromProperty(propSimple, enumValue, propDefSimple);
+ return enumValue;
+ }
+
+ protected void setInnerValue(String propSimpleValue, MetaValue metaValue, PropertyDefinitionSimple propDefSimple)
+ {
+ EnumValueSupport enumValueSupport = (EnumValueSupport)metaValue;
+ enumValueSupport.setValue(propSimpleValue);
+ }
+}
\ No newline at end of file
Added: trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToSimpleValueAdapter.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToSimpleValueAdapter.java (rev 0)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/adapter/impl/PropertySimpleToSimpleValueAdapter.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -0,0 +1,94 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.rhq.plugin.adapter.impl;
+
+import java.io.Serializable;
+
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.teiid.rhq.plugin.adapter.api.AbstractPropertySimpleAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+
+import org.jboss.metatype.api.types.MetaType;
+import org.jboss.metatype.api.types.SimpleMetaType;
+import org.jboss.metatype.api.values.MetaValue;
+import org.jboss.metatype.api.values.SimpleValue;
+import org.jboss.metatype.api.values.SimpleValueSupport;
+
+/**
+ * This class provides code that maps back and forth between a {@link PropertySimple} and a {@link SimpleValueSupport}.
+ *
+ */
+public class PropertySimpleToSimpleValueAdapter extends AbstractPropertySimpleAdapter implements PropertyAdapter<PropertySimple, PropertyDefinitionSimple>
+{
+ public void populatePropertyFromMetaValue(PropertySimple propSimple, MetaValue metaValue, PropertyDefinitionSimple propDefSimple)
+ {
+ Object value = (metaValue != null) ? ((SimpleValue)metaValue).getValue() : null;
+ propSimple.setValue(value);
+ }
+
+ public MetaValue convertToMetaValue(PropertySimple propSimple, PropertyDefinitionSimple propDefSimple, MetaType metaType)
+ {
+ SimpleValue simpleValue = new SimpleValueSupport((SimpleMetaType)metaType, null);
+ populateMetaValueFromProperty(propSimple, simpleValue, propDefSimple);
+ return simpleValue;
+ }
+
+ protected void setInnerValue(String propSimpleValue, MetaValue metaValue, PropertyDefinitionSimple propDefSimple)
+ {
+ SimpleValueSupport simpleValueSupport = (SimpleValueSupport)metaValue;
+ if (propSimpleValue == null)
+ {
+ // A null value is the easiest case - just set the SimpleMetaValue's inner value to null.
+ simpleValueSupport.setValue(null);
+ return;
+ }
+ // String value is non-null, so we can massage it into the proper type for the SimpleMetaValue's inner value.
+ SimpleMetaType simpleMetaType = simpleValueSupport.getMetaType();
+ Serializable innerValue;
+ if (simpleMetaType.equals(SimpleMetaType.STRING) || simpleMetaType.equals(SimpleMetaType.NAMEDOBJECT))
+ innerValue = propSimpleValue;
+ else if (simpleMetaType.equals(SimpleMetaType.BOOLEAN) || simpleMetaType.equals(SimpleMetaType.BOOLEAN_PRIMITIVE))
+ innerValue = Boolean.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.BYTE) || simpleMetaType.equals(SimpleMetaType.BYTE_PRIMITIVE))
+ innerValue = Byte.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.CHARACTER) || simpleMetaType.equals(SimpleMetaType.CHARACTER_PRIMITIVE))
+ {
+ if (propSimpleValue.length() != 1)
+ throw new IllegalStateException("String value '" + propSimpleValue + " cannot be converted to a character.");
+ innerValue = propSimpleValue.charAt(0);
+ }
+ else if (simpleMetaType.equals(SimpleMetaType.DOUBLE) || simpleMetaType.equals(SimpleMetaType.DOUBLE_PRIMITIVE))
+ innerValue = Double.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.FLOAT) || simpleMetaType.equals(SimpleMetaType.FLOAT_PRIMITIVE))
+ innerValue = Float.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.INTEGER) || simpleMetaType.equals(SimpleMetaType.INTEGER_PRIMITIVE))
+ innerValue = Integer.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.LONG) || simpleMetaType.equals(SimpleMetaType.LONG_PRIMITIVE))
+ innerValue = Long.valueOf(propSimpleValue);
+ else if (simpleMetaType.equals(SimpleMetaType.SHORT) || simpleMetaType.equals(SimpleMetaType.SHORT_PRIMITIVE))
+ innerValue = Short.valueOf(propSimpleValue);
+ else
+ throw new IllegalStateException("Unsupported MetaType: " + simpleMetaType);
+ simpleValueSupport.setValue(innerValue);
+ }
+}
Modified: trunk/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java
===================================================================
--- trunk/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/java/org/teiid/rhq/plugin/util/ProfileServiceUtil.java 2010-05-19 23:20:03 UTC (rev 2145)
@@ -1,8 +1,36 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
package org.teiid.rhq.plugin.util;
import java.io.File;
+import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
import java.util.Set;
import javax.naming.InitialContext;
@@ -17,21 +45,104 @@
import org.jboss.managed.api.ManagedComponent;
import org.jboss.managed.api.ManagedDeployment;
import org.jboss.managed.api.ManagedProperty;
+import org.jboss.managed.api.annotation.ViewUse;
+import org.jboss.metatype.api.types.MapCompositeMetaType;
import org.jboss.metatype.api.types.MetaType;
import org.jboss.metatype.api.types.SimpleMetaType;
import org.jboss.metatype.api.values.EnumValue;
import org.jboss.metatype.api.values.MetaValue;
import org.jboss.metatype.api.values.SimpleValue;
import org.jboss.profileservice.spi.ProfileService;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.configuration.definition.ConfigurationTemplate;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.rhq.core.domain.configuration.definition.PropertySimpleType;
+import org.rhq.core.domain.resource.ResourceType;
+import org.teiid.rhq.plugin.TranslatorComponent;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapter;
+import org.teiid.rhq.plugin.adapter.api.PropertyAdapterFactory;
+import com.sun.istack.NotNull;
+import com.sun.istack.Nullable;
public class ProfileServiceUtil {
- protected final Log LOG = LogFactory.getLog(ProfileServiceUtil.class);
+ protected final static Log LOG = LogFactory
+ .getLog(ProfileServiceUtil.class);
private static ComponentType DQPTYPE = new ComponentType("teiid", "dqp");
private static String DQPNAME = "org.teiid.jboss.deployers.RuntimeEngineDeployer";
+ private static final Map<String, ComponentType> COMPONENT_TYPE_CACHE = new HashMap<String, ComponentType>();
+ private static final Map<String, KnownDeploymentTypes> DEPLOYMENT_TYPE_CACHE = new HashMap<String, KnownDeploymentTypes>();
+ private static final Map<String, Configuration> DEFAULT_PLUGIN_CONFIG_CACHE = new HashMap<String, Configuration>();
+ protected static final String PLUGIN = "ProfileService";
+
+ public static ComponentType getComponentType(
+ @NotNull ResourceType resourceType) {
+ String resourceTypeName = resourceType.getName();
+ if (COMPONENT_TYPE_CACHE.containsKey(resourceTypeName))
+ return COMPONENT_TYPE_CACHE.get(resourceTypeName);
+ Configuration defaultPluginConfig = getDefaultPluginConfiguration(resourceType);
+ String type = defaultPluginConfig.getSimpleValue(
+ TranslatorComponent.Config.COMPONENT_TYPE, null);
+ if (type == null || type.equals(""))
+ throw new IllegalStateException(
+ "Required plugin configuration property '"
+ + TranslatorComponent.Config.COMPONENT_TYPE
+ + "' is not defined in default template.");
+ String subtype = defaultPluginConfig.getSimpleValue(
+ TranslatorComponent.Config.COMPONENT_SUBTYPE, null);
+ if (subtype == null || subtype.equals(""))
+ throw new IllegalStateException(
+ "Required plugin configuration property '"
+ + TranslatorComponent.Config.COMPONENT_SUBTYPE
+ + "' is not defined in default template.");
+ ComponentType componentType = new ComponentType(type, subtype);
+ COMPONENT_TYPE_CACHE.put(resourceTypeName, componentType);
+ return componentType;
+ }
+
+ private static Configuration getDefaultPluginConfiguration(
+ ResourceType resourceType) {
+ ConfigurationTemplate pluginConfigDefaultTemplate = resourceType
+ .getPluginConfigurationDefinition().getDefaultTemplate();
+ return (pluginConfigDefaultTemplate != null) ? pluginConfigDefaultTemplate
+ .createConfiguration()
+ : new Configuration();
+ }
+
/**
+ * @param name
+ * @param componentType
+ * @return
+ */
+ public static boolean isManagedComponent(ManagementView managementView,
+ String name, ComponentType componentType) {
+ boolean isDeployed = false;
+ if (name != null) {
+ try {
+ ManagedComponent component = getManagedComponent(componentType,
+ name);
+ if (component != null)
+ isDeployed = true;
+ } catch (Exception e) {
+ // Setting it to true to be safe than sorry, since there might
+ // be a component
+ // already deployed in the AS.
+ isDeployed = true;
+ }
+ }
+ return isDeployed;
+ }
+
+ /**
* Get the passed in {@link ManagedComponent}
*
* @return {@link ManagedComponent}
@@ -45,7 +156,7 @@
ManagementView mv = getManagementView(ps, true);
ManagedComponent mc = mv.getComponent(componentName, componentType);
-
+
return mc;
}
@@ -54,7 +165,8 @@
* type.
*
* @return Set of {@link ManagedComponent}s
- * @throws NamingException, Exception
+ * @throws NamingException
+ * , Exception
* @throws Exception
*/
public static Set<ManagedComponent> getManagedComponents(
@@ -71,7 +183,8 @@
* @param {@link ManagementView}
* @return
*/
- public static ManagementView getManagementView(ProfileService ps, boolean load) {
+ public static ManagementView getManagementView(ProfileService ps,
+ boolean load) {
ManagementView mv = ps.getViewManager();
if (load) {
mv.load();
@@ -96,7 +209,8 @@
/**
* @return {@link ProfileService}
- * @throws NamingException, Exception
+ * @throws NamingException
+ * , Exception
*/
public static ProfileService getProfileService() throws NamingException {
InitialContext ic = new InitialContext();
@@ -107,7 +221,8 @@
/**
* @return {@link File}
- * @throws NamingException, Exception
+ * @throws NamingException
+ * , Exception
*/
public static File getDeployDirectory() throws NamingException, Exception {
ProfileService ps = getProfileService();
@@ -141,51 +256,280 @@
File deployDir = warFile.getParentFile();
return deployDir;
}
-
- public static ManagedComponent getDQPManagementView() throws NamingException, Exception {
-
+
+ public static ManagedComponent getDQPManagementView()
+ throws NamingException, Exception {
+
return getManagedComponent(DQPTYPE, DQPNAME);
}
-
+
public static String stringValue(MetaValue v1) throws Exception {
if (v1 != null) {
MetaType type = v1.getMetaType();
if (type instanceof SimpleMetaType) {
- SimpleValue simple = (SimpleValue)v1;
+ SimpleValue simple = (SimpleValue) v1;
return simple.getValue().toString();
}
throw new Exception("Failed to convert value to string value");
}
return null;
- }
-
+ }
+
public static Boolean booleanValue(MetaValue v1) throws Exception {
if (v1 != null) {
MetaType type = v1.getMetaType();
if (type instanceof SimpleMetaType) {
- SimpleValue simple = (SimpleValue)v1;
+ SimpleValue simple = (SimpleValue) v1;
return Boolean.valueOf(simple.getValue().toString());
}
throw new Exception("Failed to convert value to boolean value");
}
return null;
- }
+ }
+
+ public static <T> T getSimpleValue(ManagedComponent mc, String prop,
+ Class<T> expectedType) {
+ ManagedProperty mp = mc.getProperty(prop);
+ if (mp != null) {
+ MetaType metaType = mp.getMetaType();
+ if (metaType.isSimple()) {
+ SimpleValue simpleValue = (SimpleValue) mp.getValue();
+ return expectedType.cast((simpleValue != null) ? simpleValue
+ .getValue() : null);
+ } else if (metaType.isEnum()) {
+ EnumValue enumValue = (EnumValue) mp.getValue();
+ return expectedType.cast((enumValue != null) ? enumValue
+ .getValue() : null);
+ }
+ throw new IllegalStateException(prop + " is not a simple type");
+ }
+ return null;
+ }
+
+ public static Map<String, PropertySimple> getCustomProperties(
+ Configuration pluginConfig) {
+ Map<String, PropertySimple> customProperties = new LinkedHashMap<String, PropertySimple>();
+ if (pluginConfig == null)
+ return customProperties;
+ PropertyMap customPropsMap = pluginConfig.getMap("custom-properties");
+ if (customPropsMap != null) {
+ Collection<Property> customProps = customPropsMap.getMap().values();
+ for (Property customProp : customProps) {
+ if (!(customProp instanceof PropertySimple)) {
+ LOG
+ .error("Custom property definitions in plugin configuration must be simple properties - property "
+ + customProp + " is not - ignoring...");
+ continue;
+ }
+ customProperties.put(customProp.getName(),
+ (PropertySimple) customProp);
+ }
+ }
+ return customProperties;
+ }
+
+ public static Configuration convertManagedObjectToConfiguration(
+ Map<String, ManagedProperty> managedProperties,
+ Map<String, PropertySimple> customProps, ResourceType resourceType) {
+ Configuration config = new Configuration();
+ ConfigurationDefinition configDef = resourceType
+ .getResourceConfigurationDefinition();
+ Map<String, PropertyDefinition> propDefs = configDef
+ .getPropertyDefinitions();
+ Set<String> propNames = managedProperties.keySet();
+ for (String propName : propNames) {
+ PropertyDefinition propertyDefinition = propDefs.get(propName);
+ ManagedProperty managedProperty = managedProperties.get(propName);
+ if (propertyDefinition == null) {
+ if (!managedProperty.hasViewUse(ViewUse.STATISTIC))
+ LOG
+ .debug(resourceType
+ + " does not define a property corresponding to ManagedProperty '"
+ + propName + "'.");
+ continue;
+ }
+ if (managedProperty == null) {
+ // This should never happen, but don't let it blow us up.
+ LOG.error("ManagedProperty '" + propName
+ + "' has a null value in the ManagedProperties Map.");
+ continue;
+ }
+ MetaValue metaValue = managedProperty.getValue();
+ if (managedProperty.isRemoved() || metaValue == null) {
+ // Don't even add a Property to the Configuration if the
+ // ManagedProperty is flagged as removed or has a
+ // null value.
+ continue;
+ }
+ PropertySimple customProp = customProps.get(propName);
+ PropertyAdapter<Property, PropertyDefinition> propertyAdapter = PropertyAdapterFactory
+ .getCustomPropertyAdapter(customProp);
+ if (propertyAdapter == null)
+ propertyAdapter = PropertyAdapterFactory
+ .getPropertyAdapter(metaValue);
+ if (propertyAdapter == null) {
+ LOG
+ .error("Unable to find a PropertyAdapter for ManagedProperty '"
+ + propName
+ + "' with MetaType ["
+ + metaValue.getMetaType()
+ + "] for ResourceType '"
+ + resourceType.getName() + "'.");
+ continue;
+ }
+ Property property = propertyAdapter.convertToProperty(metaValue,
+ propertyDefinition);
+ config.put(property);
+ }
+ return config;
+ }
+
+ public static void convertConfigurationToManagedProperties(
+ Map<String, ManagedProperty> managedProperties,
+ Configuration configuration, ResourceType resourceType) {
+ ConfigurationDefinition configDefinition = resourceType
+ .getResourceConfigurationDefinition();
+ for (ManagedProperty managedProperty : managedProperties.values()) {
+ String propertyName = managedProperty.getName();
+ PropertyDefinition propertyDefinition = configDefinition
+ .get(propertyName);
+ if (propertyDefinition==null){
+ //The managed property is not defined in the configuration
+ continue;
+ }
+ populateManagedPropertyFromProperty(managedProperty,
+ propertyDefinition, configuration);
+ }
+ return;
+ }
+
+ private static void populateManagedPropertyFromProperty(ManagedProperty managedProperty,
+ PropertyDefinition propertyDefinition, Configuration configuration) {
+ // If the ManagedProperty defines a default value, assume it's more
+ // definitive than any default value that may
+ // have been defined in the plugin descriptor, and update the
+ // PropertyDefinition to use that as its default
+ // value.
+ MetaValue defaultValue = managedProperty.getDefaultValue();
+ if (defaultValue != null)
+ updateDefaultValueOnPropertyDefinition(propertyDefinition,
+ defaultValue);
+ MetaValue metaValue = managedProperty.getValue();
+ PropertyAdapter propertyAdapter = null;
+ if (metaValue != null) {
+ LOG.trace("Populating existing MetaValue of type "
+ + metaValue.getMetaType() + " from RHQ property "
+ + propertyDefinition.getName() + " with definition " + propertyDefinition
+ + "...");
+ propertyAdapter = PropertyAdapterFactory
+ .getPropertyAdapter(metaValue);
+ propertyAdapter.populateMetaValueFromProperty(configuration.getSimple(propertyDefinition.getName()), metaValue,
+ propertyDefinition);
+ } else {
+ MetaType metaType = managedProperty.getMetaType();
+ if (propertyAdapter == null)
+ propertyAdapter = PropertyAdapterFactory
+ .getPropertyAdapter(metaType);
+ LOG.trace("Converting property " + propertyDefinition.getName() + " with definition "
+ + propertyDefinition + " to MetaValue of type " + metaType
+ + "...");
+ metaValue = propertyAdapter.convertToMetaValue(configuration.getSimple(propertyDefinition.getName()),
+ propertyDefinition, metaType);
+ managedProperty.setValue(metaValue);
+ }
+ }
+
+ private static void updateDefaultValueOnPropertyDefinition(
+ PropertyDefinition propertyDefinition,
+ @NotNull MetaValue defaultValue) {
+ if (!(propertyDefinition instanceof PropertyDefinitionSimple)) {
+ LOG
+ .debug("Cannot update default value on non-simple property definition "
+ + propertyDefinition
+ + "(default value is "
+ + defaultValue + ").");
+ return;
+ }
+ MetaType metaType = defaultValue.getMetaType();
+ if (!metaType.isSimple() && !metaType.isEnum()) {
+ LOG.debug("Cannot update default value on " + propertyDefinition
+ + ", because default value's type (" + metaType
+ + ") is not simple or enum.");
+ return;
+ }
+ PropertyDefinitionSimple propertyDefinitionSimple = (PropertyDefinitionSimple) propertyDefinition;
+ if (metaType.isSimple()) {
+ SimpleValue defaultSimpleValue = (SimpleValue) defaultValue;
+ Serializable value = defaultSimpleValue.getValue();
+ propertyDefinitionSimple.setDefaultValue((value != null) ? value
+ .toString() : null);
+ } else { // defaultValueMetaType.isEnum()
+ EnumValue defaultEnumValue = (EnumValue) defaultValue;
+ Serializable value = defaultEnumValue.getValue();
+ propertyDefinitionSimple.setDefaultValue((value != null) ? value
+ .toString() : null);
+ }
+ }
+
+ public static MetaType convertPropertyDefinitionToMetaType(
+ PropertyDefinition propDef) {
+ MetaType memberMetaType;
+ if (propDef instanceof PropertyDefinitionSimple) {
+ PropertySimpleType propSimpleType = ((PropertyDefinitionSimple) propDef)
+ .getType();
+ memberMetaType = convertPropertySimpleTypeToSimpleMetaType(propSimpleType);
+ } else if (propDef instanceof PropertyDefinitionList) {
+ // TODO (very low priority, since lists of lists are not going to be
+ // at all common)
+ memberMetaType = null;
+ } else if (propDef instanceof PropertyDefinitionMap) {
+ Map<String, PropertyDefinition> memberPropDefs = ((PropertyDefinitionMap) propDef)
+ .getPropertyDefinitions();
+ if (memberPropDefs.isEmpty())
+ throw new IllegalStateException(
+ "PropertyDefinitionMap doesn't contain any member PropertyDefinitions.");
+ // NOTE: We assume member prop defs are all of the same type, since
+ // for MapCompositeMetaTypes, they have to be.
+ PropertyDefinition mapMemberPropDef = memberPropDefs.values()
+ .iterator().next();
+ MetaType mapMemberMetaType = convertPropertyDefinitionToMetaType(mapMemberPropDef);
+ memberMetaType = new MapCompositeMetaType(mapMemberMetaType);
+ } else {
+ throw new IllegalStateException(
+ "List member PropertyDefinition has unknown type: "
+ + propDef.getClass().getName());
+ }
+ return memberMetaType;
+ }
- public static <T> T getSimpleValue(ManagedComponent mc, String prop, Class<T> expectedType) {
- ManagedProperty mp = mc.getProperty(prop);
- if (mp != null) {
- MetaType metaType = mp.getMetaType();
- if (metaType.isSimple()) {
- SimpleValue simpleValue = (SimpleValue)mp.getValue();
- return expectedType.cast((simpleValue != null) ? simpleValue.getValue() : null);
- }
- else if (metaType.isEnum()) {
- EnumValue enumValue = (EnumValue)mp.getValue();
- return expectedType.cast((enumValue != null) ? enumValue.getValue() : null);
- }
- throw new IllegalStateException(prop+ " is not a simple type");
- }
- return null;
- }
+ private static MetaType convertPropertySimpleTypeToSimpleMetaType(PropertySimpleType memberSimpleType)
+ {
+ MetaType memberMetaType;
+ Class memberClass;
+ switch (memberSimpleType)
+ {
+ case BOOLEAN:
+ memberClass = Boolean.class;
+ break;
+ case INTEGER:
+ memberClass = Integer.class;
+ break;
+ case LONG:
+ memberClass = Long.class;
+ break;
+ case FLOAT:
+ memberClass = Float.class;
+ break;
+ case DOUBLE:
+ memberClass = Double.class;
+ break;
+ default:
+ memberClass = String.class;
+ break;
+ }
+ memberMetaType = SimpleMetaType.resolve(memberClass.getName());
+ return memberMetaType;
+ }
+
}
Modified: trunk/console/src/main/resources/META-INF/rhq-plugin.xml
===================================================================
--- trunk/console/src/main/resources/META-INF/rhq-plugin.xml 2010-05-19 21:07:59 UTC (rev 2144)
+++ trunk/console/src/main/resources/META-INF/rhq-plugin.xml 2010-05-19 23:20:03 UTC (rev 2145)
@@ -25,6 +25,40 @@
'>
<!ENTITY translatorConfiguration '
+
+ <c:list-property name="translatorList" description="Properties for this translator"
+ readOnly="true">
+ <c:simple-property name="name" displayName="Name"
+ description="Name of the translator" />
+ <c:simple-property name="execution-factory-class" displayName="execution-factory-class"
+ description="Connector Class" />
+ <c:simple-property name="capabilities-class" displayName="capabilities-class"
+ description="The class to use to provide the Connector Capabilities" />
+ <c:simple-property name="override-capabilities-file" displayName="override-capabilities-file"
+ description="Property file that defines the override capability properties" />
+ <c:simple-property name="immutable" displayName="immutable"
+ description="Is Immutable, True if the source never changes." type="boolean" default="false" />
+ <c:simple-property name="exception-on-max-rows" displayName="exception-on-max-rows" type="boolean" default="false" />
+ description="Indicates if an Exception should be thrown if the specified value for Maximum Result Rows is exceeded; else no exception and no more than the maximum will be returned" default="false" />
+ <c:simple-property name="max-result-rows" displayName="max-result-rows"
+ description="Maximum Result Rows allowed" default="false" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions" type="boolean" default="false" />
+ <c:list-property name="translatorList" description="Properties for this translator"
+ readOnly="true">
+ <c:map-property name="translator-properties" >
+ <c:simple-property name="name" displayName="Name"
+ description="Name of this property" readOnly="true" />
+ <c:simple-property name="value" displayName="Value"
+ description="Value of this property" />
+ <c:simple-property name="description" displayName="Description"
+ description="Description of this property" />
+ </c:map-property>
+ </c:list-property>
+
+'>
+
+<!ENTITY accessTranslatorConfiguration '
<resource-configuration>
<c:list-property name="translatorList" description="Properties for this translator"
readOnly="true">
@@ -37,11 +71,9 @@
description="Description of this property" readOnly="true" />
</c:map-property>
</c:list-property>
- </resource-configuration>
+ </resource-configuration>
-
-'>
-
+'>
<!ENTITY datasourceAndConnectionFactoryOperations '
<operation name="flush" displayName="Flush"
@@ -1258,10 +1290,203 @@
</service>
<service name="Translators" description="Teiid Translators"
- class="TranslatorComponent" discovery="TranslatorDiscoveryComponent">
+ class="TranslatorComponent" discovery="TranslatorDiscoveryComponent"
+ createDeletePolicy="both" creationDataType="configuration">
- &translatorConfiguration;
+ <plugin-configuration>
+ <c:simple-property name="componentType" default="teiid"
+ readOnly="true" />
+ <c:simple-property name="componentSubtype"
+ default="translator" readOnly="true" />
+ <c:simple-property name="componentName" default="teiid"
+ readOnly="true" />
+ <c:simple-property name="template-name" default="translator"
+ readOnly="true" />
+ <c:simple-property name="resourceName" default="name">
+ <c:description>The name of the Resource configuration property
+ whose value should be used as the
+ Resource name when creating a new
+ Resource of this type.</c:description>
+ </c:simple-property>
+ </plugin-configuration>
+ <resource-configuration>
+ <c:simple-property name="name" displayName="Name"
+ description="Name of the translator" />
+ <c:simple-property name="execution-factory-class"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="immutable" displayName="immutable"
+ description="Is Immutable, True if the source never changes." type="boolean"
+ default="false" />
+ <c:simple-property name="exception-on-max-rows"
+ displayName="exception-on-max-rows"
+ description="Indicates if an Exception should be thrown if the
+ specified value for Maximum Result Rows is exceeded; else no
+ exception and no more than the maximum will be returned"
+ type="boolean" default="false" defaultValue="false" />
+ <c:simple-property name="max-result-rows"
+ displayName="max-result-rows" description="Maximum Result Rows allowed"
+ default="false" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="false" />
+ <c:list-property name="translatorList" readOnly="true" required="false"
+ displayName="Translator Specific Properties" description="List of translator specific properties">
+ <c:map-property name="translator-properties" >
+ <c:simple-property name="name" displayName="Name"
+ description="Name of this property" readOnly="true" />
+ <c:simple-property name="value" displayName="Value"
+ description="Value of this property" />
+ <c:simple-property name="description"
+ displayName="Description" description="Description of this property" />
+ </c:map-property>
+ </c:list-property>
+ <c:simple-property name="template-name" default="translator"
+ readOnly="true" />
+
+ <c:template name="Access" description="Translator for Access">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.access.AccessExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="DB2" description="Translator for DB2">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.db2.DB2ExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="Derby" description="Translator for Derby">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.derby.DerbyExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="H2" description="Translator for H2">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.h2.H2ExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="HSQL" description="Translator for HSQL">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.hsql.HsqlExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="MySQL" description="Translator for MySQL">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.mysql.MySQLExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="MySQL5" description="Translator for MySQL 5">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.mysql5.MySQL5ExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="Oracle" description="Translator for Oracle">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.oracle.OracleExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="SQLServer" description="Translator for SQLServer">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.oracle.SQLServerExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="Sybase" description="Translator for Sybase">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.jdbc.sybase.SybaseExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-jdbc-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="LDAP" description="Translator for LDAP">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.ldap.LDAPExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-ldap-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="SalesForce" description="Translator for SalesForce">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.salesforce.SalesForceExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-salesforce-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="XML" description="Translator for XML">
+ <c:simple-property name="execution-factory-class"
+ default="org.teiid.translator.xml.XMLExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-xml-${project.version}" readOnly="true" />
+ </c:template>
+ <c:template name="Loopback" description="Translator for Loopback">
+ <c:simple-property name="execution-factory-class"
+ default=">org.teiid.translator.loopback.LoopbackExecutionFactory"
+ displayName="execution-factory-class" description="Connector Class" />
+ <c:simple-property name="xa-capable" displayName="xa-capable"
+ description="True, if this connector supports XA Transactions"
+ type="boolean" default="true" />
+ <c:simple-property name="template-name"
+ default="translator-loopback-${project.version}" readOnly="true" />
+ </c:template>
+
+ </resource-configuration>
+
</service>
</server>
15 years, 11 months
teiid SVN: r2144 - trunk/connectors/translator-xml/src/main/resources/META-INF.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-19 17:07:59 -0400 (Wed, 19 May 2010)
New Revision: 2144
Modified:
trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml
Log:
TEIID-1077: fixing the data filetering in the XML files
Modified: trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml 2010-05-19 21:07:30 UTC (rev 2143)
+++ trunk/connectors/translator-xml/src/main/resources/META-INF/jboss-beans.xml 2010-05-19 21:07:59 UTC (rev 2144)
@@ -10,7 +10,7 @@
<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.Class">org.teiid.translator.xml.XMLExecutionFactory</parameter>
<parameter class="java.lang.String">${project.artifactId}-${project.version}</parameter>
<parameter class="java.lang.String">${project.description}</parameter>
</constructor>
15 years, 11 months
teiid SVN: r2143 - trunk/connectors/translator-xml.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-19 17:07:30 -0400 (Wed, 19 May 2010)
New Revision: 2143
Modified:
trunk/connectors/translator-xml/pom.xml
Log:
TEIID-1077: fixing the data filetering in the XML files
Modified: trunk/connectors/translator-xml/pom.xml
===================================================================
--- trunk/connectors/translator-xml/pom.xml 2010-05-19 20:01:26 UTC (rev 2142)
+++ trunk/connectors/translator-xml/pom.xml 2010-05-19 21:07:30 UTC (rev 2143)
@@ -1,60 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <parent>
- <artifactId>connectors</artifactId>
- <groupId>org.jboss.teiid</groupId>
- <version>7.0.0-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>translator-xml</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <name>XML Translator</name>
- <description>This translator consumes the XML documents from Web
- service and transforms the document into a relational structure.</description>
- <dependencies>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>connectors</artifactId>
+ <groupId>org.jboss.teiid</groupId>
+ <version>7.0.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>translator-xml</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <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-api</artifactId>
- <scope>provided</scope>
+ <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>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
</dependency>
<dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>jdom</groupId>
- <artifactId>jdom</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <scope>provided</scope>
- </dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
+ <groupId>jdom</groupId>
+ <artifactId>jdom</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>javax.resource</groupId>
<artifactId>connector-api</artifactId>
<scope>provided</scope>
</dependency>
-
- <dependency>
- <groupId>xom</groupId>
- <artifactId>xom</artifactId>
- <version>1.2</version>
- </dependency>
- <dependency>
- <groupId>nux</groupId>
- <artifactId>nux</artifactId>
- <version>1.6</version>
- </dependency>
+ <dependency>
+ <groupId>xom</groupId>
+ <artifactId>xom</artifactId>
+ <version>1.2</version>
+ </dependency>
+ <dependency>
+ <groupId>nux</groupId>
+ <artifactId>nux</artifactId>
+ <version>1.6</version>
+ </dependency>
</dependencies>
-
+
+ <build>
+ <outputDirectory>target/classes</outputDirectory>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>false</filtering>
+ <excludes>
+ <exclude>**/*.xml</exclude>
+ <exclude>**/*.properties</exclude>
+ </excludes>
+ </resource>
+ </resources>
+ </build>
+
</project>
15 years, 11 months
teiid SVN: r2142 - in trunk: connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming and 4 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-19 16:01:26 -0400 (Wed, 19 May 2010)
New Revision: 2142
Added:
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CartesienCriteriaGenerator.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CompositeExecution.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCartesianCriteriaGenerator.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestBaseStreamingExecution.java
trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestSoapExecution.java
trunk/connectors/translator-xml/src/test/resources/cis.vdb
Modified:
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.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/XMLExecutionFactory.java
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java
trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java
Log:
TEIID-1077: adding the fix for the single request spaning the multiple requests based on the cartesian join of the criteria
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CartesienCriteriaGenerator.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CartesienCriteriaGenerator.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CartesienCriteriaGenerator.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -0,0 +1,95 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+/**
+ * creates a Cartesian product of the Criteria descriptions based on their values.
+ */
+public class CartesienCriteriaGenerator {
+
+ public static List<List<CriteriaDesc>> generateCartesianCriteria(List<CriteriaDesc> params) {
+ List<List<CriteriaDesc>> cartesianProduct = new ArrayList<List<CriteriaDesc>>();
+
+ for (CriteriaDesc desc : params) {
+ createCartesionProduct(cartesianProduct, desc);
+ }
+
+ return cartesianProduct;
+ }
+
+ static void createCartesionProduct(List<List<CriteriaDesc>> cartesianProduct, CriteriaDesc desc) {
+
+ List<CriteriaDesc> firstLevel = new ArrayList<CriteriaDesc>();
+ if (desc.isUnlimited()) {
+ firstLevel.add(desc);
+ }
+ else {
+ for (Object value: desc.getValues()) {
+ CriteriaDesc cd = desc.cloneWithoutValues();
+ cd.setValue(0, value);
+ firstLevel.add(cd);
+ }
+ }
+
+ if (cartesianProduct.isEmpty()) {
+ for (CriteriaDesc cd:firstLevel) {
+ List<CriteriaDesc> secondLevel = new ArrayList<CriteriaDesc>();
+ secondLevel.add(cd);
+ cartesianProduct.add(secondLevel);
+ }
+ }
+ else {
+ List<List<CriteriaDesc>> newcartesianProduct = new ArrayList<List<CriteriaDesc>>();
+
+ for (CriteriaDesc cd:firstLevel) {
+ for (List<CriteriaDesc> secondLevel:cartesianProduct) {
+
+ List<CriteriaDesc> colnedSecondLevel = makeClone(secondLevel);
+ colnedSecondLevel.add(cd);
+ newcartesianProduct.add(colnedSecondLevel);
+ }
+ }
+ cartesianProduct.clear();
+ cartesianProduct.addAll(newcartesianProduct);
+ }
+ }
+
+ private static List<CriteriaDesc> makeClone(List<CriteriaDesc> original){
+ List<CriteriaDesc> clonedList = new ArrayList<CriteriaDesc>();
+
+ for (CriteriaDesc cd:original) {
+ CriteriaDesc clone = cd.cloneWithoutValues();
+ int i = 0;
+ for (Object value:cd.getValues()) {
+ clone.setValue(i++, value);
+ }
+ clonedList.add(clone);
+ }
+ return clonedList;
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CartesienCriteriaGenerator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CompositeExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CompositeExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CompositeExecution.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -0,0 +1,85 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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;
+
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
+
+public class CompositeExecution implements ResultSetExecution {
+
+ private boolean closed = false;
+ private List<ResultSetExecution> executions = new ArrayList<ResultSetExecution>();
+ private int currentExecutionNumber = 0;
+ private ResultSetExecution currentExecution;
+
+ public void addExecution(ResultSetExecution execution) {
+ if (this.closed) {
+ throw new IllegalStateException("This execution is already closed"); //$NON-NLS-1$
+ }
+ this.executions.add(execution);
+ }
+
+ @Override
+ public List<?> next() throws TranslatorException, DataNotAvailableException {
+ List result = null;
+ if (this.currentExecution != null) {
+ result = this.currentExecution.next();
+ }
+
+ if (result == null) {
+ if(this.currentExecutionNumber < this.executions.size()) {
+ this.currentExecution = this.executions.get(this.currentExecutionNumber++);
+ result = this.currentExecution.next();
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public void cancel() throws TranslatorException {
+ this.closed = true;
+ for(ResultSetExecution exec:this.executions) {
+ exec.cancel();
+ }
+ }
+
+ @Override
+ public void close() throws TranslatorException {
+ this.closed = true;
+ for(ResultSetExecution exec:this.executions) {
+ exec.close();
+ }
+ }
+
+ @Override
+ public void execute() throws TranslatorException {
+ this.closed = true;
+ for(ResultSetExecution exec:this.executions) {
+ exec.execute();
+ }
+ }
+
+}
Property changes on: trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/CompositeExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: 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 2010-05-18 20:59:49 UTC (rev 2141)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -31,7 +31,6 @@
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;
@@ -54,10 +53,9 @@
private int currentRow = 0;
- public FileResultSetExecution(Select query, XMLExecutionFactory executionFactory, FileConnection connection) throws TranslatorException {
+ public FileResultSetExecution(List<CriteriaDesc> requestParams, ExecutionInfo executionInfo, XMLExecutionFactory executionFactory, FileConnection connection) throws TranslatorException {
- QueryAnalyzer analyzer = new QueryAnalyzer(query);
- this.executionInfo = analyzer.getExecutionInfo();
+ this.executionInfo = executionInfo;
String tableName = this.executionInfo.getLocation();
if (tableName == null) {
@@ -67,14 +65,8 @@
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.executionInfo.setParameters(requestParams);
this.executionFactory = executionFactory;
this.streamProducer = new StreamingResultsProducer(this.executionInfo, this.executionFactory.getSaxFilterProvider());
}
Modified: 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 2010-05-18 20:59:49 UTC (rev 2141)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/QueryAnalyzer.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -63,7 +63,7 @@
return this.executionInfo;
}
- private void setGroupInfo() throws TranslatorException {
+ private void setGroupInfo() {
List<TableReference> fromItems = command.getFrom();
//Can only be one because we do not support joins
NamedTable group = (NamedTable) fromItems.get(0);
@@ -197,12 +197,12 @@
}
}
- private void setProperties() throws TranslatorException {
+ private void setProperties() {
this.executionInfo.setOtherProperties(table.getProperties());
}
- public List<CriteriaDesc[]> getRequestPerms() {
- return RequestGenerator.getRequests(this.executionInfo.getParameters());
+ public List<List<CriteriaDesc>> getRequestPerms() {
+ return CartesienCriteriaGenerator.generateCartesianCriteria(this.executionInfo.getParameters());
}
}
Modified: 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 2010-05-18 20:59:49 UTC (rev 2141)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -23,6 +23,7 @@
package org.teiid.translator.xml;
import java.sql.SQLXML;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -54,7 +55,7 @@
private String saxFilterProviderClass;
private String encoding = "ISO-8859-1"; //$NON-NLS-1$
- private Map<String, SQLXML> responses = new ConcurrentHashMap<String, SQLXML>();
+ private Map<String, List<SQLXML>> responses = new ConcurrentHashMap<String, List<SQLXML>>();
private boolean logRequestResponseDocs = false;
private String queryPreprocessorClass;
@@ -105,15 +106,20 @@
this.logRequestResponseDocs = logRequestResponseDocs;
}
- public SQLXML getResponse(String key) {
+ public List<SQLXML> getResponse(String key) {
return this.responses.get(key);
}
public void setResponse(String key, SQLXML xml) {
- this.responses.put(key, xml);
+ List<SQLXML> results = this.responses.get(key);
+ if (results == null) {
+ results = new ArrayList<SQLXML>();
+ this.responses.put(key, results);
+ }
+ results.add(xml);
}
- public SQLXML removeResponse(String key) {
+ public List<SQLXML> removeResponse(String key) {
return this.responses.remove(key);
}
@@ -147,19 +153,35 @@
command = preProcessor.preprocessQuery((Select)command, metadata, executionContext);
}
+ QueryAnalyzer analyzer = new QueryAnalyzer((Select)command);
+ ExecutionInfo executionInfo = analyzer.getExecutionInfo();
+ List<List<CriteriaDesc>> requestPerms = analyzer.getRequestPerms();
+
+ if (requestPerms.size() > 1) {
+ CompositeExecution compasiteExecution = new CompositeExecution();
+ for (List<CriteriaDesc> cds: requestPerms) {
+ compasiteExecution.addExecution(createExecution(cds, executionInfo, executionContext,connectionFactory));
+ }
+ return compasiteExecution;
+ }
+ return createExecution(requestPerms.get(0), executionInfo, executionContext,connectionFactory);
+ }
+
+ private ResultSetExecution createExecution(List<CriteriaDesc> cds, ExecutionInfo executionInfo, ExecutionContext executionContext, Object connectionFactory)
+ throws TranslatorException {
try {
ConnectionFactory cf = (ConnectionFactory)connectionFactory;
Connection connection = cf.getConnection();
if (connection instanceof FileConnection) {
- return new FileResultSetExecution((Select)command, this, (FileConnection)connection);
+ return new FileResultSetExecution(cds, executionInfo, this, (FileConnection)connection);
}
else if (connection instanceof Dispatch<?>) {
- return new BaseStreamingExecution((Select)command, metadata, executionContext, this, (Dispatch)connection);
+ return new BaseStreamingExecution(cds, executionInfo, executionContext, this, (Dispatch)connection);
}
- return null;
} catch (ResourceException e) {
throw new TranslatorException(e);
}
+ return null;
}
private RequestPreprocessor getRequestPreProcessor() throws TranslatorException {
Modified: 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 2010-05-18 20:59:49 UTC (rev 2141)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/streaming/BaseStreamingExecution.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -22,8 +22,10 @@
package org.teiid.translator.xml.streaming;
import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
+import java.net.URLEncoder;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.util.ArrayList;
@@ -40,11 +42,10 @@
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
+import org.teiid.core.TeiidRuntimeException;
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;
@@ -56,14 +57,14 @@
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$
+ private static final String DOT_SLASH = "./"; //$NON-NLS-1$
+ private static final String SLASH = "/"; //$NON-NLS-1$
+ 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$
@@ -75,47 +76,36 @@
private int resultIndex = 0;
// injected state
- protected RuntimeMetadata metadata;
protected ExecutionContext context;
protected XMLExecutionFactory executionFactory;
Dispatch<Source> dispatch;
ExecutionInfo executionInfo;
- private Source soapPayload;
+ Source soapPayload;
Iterator<Document> resultsIterator;
- public BaseStreamingExecution(Select command, RuntimeMetadata rtMetadata, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch<Source> dispatch) throws TranslatorException {
- this.metadata = rtMetadata;
+ public BaseStreamingExecution(List<CriteriaDesc> requestParams, ExecutionInfo executionInfo, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch<Source> dispatch) throws TranslatorException {
this.context = context;
this.executionFactory = executionFactory;
this.dispatch = dispatch;
-
- QueryAnalyzer analyzer = new QueryAnalyzer(command);
- this.executionInfo = analyzer.getExecutionInfo();
- List<CriteriaDesc[]> requestPerms = analyzer.getRequestPerms();
+ this.executionInfo = executionInfo;
- for (CriteriaDesc[] criteria : requestPerms) {
- processOutputXPathDescs(this.executionInfo.getRequestedColumns(), Arrays.asList(criteria));
- }
+ processOutputXPathDescs(this.executionInfo.getRequestedColumns(), requestParams);
- 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);
- }
- }
- }
+ if (checkIfRequestIsNeeded(this.executionInfo)) {
+ // Build a query String for http
+ String queryString = buildQueryString(requestParams);
+ 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) {
@@ -126,7 +116,7 @@
try {
// Build XML string for HTTP
- String xmlPayload = buildSimpleXML(requestPerms);
+ String xmlPayload = buildSimpleXML(requestParams);
if (xmlPayload != null) {
Map<String, Object> map = (Map)this.dispatch.getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
if (map == null) {
@@ -144,7 +134,7 @@
try {
// Build XML for SOAP
- String soapIn = buildSOAPInput(requestPerms);
+ String soapIn = buildSOAPInput(requestParams);
if(soapIn != null) {
this.soapPayload = new StreamSource(new StringReader(soapIn));
if (executionFactory.isLogRequestResponseDocs()) {
@@ -161,15 +151,16 @@
}
- private String buildQueryString(List<CriteriaDesc[]> parameters) throws TranslatorException{
+ 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$
- }
- }
+ try {
+ for(CriteriaDesc cd: parameters) {
+ String name = (cd.getInputXpath() == null || cd.getInputXpath().length() == 0) ? cd.getColumnName() : cd.getInputXpath();
+ sb.append(URLEncoder.encode(name, "UTF-8")).append("=").append(URLEncoder.encode(cd.getCurrentIndexValue(), "UTF-8")).append("&"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ }
+ } catch (UnsupportedEncodingException e) {
+ throw new TeiidRuntimeException(e);
+ }
return sb.toString();
}
@@ -234,9 +225,7 @@
@Override
public void execute() throws TranslatorException {
- ArrayList<Document> result = new ArrayList<Document>();
- result.add(getDocumentStream(this.executionInfo));
- this.resultsIterator = result.iterator();
+ this.resultsIterator = getDocumentStream(this.executionInfo).iterator();
}
/**
@@ -319,16 +308,18 @@
}
- private Document getDocumentStream(ExecutionInfo executionInfo) {
- Document document;
+ private List<Document> getDocumentStream(ExecutionInfo executionInfo) {
+ ArrayList<Document> docs = new ArrayList<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);
+ List<SQLXML> xmls = this.executionFactory.getResponse(responseid);
+ for (SQLXML xml:xmls) {
+ Assertion.isNotNull(xml);
+ docs.add(new DocumentImpl(xml, responseid));
+ }
} else {
// Not a join, but might still be cached.
// Not cached, so make the request
@@ -341,21 +332,17 @@
}
}
this.executionFactory.setResponse(this.context.getExecutionCountIdentifier(), responseBody);
- document = new DocumentImpl(responseBody, this.context.getExecutionCountIdentifier());
+ docs.add(new DocumentImpl(responseBody, this.context.getExecutionCountIdentifier()));
}
- return document;
+ return docs;
}
- 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));
+ private String buildSOAPInput(List<CriteriaDesc> params) throws TranslatorException {
List<CriteriaDesc> headerParams = new ArrayList<CriteriaDesc>();
List<CriteriaDesc> bodyParams = new ArrayList<CriteriaDesc>();
- for (CriteriaDesc desc : queryList) {
+ for (CriteriaDesc desc : params) {
if (desc.getInputXpath().startsWith(soapNSLabel+ ":" + soapHeader)) { //$NON-NLS-1$
headerParams.add(desc);
} else {
@@ -369,15 +356,13 @@
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$
+ if (inputParmsXPath == null || inputParmsXPath.equals(DOT_SLASH) || 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);
+ org.jdom.Document doc = builder.buildDocument(params, inputParmsXPath, namespacePrefixes);
if (hasDummy) {
// Since there is no real root - these should all be elements
Element element = (Element) doc.getRootElement().getChildren().get(0);
@@ -387,18 +372,18 @@
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);
-
+ private String buildSimpleXML(List<CriteriaDesc> params) throws TranslatorException{
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);
+
+ if(inputParmsXPath.equals(SLASH)) {
+ inputParmsXPath = "SLASH"; //$NON-NLS-1$
+ }
- org.jdom.Document inputXMLDoc = builder.buildDocument(Arrays.asList(parameters), inputParmsXPath,namespacePrefixes);
+ org.jdom.Document inputXMLDoc = builder.buildDocument(params, inputParmsXPath,namespacePrefixes);
XMLOutputter out = new XMLOutputter();
return out.outputString(inputXMLDoc).trim();
}
-
}
\ No newline at end of file
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCartesianCriteriaGenerator.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCartesianCriteriaGenerator.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCartesianCriteriaGenerator.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -0,0 +1,119 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.translator.xml;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.metadata.Column;
+
+
+@SuppressWarnings("nls")
+public class TestCartesianCriteriaGenerator {
+
+ @Test
+ public void testCartesian() throws Exception {
+ String[] validValues = {"ACE", "ADE", "BCE", "BDE", "ACF", "ADF", "BCF", "BDF"};
+
+ List<CriteriaDesc> list = new ArrayList<CriteriaDesc>();
+
+ Column c1 = new Column();
+ c1.setName("c1");
+
+ Column c2 = new Column();
+ c2.setName("c2");
+
+ Column c3 = new Column();
+ c3.setName("c3");
+
+ CriteriaDesc desc1 = new CriteriaDesc(c1, Arrays.asList(new String[] {"A", "B"}));
+ CriteriaDesc desc2 = new CriteriaDesc(c2, Arrays.asList(new String[] {"C", "D"}));
+ CriteriaDesc desc3 = new CriteriaDesc(c3, Arrays.asList(new String[] {"E", "F"}));
+ list.add(desc1);
+ list.add(desc2);
+ list.add(desc3);
+
+ List<List<CriteriaDesc>> catesianProduct = CartesienCriteriaGenerator.generateCartesianCriteria(list);
+
+ assertEquals(8, catesianProduct.size());
+ for (List<CriteriaDesc> cds:catesianProduct) {
+ assertEquals(3, cds.size());
+
+ String value = "";
+ for (CriteriaDesc cd:cds) {
+ List values = cd.getValues();
+ for (Object v:values) {
+ value = value+v.toString();
+ }
+ }
+ assertTrue(Arrays.asList(validValues).contains(value));
+ }
+ }
+
+
+ @Test
+ public void testCartesianWithMultiValue() throws Exception {
+ // the brackets represent the grouping, how they come as multi values.
+ String[] validValues = {"[A][C][EF]", "[A][D][EF]", "[B][C][EF]", "[B][D][EF]"};
+
+ List<CriteriaDesc> list = new ArrayList<CriteriaDesc>();
+
+ Column c1 = new Column();
+ c1.setName("c1");
+
+ Column c2 = new Column();
+ c2.setName("c2");
+
+ // make this column takes multi values
+ Column c3 = new Column();
+ c3.setName("c3");
+ c3.setProperty(CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_COLUMN_PROPERTY_NAME, CriteriaDesc.PARM_HAS_MULTIPLE_VALUES_MULTI_ELEMENT_NAME);
+
+ CriteriaDesc desc1 = new CriteriaDesc(c1, Arrays.asList(new String[] {"[A]", "[B]"}));
+ CriteriaDesc desc2 = new CriteriaDesc(c2, Arrays.asList(new String[] {"[C]", "[D]"}));
+ CriteriaDesc desc3 = new CriteriaDesc(c3, Arrays.asList(new String[] {"[E", "F]"}));
+ list.add(desc1);
+ list.add(desc2);
+ list.add(desc3);
+
+ List<List<CriteriaDesc>> catesianProduct = CartesienCriteriaGenerator.generateCartesianCriteria(list);
+
+ assertEquals(4, catesianProduct.size());
+ for (List<CriteriaDesc> cds:catesianProduct) {
+ assertEquals(3, cds.size());
+
+ String value = "";
+ for (CriteriaDesc cd:cds) {
+ List values = cd.getValues();
+ for (Object v:values) {
+ value = value+v.toString();
+ }
+ }
+ assertTrue(Arrays.asList(validValues).contains(value));
+ }
+ }
+
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/TestCartesianCriteriaGenerator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestBaseStreamingExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestBaseStreamingExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestBaseStreamingExecution.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -0,0 +1,83 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+package org.teiid.translator.xml.streaming;
+
+import java.util.Map;
+
+import javax.xml.ws.handler.MessageContext;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.language.Select;
+import org.teiid.metadata.index.VDBMetadataFactory;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.xml.XMLExecutionFactory;
+
+import com.metamatrix.cdk.api.TranslationUtility;
+
+import static org.junit.Assert.*;
+
+@SuppressWarnings("nls")
+public class TestBaseStreamingExecution {
+
+ @Test
+ public void testXMLGeneration() throws Exception {
+
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+
+ String vdbPath = UnitTestUtil.getTestDataPath()+"/cis.vdb";
+ TranslationUtility util = new TranslationUtility(VDBMetadataFactory.getVDBMetadata(vdbPath));
+
+ String sql = "SELECT FullCountryInfoSoapRequest.ResponseOut FROM FullCountryInfoSoapRequest WHERE FullCountryInfoSoapRequest.sCountryISOCode = 'US'";
+
+ ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ Mockito.stub(context.getExecutionCountIdentifier()).toReturn("1.1");
+
+ ResultSetExecution exec = factory.createResultSetExecution((Select)util.parseCommand(sql), context, util.createRuntimeMetadata(), TestSoapExecution.getCF());
+ assertTrue(exec instanceof BaseStreamingExecution);
+
+ BaseStreamingExecution bse = (BaseStreamingExecution)exec;
+ String soapRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tns:FullCountryInfo xmlns:tns=\"http://www.oorsprong.org/websamples.countryinfo\"><tns:sCountryISOCode>US</tns:sCountryISOCode></tns:FullCountryInfo>";
+ assertEquals(soapRequest, TestSoapExecution.getContent(bse.soapPayload));
+
+ Map<String, Object> map = (Map)bse.dispatch.getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS);
+
+ String xmlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"+
+ "<SLASH xmlns:mmn0=\"http://www.oorsprong.org/websamples.countryinfo\" xmlns:tns=\"http://www.oorsprong.org/websamples.countryinfo\"><tns:FullCountryInfo><tns:sCountryISOCode>US</tns:sCountryISOCode></tns:FullCountryInfo></SLASH>";
+ assertEquals(xmlRequest, map.get("xml"));
+
+ assertEquals("tns%3AFullCountryInfo%2Ftns%3AsCountryISOCode=US&", bse.dispatch.getRequestContext().get(MessageContext.QUERY_STRING));
+
+ // response doc; nothing gets generated for this guy..
+ sql = "SELECT * FROM FullCountryInfoSoapResponse WHERE FullCountryInfoSoapResponse.ResponseIn = '1.1'";
+ exec = factory.createResultSetExecution((Select)util.parseCommand(sql), context, util.createRuntimeMetadata(), TestSoapExecution.getCF());
+ assertTrue(exec instanceof BaseStreamingExecution);
+ bse = (BaseStreamingExecution)exec;
+ assertNull(bse.soapPayload);
+ assertNull(bse.dispatch.getRequestContext().get(MessageContext.INBOUND_MESSAGE_ATTACHMENTS));
+ assertNull(bse.dispatch.getRequestContext().get(MessageContext.QUERY_STRING));
+ }
+
+
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestBaseStreamingExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestSoapExecution.java
===================================================================
--- trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestSoapExecution.java (rev 0)
+++ trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestSoapExecution.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -0,0 +1,244 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with 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 static org.junit.Assert.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+
+import javax.resource.ResourceException;
+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.Dispatch;
+import javax.xml.ws.EndpointReference;
+import javax.xml.ws.Response;
+
+import org.junit.Test;
+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.xml.XMLExecutionFactory;
+
+import com.metamatrix.cdk.api.ConnectorHost;
+
+@SuppressWarnings("nls")
+public class TestSoapExecution {
+
+ public static BasicConnectionFactory getCF() {
+ BasicConnectionFactory cf = new BasicConnectionFactory() {
+ @Override
+ public BasicConnection getConnection() throws ResourceException {
+ String usResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<m:FullCountryInfoResponse xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:FullCountryInfoResult>"
+ + "<m:sISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">US</m:sISOCode>"
+ + "<m:sName xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">United States</m:sName>"
+ + "<m:sCapitalCity xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">Washington</m:sCapitalCity>"
+ + "<m:sPhoneCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">1</m:sPhoneCode>"
+ + "<m:sContinentCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">AM</m:sContinentCode>"
+ + "<m:sCurrencyISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">USD</m:sCurrencyISOCode>"
+ + "<m:sCountryFlag xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">http://www.oorsprong.org/WebSamples.CountryInfo/Images/USA.jpg</m:sCountryFlag>"
+ + "<m:Languages xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:tLanguage xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:sISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">eng</m:sISOCode>"
+ + "<m:sName xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">English</m:sName>"
+ + "</m:tLanguage>"
+ + "</m:Languages>"
+ + "</m:FullCountryInfoResult>"
+ + "</m:FullCountryInfoResponse>";
+
+ String jpResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<m:FullCountryInfoResponse xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:FullCountryInfoResult>"
+ + "<m:sISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">JP</m:sISOCode>"
+ + "<m:sName xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">Japan</m:sName>"
+ + "<m:sCapitalCity xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">Tokyo</m:sCapitalCity>"
+ + "<m:sPhoneCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">12</m:sPhoneCode>"
+ + "<m:sContinentCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">AM</m:sContinentCode>"
+ + "<m:sCurrencyISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">YEN</m:sCurrencyISOCode>"
+ + "<m:sCountryFlag xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">http://www.oorsprong.org/WebSamples.CountryInfo/Images/JAPAN.jpg</m:sCountryFlag>"
+ + "<m:Languages xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:tLanguage xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">"
+ + "<m:sISOCode xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">japanese</m:sISOCode>"
+ + "<m:sName xmlns:m=\"http://www.oorsprong.org/websamples.countryinfo\">Japan</m:sName>"
+ + "</m:tLanguage>"
+ + "</m:Languages>"
+ + "</m:FullCountryInfoResult>"
+ + "</m:FullCountryInfoResponse>";
+
+ HashMap<String, String> map = new HashMap<String, String>();
+ map.put("US", usResult);
+ map.put("JP", jpResult);
+ return new MyDispatch(map);
+ }
+
+ };
+ return cf;
+ }
+
+ //@Test
+ public void testSOAPSingleRequest() throws Exception {
+
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+
+ String vdbPath = UnitTestUtil.getTestDataPath()+"/cis.vdb";
+ ConnectorHost host = new ConnectorHost(factory, getCF(), vdbPath);
+ ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ Mockito.stub(context.getExecutionCountIdentifier()).toReturn("1.1");
+ host.setExecutionContext(context);
+
+ List result = host.executeCommand("SELECT FullCountryInfoSoapRequest.ResponseOut FROM FullCountryInfoSoapRequest WHERE FullCountryInfoSoapRequest.sCountryISOCode = 'US'", false);
+ assertEquals(1, result.size());
+ assertEquals("1.1", ((List)result.get(0)).get(0));
+
+ result = host.executeCommand("SELECT * FROM FullCountryInfoSoapResponse WHERE FullCountryInfoSoapResponse.ResponseIn = '1.1'");
+
+ List row = (List)result.get(0);
+ assertEquals("1.1", row.get(0));
+ assertEquals("/m:FullCountryInfoResponse[0]", row.get(1));
+ assertEquals("US", row.get(2));
+ assertEquals("United States", row.get(3));
+ }
+
+
+ @Test
+ public void testSOAPMultipleRequests() throws Exception {
+
+ XMLExecutionFactory factory = new XMLExecutionFactory();
+
+
+ String vdbPath = UnitTestUtil.getTestDataPath()+"/cis.vdb";
+ ConnectorHost host = new ConnectorHost(factory, getCF(), vdbPath);
+ ExecutionContext context = Mockito.mock(ExecutionContext.class);
+ Mockito.stub(context.getExecutionCountIdentifier()).toReturn("1.2");
+ host.setExecutionContext(context);
+
+ List result = host.executeCommand("SELECT FullCountryInfoSoapRequest.ResponseOut FROM FullCountryInfoSoapRequest WHERE FullCountryInfoSoapRequest.sCountryISOCode IN('US', 'JP')", false);
+ assertEquals(2, result.size());
+ assertEquals("1.2", ((List)result.get(0)).get(0));
+
+
+ result = host.executeCommand("SELECT * FROM FullCountryInfoSoapResponse WHERE FullCountryInfoSoapResponse.ResponseIn = '1.2'");
+ assertEquals(2, result.size());
+
+ List row = (List)result.get(0);
+ assertEquals("1.2", row.get(0));
+ assertEquals("/m:FullCountryInfoResponse[0]", row.get(1));
+ assertEquals("US", row.get(2));
+ assertEquals("United States", row.get(3));
+
+ row = (List)result.get(1);
+ assertEquals("1.2", row.get(0));
+ assertEquals("/m:FullCountryInfoResponse[0]", row.get(1));
+ assertEquals("JP", row.get(2));
+ assertEquals("Japan", row.get(3));
+ }
+
+
+ static class MyDispatch extends BasicConnection implements Dispatch<Source>{
+ private Map<String, Object> requestContext = new HashMap<String, Object>();
+ private Map<String, String> result;
+
+ public MyDispatch(Map<String, String> result) {
+ this.result = result;
+ }
+
+ @Override
+ public Source invoke(Source msg) {
+ String content = getContent(msg);
+ if (content.indexOf("<tns:sCountryISOCode>US</tns:sCountryISOCode>") != -1){
+ return new StreamSource(new StringReader(this.result.get("US")));
+ }
+ if (content.indexOf("<tns:sCountryISOCode>JP</tns:sCountryISOCode>") != -1){
+ return new StreamSource(new StringReader(this.result.get("JP")));
+ }
+ return null;
+ }
+
+ @Override
+ public Response<Source> invokeAsync(Source msg) {
+ return null;
+ }
+
+ @Override
+ public Future<?> invokeAsync(Source msg, AsyncHandler<Source> handler) {
+ return null;
+ }
+
+ @Override
+ public void invokeOneWay(Source msg) {
+ }
+
+ @Override
+ public Binding getBinding() {
+ return null;
+ }
+
+ @Override
+ public EndpointReference getEndpointReference() {
+ return null;
+ }
+
+ @Override
+ public <T extends EndpointReference> T getEndpointReference(Class<T> clazz) {
+ return null;
+ }
+
+ @Override
+ public Map<String, Object> getRequestContext() {
+ return this.requestContext;
+ }
+
+ @Override
+ public Map<String, Object> getResponseContext() {
+ return null;
+ }
+
+ @Override
+ public void close() throws ResourceException {
+ }
+ }
+
+ public static String getContent(Source msg) {
+ StreamSource ss = (StreamSource)msg;
+ BufferedReader reader = new BufferedReader(ss.getReader());
+ String line = null;
+ String content = "";
+ try {
+ while ((line = reader.readLine()) != null) {
+ content = content + line;
+ }
+ } catch (IOException e) {
+ }
+ return content;
+ }
+}
Property changes on: trunk/connectors/translator-xml/src/test/java/org/teiid/translator/xml/streaming/TestSoapExecution.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/connectors/translator-xml/src/test/resources/cis.vdb
===================================================================
(Binary files differ)
Property changes on: trunk/connectors/translator-xml/src/test/resources/cis.vdb
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java
===================================================================
--- trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java 2010-05-18 20:59:49 UTC (rev 2141)
+++ trunk/metadata/src/test/java/com/metamatrix/cdk/api/ConnectorHost.java 2010-05-19 20:01:26 UTC (rev 2142)
@@ -73,22 +73,30 @@
Command command = getCommand(query);
RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
- return executeCommand(command, runtimeMetadata);
+ return executeCommand(command, runtimeMetadata, true);
}
+ public List executeCommand(String query, boolean close) throws TranslatorException {
+ Command command = getCommand(query);
+ RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
+
+ return executeCommand(command, runtimeMetadata, close);
+ }
+
public List executeCommand(Command command) throws TranslatorException {
RuntimeMetadata runtimeMetadata = getRuntimeMetadata();
- return executeCommand(command, runtimeMetadata);
+ return executeCommand(command, runtimeMetadata, true);
}
- private List executeCommand(Command command, RuntimeMetadata runtimeMetadata)
+ private List executeCommand(Command command, RuntimeMetadata runtimeMetadata, boolean close)
throws TranslatorException {
Execution exec = connector.createExecution(command, this.executionContext, runtimeMetadata, this.connectionFactory);
exec.execute();
List results = readResultsFromExecution(exec);
- exec.close();
-
+ if (close) {
+ exec.close();
+ }
return results;
}
@@ -103,7 +111,7 @@
}
public int[] executeBatchedUpdates(Command[] commands, RuntimeMetadata runtimeMetadata) throws TranslatorException {
- List<List> result = executeCommand(new BatchedUpdates(Arrays.asList(commands)), runtimeMetadata);
+ List<List> result = executeCommand(new BatchedUpdates(Arrays.asList(commands)), runtimeMetadata, true);
int[] counts = new int[result.size()];
for (int i = 0; i < counts.length; i++) {
counts[i] = ((Integer)result.get(i).get(0)).intValue();
15 years, 11 months
teiid SVN: r2141 - trunk/documentation/reference/src/main/docbook/en-US/content.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-18 16:59:49 -0400 (Tue, 18 May 2010)
New Revision: 2141
Modified:
trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
Log:
TEIID-171 adding support for xmlagg
Modified: trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
===================================================================
--- trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml 2010-05-18 20:54:34 UTC (rev 2140)
+++ trunk/documentation/reference/src/main/docbook/en-US/content/sql_support.xml 2010-05-18 20:59:49 UTC (rev 2141)
@@ -220,6 +220,9 @@
<listitem>
<para>MAX(expression) – maximum value in a group (excluding null)</para>
</listitem>
+ <listitem>
+ <para>XMLAGG(xml expression <link linkend="orderby_clause">[ORDER BY ...]</link>) – xml concatination of all xml expressions in a group (excluding null)</para>
+ </listitem>
</itemizedlist>
<itemizedlist>
<para>Syntax Rules:
@@ -783,7 +786,7 @@
<sect2 id="orderby_clause">
<title>ORDER BY Clause</title>
<para>
- The ORDER BY clause specifies how the returned records from a SELECT should be sorted. The options are ASC (ascending) and DESC (descending).
+ The ORDER BY clause specifies how records should be sorted. The options are ASC (ascending) and DESC (descending).
</para>
<para>
Usage:
15 years, 11 months
teiid SVN: r2140 - in trunk/engine/src: main/java/org/teiid/query/function/aggregate and 15 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-18 16:54:34 -0400 (Tue, 18 May 2010)
New Revision: 2140
Added:
trunk/engine/src/main/java/org/teiid/query/function/aggregate/XMLAgg.java
trunk/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java
Removed:
trunk/engine/src/main/java/org/teiid/query/function/aggregate/NullFilter.java
trunk/engine/src/main/java/org/teiid/query/processor/relational/DuplicateFilter.java
trunk/engine/src/test/java/org/teiid/common/log/
Modified:
trunk/engine/src/main/java/org/teiid/common/buffer/TupleSource.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/Avg.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/Count.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/Max.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/Min.java
trunk/engine/src/main/java/org/teiid/query/function/aggregate/Sum.java
trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
trunk/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java
trunk/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java
trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java
trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
trunk/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java
trunk/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java
trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
trunk/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java
trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
trunk/engine/src/main/resources/org/teiid/query/i18n.properties
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/language/TestAggregateImpl.java
trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java
trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
trunk/engine/src/test/java/org/teiid/query/processor/relational/TestDuplicateFilter.java
trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
Log:
TEIID-171 adding support for xmlagg
Modified: trunk/engine/src/main/java/org/teiid/common/buffer/TupleSource.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/common/buffer/TupleSource.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/common/buffer/TupleSource.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -26,7 +26,7 @@
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
/**
@@ -40,7 +40,7 @@
* Returns the List of ElementSymbol describing the Tuple Source
* @return the List of elements describing the Tuple Source
*/
- List<SingleElementSymbol> getSchema();
+ List<? extends Expression> getSchema();
/**
* Returns the next tuple
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,6 +22,8 @@
package org.teiid.query.function.aggregate;
+import java.util.List;
+
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.TeiidComponentException;
@@ -34,8 +36,13 @@
* being aggregated, then addInput() is called for every row in the group, then
* getResult() is called to retrieve the result.
*/
-public interface AggregateFunction {
+public abstract class AggregateFunction {
+ private int expressionIndex = -1;
+
+ public void setExpressionIndex(int expressionIndex) {
+ this.expressionIndex = expressionIndex;
+ }
/**
* Called to initialize the function. In the future this may expand
@@ -43,21 +50,36 @@
* @param dataType Data type of element begin aggregated
* @param inputType
*/
- public abstract void initialize(Class dataType, Class inputType);
+ public void initialize(Class<?> dataType, Class<?> inputType) {}
/**
* Called to reset the state of the function.
*/
public abstract void reset();
+ public void addInput(List<?> tuple) throws TeiidComponentException, TeiidProcessingException {
+ if (expressionIndex == -1) {
+ addInputDirect(null, tuple);
+ return;
+ }
+ Object input = tuple.get(expressionIndex);
+ if (!filter(input)) {
+ addInputDirect(input, tuple);
+ }
+ }
+
+ boolean filter(Object value) {
+ return value == null;
+ }
+
/**
* Called for the element value in every row of a group.
* @param input Input value, may be null
+ * @param tuple
+ * @throws TeiidProcessingException
*/
- public abstract void addInput(Object input)
- throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException;
+ public abstract void addInputDirect(Object input, List<?> tuple) throws TeiidComponentException, TeiidProcessingException;
-
/**
* Called after all values have been processed to get the result.
* @return Result value
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/Avg.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/Avg.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/Avg.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -23,6 +23,7 @@
package org.teiid.query.function.aggregate;
import java.math.BigDecimal;
+import java.util.List;
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
@@ -45,16 +46,9 @@
private int count = 0;
/**
- * Constructor for Avg.
- */
- public Avg() {
- super();
- }
-
- /**
* @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
*/
- public void initialize(Class dataType, Class inputType) {
+ public void initialize(Class<?> dataType, Class<?> inputType) {
if (dataType.equals(DataTypeManager.DefaultDataClasses.BIG_DECIMAL)) {
this.accumulatorType = BIG_DECIMAL;
} else {
@@ -68,12 +62,12 @@
}
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object input)
+ public void addInputDirect(Object input, List<?> tuple)
throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
- super.addInput(input);
+ super.addInputDirect(input, tuple);
count++;
}
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,6 +22,8 @@
package org.teiid.query.function.aggregate;
+import java.util.List;
+
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.TeiidComponentException;
@@ -29,31 +31,23 @@
/**
*/
-public class ConstantFunction implements AggregateFunction {
+public class ConstantFunction extends AggregateFunction {
private Object value;
- /**
- * Constructor for NoFunction.
- */
- public ConstantFunction() {
- super();
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- }
-
public void reset() {
this.value = null;
}
+
+ @Override
+ boolean filter(Object input) {
+ return false;
+ }
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object input)
+ public void addInputDirect(Object input, List<?> tuple)
throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
value = input;
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/Count.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/Count.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/Count.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,34 +22,23 @@
package org.teiid.query.function.aggregate;
+import java.util.List;
+
/**
* Just a simple COUNT() implementation that counts every non-null row it sees.
*/
-public class Count implements AggregateFunction {
+public class Count extends AggregateFunction {
private int count = 0;
- /**
- * Constructor for Count.
- */
- public Count() {
- super();
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- }
-
public void reset() {
count = 0;
}
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object input) {
+ public void addInputDirect(Object input, List<?> tuple) {
count++;
}
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/Max.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/Max.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/Max.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,6 +22,8 @@
package org.teiid.query.function.aggregate;
+import java.util.List;
+
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.TeiidComponentException;
@@ -31,31 +33,18 @@
/**
*/
-public class Max implements AggregateFunction {
+public class Max extends AggregateFunction {
private Object maxValue;
- /**
- * Constructor for Min.
- */
- public Max() {
- super();
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- }
-
public void reset() {
maxValue = null;
}
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object value)
+ public void addInputDirect(Object value, List<?> tuple)
throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
if(maxValue == null) {
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/Min.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/Min.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/Min.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,6 +22,8 @@
package org.teiid.query.function.aggregate;
+import java.util.List;
+
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.core.TeiidComponentException;
@@ -31,31 +33,18 @@
/**
*/
-public class Min implements AggregateFunction {
+public class Min extends AggregateFunction {
private Object minValue;
- /**
- * Constructor for Min.
- */
- public Min() {
- super();
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- }
-
public void reset() {
minValue = null;
}
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object value)
+ public void addInputDirect(Object value, List<?> tuple)
throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
if(minValue == null) {
Deleted: trunk/engine/src/main/java/org/teiid/query/function/aggregate/NullFilter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/NullFilter.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/NullFilter.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -1,84 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.function.aggregate;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-
-
-
-/**
- */
-public class NullFilter implements AggregateFunction {
-
- private AggregateFunction proxy;
-
- /**
- * Constructor for NullFilter.
- */
- public NullFilter(AggregateFunction proxy) {
- super();
-
- this.proxy = proxy;
- }
-
- public AggregateFunction getProxy() {
- return proxy;
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- this.proxy.initialize(dataType, inputType);
- }
-
- public void reset() {
- this.proxy.reset();
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
- */
- public void addInput(Object input)
- throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
-
- if(input != null) {
- this.proxy.addInput(input);
- }
- }
-
- /**
- * @throws TeiidProcessingException
- * @see org.teiid.query.function.aggregate.AggregateFunction#getResult()
- */
- public Object getResult()
- throws TeiidComponentException, TeiidProcessingException {
-
- return this.proxy.getResult();
- }
-
-
-}
Modified: trunk/engine/src/main/java/org/teiid/query/function/aggregate/Sum.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/Sum.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/Sum.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -24,6 +24,7 @@
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.util.List;
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
@@ -36,7 +37,7 @@
* of a column. The type of the result varies depending on the type
* of the input {@see AggregateSymbol}
*/
-public class Sum implements AggregateFunction {
+public class Sum extends AggregateFunction {
// Various possible accumulators, depending on type
protected static final int LONG = 0;
@@ -49,12 +50,6 @@
private Object sum = null;
/**
- * Constructor for Sum.
- */
- public Sum() {
- }
-
- /**
* Allows subclasses to determine type of accumulator for the SUM.
* @return Type, as defined in constants
*/
@@ -65,7 +60,7 @@
/**
* @see org.teiid.query.function.aggregate.AggregateFunction#initialize(boolean, String)
*/
- public void initialize(Class dataType, Class inputType) {
+ public void initialize(Class<?> dataType, Class<?> inputType) {
if(dataType.equals(DataTypeManager.DefaultDataClasses.LONG)) {
this.accumulatorType = LONG;
@@ -87,9 +82,9 @@
}
/**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
*/
- public void addInput(Object input)
+ public void addInputDirect(Object input, List<?> tuple)
throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
if (this.sum == null) {
Added: trunk/engine/src/main/java/org/teiid/query/function/aggregate/XMLAgg.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/function/aggregate/XMLAgg.java (rev 0)
+++ trunk/engine/src/main/java/org/teiid/query/function/aggregate/XMLAgg.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.query.function.aggregate;
+
+import java.util.List;
+
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.XMLType;
+import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.util.CommandContext;
+
+/**
+ * Aggregates XML entries
+ */
+public class XMLAgg extends AggregateFunction {
+
+ private XMLType result;
+ private CommandContext context;
+
+ public XMLAgg(CommandContext context) {
+ this.context = context;
+ }
+
+ public void reset() {
+ result = null;
+ }
+
+ /**
+ * @throws TeiidProcessingException
+ * @throws TeiidComponentException
+ * @see org.teiid.query.function.aggregate.AggregateFunction#addInputDirect(Object, List)
+ */
+ public void addInputDirect(Object input, List<?> tuple) throws TeiidComponentException, TeiidProcessingException {
+ result = XMLSystemFunctions.xmlConcat(context, result, input);
+ }
+
+ /**
+ * @see org.teiid.query.function.aggregate.AggregateFunction#getResult()
+ */
+ public Object getResult() {
+ return result;
+ }
+
+}
Property changes on: trunk/engine/src/main/java/org/teiid/query/function/aggregate/XMLAgg.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -248,6 +248,9 @@
} else if(functionType.equals(SQLReservedWords.MAX)) {
int num = info.anonMaxCount++;
return "max" + (num == 0 ? "" : ""+num);//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ } else if(functionType.equals(SQLReservedWords.XMLAGG)) {
+ int num = info.anonMaxCount++;
+ return "xmlagg" + (num == 0 ? "" : ""+num);//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else {
Object[] params = new Object[] { functionType };
throw new ParseException(QueryPlugin.Util.getString("SQLParser.Unknown_agg_func", params)); //$NON-NLS-1$
Deleted: trunk/engine/src/main/java/org/teiid/query/processor/relational/DuplicateFilter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/DuplicateFilter.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/processor/relational/DuplicateFilter.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -1,154 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.query.processor.relational;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.api.exception.query.ExpressionEvaluationException;
-import org.teiid.api.exception.query.FunctionExecutionException;
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.TupleBuffer;
-import org.teiid.common.buffer.TupleSource;
-import org.teiid.common.buffer.BufferManager.TupleSourceType;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.function.aggregate.AggregateFunction;
-import org.teiid.query.processor.relational.SortUtility.Mode;
-import org.teiid.query.sql.lang.OrderBy;
-import org.teiid.query.sql.symbol.ElementSymbol;
-
-
-/**
- */
-public class DuplicateFilter implements AggregateFunction {
-
- // Initial setup - can be reused
- private AggregateFunction proxy;
- private BufferManager mgr;
- private String groupName;
-
- // Derived and static - can be reused
- private List elements;
- private List sortTypes;
-
- // Temporary state - should be reset
- private TupleBuffer collectionBuffer;
- private SortUtility sortUtility;
-
- /**
- * Constructor for DuplicateFilter.
- */
- public DuplicateFilter(AggregateFunction proxy, BufferManager mgr, String groupName) {
- super();
-
- this.proxy = proxy;
- this.mgr = mgr;
- this.groupName = groupName;
- }
-
- public List getElements() {
- return elements;
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
- */
- public void initialize(Class dataType, Class inputType) {
- this.proxy.initialize(dataType, inputType);
- // Set up schema
- ElementSymbol element = new ElementSymbol("val"); //$NON-NLS-1$
- element.setType(inputType);
- elements = new ArrayList();
- elements.add(element);
-
- sortTypes = new ArrayList();
- sortTypes.add(Boolean.valueOf(OrderBy.ASC));
- }
-
- public void reset() {
- this.proxy.reset();
- close();
- }
-
- private void close() {
- if (this.collectionBuffer != null) {
- collectionBuffer.remove();
- }
- this.collectionBuffer = null;
- this.sortUtility = null;
- }
-
- /**
- * @see org.teiid.query.function.aggregate.AggregateFunction#addInput(Object)
- */
- public void addInput(Object input)
- throws FunctionExecutionException, ExpressionEvaluationException, TeiidComponentException {
-
- if(collectionBuffer == null) {
- collectionBuffer = mgr.createTupleBuffer(elements, groupName, TupleSourceType.PROCESSOR);
- collectionBuffer.setForwardOnly(true);
- }
-
- List row = new ArrayList(1);
- row.add(input);
- this.collectionBuffer.addTuple(row);
- }
-
- /**
- * @throws TeiidProcessingException
- * @see org.teiid.query.function.aggregate.AggregateFunction#getResult()
- */
- public Object getResult()
- throws TeiidComponentException, TeiidProcessingException {
-
- if(collectionBuffer != null) {
- this.collectionBuffer.close();
-
- // Sort
- if (sortUtility == null) {
- sortUtility = new SortUtility(collectionBuffer.createIndexedTupleSource(), elements, sortTypes, Mode.DUP_REMOVE_SORT, mgr, groupName);
- }
- TupleBuffer sorted = sortUtility.sort();
- sorted.setForwardOnly(true);
- try {
- // Add all input to proxy
- TupleSource sortedSource = sorted.createIndexedTupleSource();
- while(true) {
- List tuple = sortedSource.nextTuple();
- if(tuple == null) {
- break;
- }
- this.proxy.addInput(tuple.get(0));
- }
- } finally {
- sorted.remove();
- }
-
- close();
- }
-
- // Return
- return this.proxy.getResult();
- }
-}
Modified: trunk/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -28,9 +28,9 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.ListIterator;
import java.util.Map;
-import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.client.plan.PlanNode;
import org.teiid.common.buffer.BlockedException;
import org.teiid.common.buffer.BufferManager;
@@ -47,12 +47,14 @@
import org.teiid.query.function.aggregate.Count;
import org.teiid.query.function.aggregate.Max;
import org.teiid.query.function.aggregate.Min;
-import org.teiid.query.function.aggregate.NullFilter;
import org.teiid.query.function.aggregate.Sum;
+import org.teiid.query.function.aggregate.XMLAgg;
import org.teiid.query.processor.ProcessorDataManager;
import org.teiid.query.processor.relational.SortUtility.Mode;
import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
import org.teiid.query.sql.symbol.Expression;
import org.teiid.query.sql.symbol.SingleElementSymbol;
import org.teiid.query.util.CommandContext;
@@ -68,7 +70,7 @@
// Collection phase
private int phase = COLLECTION;
private Map elementMap; // Map of incoming symbol to index in source elements
- private List collectedExpressions; // Collected Expressions
+ private List<Expression> collectedExpressions; // Collected Expressions
// Sort phase
private SortUtility sortUtility;
@@ -77,7 +79,6 @@
// Group phase
private AggregateFunction[] functions;
- private int[] aggProjectionIndexes;
private List lastRow;
private List currentGroupTuple;
@@ -140,33 +141,28 @@
// List should contain all grouping columns / expressions as we need those for sorting
if(this.sortElements != null) {
- this.collectedExpressions = new ArrayList(this.sortElements.size() + getElements().size());
+ this.collectedExpressions = new ArrayList<Expression>(this.sortElements.size() + getElements().size());
this.collectedExpressions.addAll(sortElements);
} else {
- this.collectedExpressions = new ArrayList(getElements().size());
+ this.collectedExpressions = new ArrayList<Expression>(getElements().size());
}
// Construct aggregate function state accumulators
functions = new AggregateFunction[getElements().size()];
- aggProjectionIndexes = new int[getElements().size()];
- Arrays.fill(aggProjectionIndexes, -1);
for(int i=0; i<getElements().size(); i++) {
SingleElementSymbol symbol = (SingleElementSymbol)getElements().get(i);
Class<?> outputType = symbol.getType();
Class<?> inputType = symbol.getType();
if(symbol instanceof AggregateSymbol) {
AggregateSymbol aggSymbol = (AggregateSymbol) symbol;
-
+
if(aggSymbol.getExpression() == null) {
functions[i] = new Count();
} else {
- int index = this.collectedExpressions.indexOf(aggSymbol.getExpression());
- if(index == -1) {
- index = this.collectedExpressions.size();
- this.collectedExpressions.add(aggSymbol.getExpression());
- }
- aggProjectionIndexes[i] = index;
- String function = aggSymbol.getAggregateFunction();
+ Expression ex = aggSymbol.getExpression();
+ inputType = ex.getType();
+ int index = collectExpression(ex);
+ String function = aggSymbol.getAggregateFunction();
if(function.equals(SQLReservedWords.COUNT)) {
functions[i] = new Count();
} else if(function.equals(SQLReservedWords.SUM)) {
@@ -175,24 +171,59 @@
functions[i] = new Avg();
} else if(function.equals(SQLReservedWords.MIN)) {
functions[i] = new Min();
+ } else if (function.equals(SQLReservedWords.MAX)){
+ functions[i] = new Max();
} else {
- functions[i] = new Max();
+ functions[i] = new XMLAgg(context);
}
if(aggSymbol.isDistinct() && !function.equals(SQLReservedWords.MIN) && !function.equals(SQLReservedWords.MAX)) {
- functions[i] = new DuplicateFilter(functions[i], getBufferManager(), getConnectionID());
- }
-
- functions[i] = new NullFilter(functions[i]);
- inputType = aggSymbol.getExpression().getType();
+ SortingFilter filter = new SortingFilter(functions[i], getBufferManager(), getConnectionID(), true);
+ ElementSymbol element = new ElementSymbol("val"); //$NON-NLS-1$
+ element.setType(inputType);
+ filter.setElements(Arrays.asList(element));
+ filter.setSortElements(filter.getElements());
+ functions[i] = filter;
+ } else if (aggSymbol.getOrderBy() != null) { //handle the xmlagg case
+ int[] orderIndecies = new int[aggSymbol.getOrderBy().getOrderByItems().size()];
+ List<Boolean> aggSortTypes = new ArrayList<Boolean>(orderIndecies.length);
+ List<ElementSymbol> schema = new ArrayList<ElementSymbol>(orderIndecies.length + 1);
+ ElementSymbol element = new ElementSymbol("val"); //$NON-NLS-1$
+ element.setType(inputType);
+ schema.add(element);
+ for (ListIterator<OrderByItem> iterator = aggSymbol.getOrderBy().getOrderByItems().listIterator(); iterator.hasNext();) {
+ OrderByItem item = iterator.next();
+ orderIndecies[iterator.previousIndex()] = collectExpression(item.getSymbol());
+ aggSortTypes.add(item.isAscending());
+ element = new ElementSymbol(String.valueOf(iterator.previousIndex()));
+ element.setType(inputType);
+ schema.add(element);
+ }
+ SortingFilter filter = new SortingFilter(functions[i], getBufferManager(), getConnectionID(), false);
+ filter.setSortTypes(aggSortTypes);
+ filter.setIndecies(orderIndecies);
+ filter.setElements(schema);
+ filter.setSortElements(schema.subList(1, schema.size()));
+ functions[i] = filter;
+ }
+ functions[i].setExpressionIndex(index);
}
} else {
functions[i] = new ConstantFunction();
- aggProjectionIndexes[i] = this.collectedExpressions.indexOf(symbol);
+ functions[i].setExpressionIndex(this.collectedExpressions.indexOf(symbol));
}
functions[i].initialize(outputType, inputType);
}
- }
+ }
+
+ private int collectExpression(Expression ex) {
+ int index = this.collectedExpressions.indexOf(ex);
+ if(index == -1) {
+ index = this.collectedExpressions.size();
+ this.collectedExpressions.add(ex);
+ }
+ return index;
+ }
AggregateFunction[] getFunctions() {
return functions;
@@ -246,7 +277,7 @@
for(int col = 0; col<columns; col++) {
// The following call may throw BlockedException, but all state to this point
// is saved in class variables so we can start over on building this tuple
- Object value = new Evaluator(elementMap, getDataManager(), getContext()).evaluate((Expression) collectedExpressions.get(col), tuple);
+ Object value = new Evaluator(elementMap, getDataManager(), getContext()).evaluate((Expression)collectedExpressions.get(col), tuple);
exprTuple.add(value);
}
sourceRow++;
@@ -263,7 +294,7 @@
}
@Override
- public List<SingleElementSymbol> getSchema() {
+ public List<Expression> getSchema() {
return collectedExpressions;
}
@@ -382,14 +413,10 @@
}
private void updateAggregates(List tuple)
- throws TeiidComponentException, ExpressionEvaluationException {
+ throws TeiidComponentException, TeiidProcessingException {
for(int i=0; i<functions.length; i++) {
- Object value = null;
- if(aggProjectionIndexes[i] != -1) {
- value = tuple.get(aggProjectionIndexes[i]);
- }
- functions[i].addInput(value);
+ functions[i].addInput(tuple);
}
}
Modified: trunk/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -42,6 +42,7 @@
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.symbol.Expression;
import org.teiid.query.sql.symbol.SingleElementSymbol;
@@ -87,7 +88,7 @@
private Mode mode;
private BufferManager bufferManager;
private String groupName;
- private List<SingleElementSymbol> schema;
+ private List<? extends Expression> schema;
private int schemaSize;
private ListNestedSortComparator comparator;
@@ -120,7 +121,7 @@
sortTypes = Collections.nCopies(sortElements.size(), OrderBy.ASC);
} else if (sortElements.size() < schema.size()) {
sortElements = new ArrayList(sortElements);
- List<SingleElementSymbol> toAdd = new ArrayList<SingleElementSymbol>(schema);
+ List<Expression> toAdd = new ArrayList<Expression>(schema);
toAdd.removeAll(sortElements);
sortElements.addAll(toAdd);
sortTypes = new ArrayList<Boolean>(sortTypes);
Copied: trunk/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java (from rev 2137, trunk/engine/src/main/java/org/teiid/query/processor/relational/DuplicateFilter.java)
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java (rev 0)
+++ trunk/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -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.query.processor.relational;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.common.buffer.BufferManager.TupleSourceType;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.function.aggregate.AggregateFunction;
+import org.teiid.query.processor.relational.SortUtility.Mode;
+
+/**
+ */
+public class SortingFilter extends AggregateFunction {
+
+ private static final int[] NO_INDECIES = new int[0];
+ // Initial setup - can be reused
+ private AggregateFunction proxy;
+ private BufferManager mgr;
+ private String groupName;
+ private boolean removeDuplicates;
+
+ // Derived and static - can be reused
+ private List elements;
+ private List sortTypes;
+ private List sortElements;
+
+ private int[] indecies = NO_INDECIES;
+
+ // Temporary state - should be reset
+ private TupleBuffer collectionBuffer;
+ private SortUtility sortUtility;
+
+ /**
+ * Constructor for DuplicateFilter.
+ */
+ public SortingFilter(AggregateFunction proxy, BufferManager mgr, String groupName, boolean removeDuplicates) {
+ super();
+
+ this.proxy = proxy;
+ this.mgr = mgr;
+ this.groupName = groupName;
+ this.removeDuplicates = removeDuplicates;
+ }
+
+ public List getElements() {
+ return elements;
+ }
+
+ public void setElements(List elements) {
+ this.elements = elements;
+ }
+
+ public void setSortTypes(List sortTypes) {
+ this.sortTypes = sortTypes;
+ }
+
+ public void setIndecies(int[] indecies) {
+ this.indecies = indecies;
+ }
+
+ public void setSortElements(List sortElements) {
+ this.sortElements = sortElements;
+ }
+
+ /**
+ * @see org.teiid.query.function.aggregate.AggregateFunction#initialize(String, Class)
+ */
+ public void initialize(Class<?> dataType, Class<?> inputType) {
+ this.proxy.initialize(dataType, inputType);
+ }
+
+ public void reset() {
+ this.proxy.reset();
+ close();
+ }
+
+ private void close() {
+ if (this.collectionBuffer != null) {
+ collectionBuffer.remove();
+ }
+ this.collectionBuffer = null;
+ this.sortUtility = null;
+ }
+
+ @Override
+ public void addInputDirect(Object input, List<?> tuple)
+ throws FunctionExecutionException, ExpressionEvaluationException,
+ TeiidComponentException, TeiidProcessingException {
+ if(collectionBuffer == null) {
+ collectionBuffer = mgr.createTupleBuffer(elements, groupName, TupleSourceType.PROCESSOR);
+ collectionBuffer.setForwardOnly(true);
+ }
+ List<Object> row = new ArrayList<Object>(1 + indecies.length);
+ row.add(input);
+ for (int i = 0; i < indecies.length; i++) {
+ row.add(tuple.get(indecies[i]));
+ }
+ this.collectionBuffer.addTuple(row);
+ }
+
+ /**
+ * @throws TeiidProcessingException
+ * @see org.teiid.query.function.aggregate.AggregateFunction#getResult()
+ */
+ public Object getResult()
+ throws TeiidComponentException, TeiidProcessingException {
+
+ if(collectionBuffer != null) {
+ this.collectionBuffer.close();
+
+ // Sort
+ if (sortUtility == null) {
+ sortUtility = new SortUtility(collectionBuffer.createIndexedTupleSource(), sortElements, sortTypes, removeDuplicates?Mode.DUP_REMOVE_SORT:Mode.SORT, mgr, groupName);
+ }
+ TupleBuffer sorted = sortUtility.sort();
+ sorted.setForwardOnly(true);
+ try {
+ // Add all input to proxy
+ TupleSource sortedSource = sorted.createIndexedTupleSource();
+ while(true) {
+ List tuple = sortedSource.nextTuple();
+ if(tuple == null) {
+ break;
+ }
+ this.proxy.addInputDirect(tuple.get(0), null);
+ }
+ } finally {
+ sorted.remove();
+ }
+
+ close();
+ }
+
+ // Return
+ return this.proxy.getResult();
+ }
+}
Modified: trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -627,13 +627,11 @@
if (! type.equals(DataTypeManager.DefaultDataTypes.STRING) &&
! type.equals(DataTypeManager.DefaultDataTypes.CLOB)) {
- if(!(expr instanceof AggregateSymbol) &&
- ResolverUtil.canImplicitlyConvert(type, DataTypeManager.DefaultDataTypes.STRING)) {
+ if(ResolverUtil.canImplicitlyConvert(type, DataTypeManager.DefaultDataTypes.STRING)) {
result = ResolverUtil.convertExpression(expr, type, DataTypeManager.DefaultDataTypes.STRING, metadata);
- } else if (!(expr instanceof AggregateSymbol) &&
- ResolverUtil.canImplicitlyConvert(type, DataTypeManager.DefaultDataTypes.CLOB)){
+ } else if (ResolverUtil.canImplicitlyConvert(type, DataTypeManager.DefaultDataTypes.CLOB)){
result = ResolverUtil.convertExpression(expr, type, DataTypeManager.DefaultDataTypes.CLOB, metadata);
@@ -666,9 +664,6 @@
Expression value = (Expression) valIter.next();
setDesiredType(value, exprType, scrit);
if(! value.getType().equals(exprType)) {
- if(value instanceof AggregateSymbol) {
- throw new QueryResolverException(ErrorMessageKeys.RESOLVER_0031, QueryPlugin.Util.getString(ErrorMessageKeys.RESOLVER_0031, scrit));
- }
// try to apply cast
String valTypeName = DataTypeManager.getDataTypeName(value.getType());
if(ResolverUtil.canImplicitlyConvert(valTypeName, exprTypeName)) {
Modified: trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -759,7 +759,7 @@
* @param query
* @throws TeiidComponentException, MetaMatrixProcessingException
*/
- public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException, TeiidProcessingException{
+ public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException {
final OrderBy orderBy = queryCommand.getOrderBy();
if (orderBy == null) {
return queryCommand;
Modified: trunk/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -132,6 +132,7 @@
public void visit(AggregateSymbol obj) {
preVisitVisitor(obj);
visitNode(obj.getExpression());
+ visitNode(obj.getOrderBy());
postVisitVisitor(obj);
}
public void visit(AliasSymbol obj) {
Modified: trunk/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -33,6 +33,7 @@
import org.teiid.language.SQLReservedWords;
import org.teiid.query.QueryPlugin;
import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.OrderBy;
import org.teiid.query.util.ErrorMessageKeys;
@@ -59,21 +60,23 @@
private String aggregate;
private boolean distinct;
+ private OrderBy orderBy;
- private static final Class COUNT_TYPE = DataTypeManager.getDataTypeClass(DataTypeManager.DefaultDataTypes.INTEGER);
- private static final Set AGGREGATE_FUNCTIONS;
- private static final Map SUM_TYPES;
- private static final Map AVG_TYPES;
+ private static final Class<Integer> COUNT_TYPE = DataTypeManager.DefaultDataClasses.INTEGER;
+ private static final Set<String> AGGREGATE_FUNCTIONS;
+ private static final Map<Class<?>, Class<?>> SUM_TYPES;
+ private static final Map<Class<?>, Class<?>> AVG_TYPES;
static {
- AGGREGATE_FUNCTIONS = new HashSet();
+ AGGREGATE_FUNCTIONS = new HashSet<String>();
AGGREGATE_FUNCTIONS.add(SQLReservedWords.COUNT);
AGGREGATE_FUNCTIONS.add(SQLReservedWords.SUM);
AGGREGATE_FUNCTIONS.add(SQLReservedWords.AVG);
AGGREGATE_FUNCTIONS.add(SQLReservedWords.MIN);
AGGREGATE_FUNCTIONS.add(SQLReservedWords.MAX);
+ AGGREGATE_FUNCTIONS.add(SQLReservedWords.XMLAGG);
- SUM_TYPES = new HashMap();
+ SUM_TYPES = new HashMap<Class<?>, Class<?>>();
SUM_TYPES.put(DataTypeManager.DefaultDataClasses.BYTE, DataTypeManager.DefaultDataClasses.LONG);
SUM_TYPES.put(DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.LONG);
SUM_TYPES.put(DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.LONG);
@@ -83,7 +86,7 @@
SUM_TYPES.put(DataTypeManager.DefaultDataClasses.DOUBLE, DataTypeManager.DefaultDataClasses.DOUBLE);
SUM_TYPES.put(DataTypeManager.DefaultDataClasses.BIG_DECIMAL, DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
- AVG_TYPES = new HashMap();
+ AVG_TYPES = new HashMap<Class<?>, Class<?>>();
AVG_TYPES.put(DataTypeManager.DefaultDataClasses.BYTE, DataTypeManager.DefaultDataClasses.DOUBLE);
AVG_TYPES.put(DataTypeManager.DefaultDataClasses.SHORT, DataTypeManager.DefaultDataClasses.DOUBLE);
AVG_TYPES.put(DataTypeManager.DefaultDataClasses.INTEGER, DataTypeManager.DefaultDataClasses.DOUBLE);
@@ -167,15 +170,15 @@
* type of the contained expression
* @return Type of the symbol
*/
- public Class getType() {
+ public Class<?> getType() {
if(this.aggregate.equals(SQLReservedWords.COUNT)) {
return COUNT_TYPE;
} else if(this.aggregate.equals(SQLReservedWords.SUM) ) {
- Class expressionType = this.getExpression().getType();
- return (Class) SUM_TYPES.get(expressionType);
+ Class<?> expressionType = this.getExpression().getType();
+ return SUM_TYPES.get(expressionType);
} else if (this.aggregate.equals(SQLReservedWords.AVG)) {
- Class expressionType = this.getExpression().getType();
- return (Class) AVG_TYPES.get(expressionType);
+ Class<?> expressionType = this.getExpression().getType();
+ return AVG_TYPES.get(expressionType);
} else {
return this.getExpression().getType();
}
@@ -184,6 +187,14 @@
public void acceptVisitor(LanguageVisitor visitor) {
visitor.visit(this);
}
+
+ public OrderBy getOrderBy() {
+ return orderBy;
+ }
+
+ public void setOrderBy(OrderBy orderBy) {
+ this.orderBy = orderBy;
+ }
/**
* Return a deep copy of this object
@@ -195,7 +206,9 @@
} else {
copy = new AggregateSymbol(getName(), getCanonical(), getAggregateFunction(), isDistinct(), null);
}
-
+ if (orderBy != null) {
+ copy.setOrderBy(orderBy.clone());
+ }
return copy;
}
@@ -219,7 +232,8 @@
return this.aggregate.equals(other.aggregate)
&& this.distinct == other.distinct
- && EquivalenceUtil.areEqual(this.getExpression(), other.getExpression());
+ && EquivalenceUtil.areEqual(this.getExpression(), other.getExpression())
+ && EquivalenceUtil.areEqual(this.getOrderBy(), other.getOrderBy());
}
}
Modified: trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -1104,6 +1104,11 @@
} else {
parts.add(registerNode(obj.getExpression()));
}
+
+ if (obj.getOrderBy() != null) {
+ parts.add(SPACE);
+ parts.add(registerNode(obj.getOrderBy()));
+ }
parts.add(")"); //$NON-NLS-1$
}
Modified: trunk/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -74,6 +74,8 @@
String aggregateFunction = obj.getAggregateFunction();
if((aggregateFunction.equals(SQLReservedWords.SUM) || aggregateFunction.equals(SQLReservedWords.AVG)) && obj.getType() == null) {
handleValidationError(QueryPlugin.Util.getString(ErrorMessageKeys.VALIDATOR_0041, new Object[] {aggregateFunction, obj}), obj);
+ } else if (aggregateFunction.equals(SQLReservedWords.XMLAGG) && obj.getType() != DataTypeManager.DefaultDataClasses.XML) {
+ handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_xml", new Object[] {aggregateFunction, obj}), obj);
}
if((obj.isDistinct() || aggregateFunction.equals(SQLReservedWords.MIN) || aggregateFunction.equals(SQLReservedWords.MAX)) && DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(aggExp.getType()))) {
handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_comparable", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
Modified: trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
===================================================================
--- trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj 2010-05-18 20:54:34 UTC (rev 2140)
@@ -1688,6 +1688,7 @@
AggregateSymbol agg = null;
boolean isDistinct = false;
Expression expression = null;
+ OrderBy orderBy = null;
}
{
// Things that can be aliased
@@ -1704,13 +1705,23 @@
functionToken = <SUM> |
functionToken = <AVG> |
functionToken = <MIN> |
- functionToken = <MAX>
+ functionToken = <MAX>
)
<LPAREN>
[ <DISTINCT> {isDistinct=true;} ]
expression = expression(info)
<RPAREN>
- )
+ )
+ |
+ (
+ functionToken = <XMLAGG>
+ <LPAREN>
+ expression = expression(info)
+ [
+ orderBy = orderby(info)
+ ]
+ <RPAREN>
+ )
)
{
if(! info.aggregatesAllowed) {
@@ -1726,7 +1737,7 @@
// COUNT(*)
agg = new AggregateSymbol(name, func, false, null);
}
-
+ agg.setOrderBy(orderBy);
return agg;
}
}
Modified: trunk/engine/src/main/resources/org/teiid/query/i18n.properties
===================================================================
--- trunk/engine/src/main/resources/org/teiid/query/i18n.properties 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/main/resources/org/teiid/query/i18n.properties 2010-05-18 20:54:34 UTC (rev 2140)
@@ -300,6 +300,7 @@
ERR.015.012.0040 = Aggregate expression has unknown data type: {0}
ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {1}
AggregateValidationVisitor.non_comparable = The aggregate function {0} cannot be used with non-comparable expressions: {1}
+AggregateValidationVisitor.non_xml = The XMLAGG aggregate function {0} requires an expression of type XML: {1}
ERR.015.012.0042 = Cross join may not have criteria: {0}
ERR.015.012.0043 = Join must have criteria declared in the ON clause: {0}
ERR.015.012.0045 = Elements in this join criteria are not from a group involved in the join: {0}
@@ -768,7 +769,7 @@
SystemSource.xpath_description=Evaluate the XPath expression against a document
SystemSource.xpath_param1=Source document
SystemSource.xpath_param2=XPath expression
-SystemSource.xpath_param2=Namespaces
+SystemSource.xpath_param3=Namespaces
SystemSource.xpathvalue_result=Single result
SystemSource.xpath_result=XPath result
SystemSource.xsltransform_description=Transform the document with the given stylesheet.
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/language/TestAggregateImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/language/TestAggregateImpl.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/language/TestAggregateImpl.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -47,7 +47,7 @@
functionName,
distinct,
new Constant(new Integer(value)));
- return (AggregateFunction)TstLanguageBridgeFactory.factory.translate(symbol);
+ return TstLanguageBridgeFactory.factory.translate(symbol);
}
Modified: trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/test/java/org/teiid/query/parser/TestParser.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -37,6 +37,7 @@
import org.teiid.client.metadata.ParameterInfo;
import org.teiid.core.TeiidException;
import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.SQLReservedWords;
import org.teiid.query.sql.lang.BetweenCriteria;
import org.teiid.query.sql.lang.Command;
import org.teiid.query.sql.lang.CompareCriteria;
@@ -6732,5 +6733,14 @@
f.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem(), new XMLNamespaces.NamespaceItem("x", "http://foo"))));
helpTestExpression("xmlforest(xmlnamespaces(no default, 'http://foo' as x), a as \"table\")", "XMLFOREST(XMLNAMESPACES(NO DEFAULT, 'http://foo' AS x), a AS \"table\")", f);
}
+
+ @Test public void testXmlAggWithOrderBy() throws Exception {
+ String sql = "SELECT xmlAgg(1 order by e2)"; //$NON-NLS-1$
+ AggregateSymbol as = new AggregateSymbol("foo", SQLReservedWords.XMLAGG, false, new Constant(1));
+ as.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("e2"))));
+ Query query = new Query();
+ query.setSelect(new Select(Arrays.asList(as)));
+ helpTest(sql, "SELECT XMLAGG(1 ORDER BY e2)", query);
+ }
}
Modified: trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -171,5 +171,35 @@
helpProcess(plan, dataManager, expected);
}
+
+ @Test public void testXmlAgg() {
+ String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)))) from pm1.g1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"a\" e2=\"3\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"0\"></x></parent>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
+
+ @Test public void testXmlAggOrderBy() {
+ String sql = "SELECT xmlelement(parent, xmlAgg(xmlelement(x, xmlattributes(e1, e2)) order by e2)) from pm1.g1"; //$NON-NLS-1$
+
+ List[] expected = new List[] {
+ Arrays.asList("<parent><x e1=\"a\" e2=\"0\"></x><x e1=\"a\" e2=\"0\"></x><x e2=\"1\"></x><x e1=\"c\" e2=\"1\"></x><x e1=\"b\" e2=\"2\"></x><x e1=\"a\" e2=\"3\"></x></parent>"),
+ };
+
+ FakeDataManager dataManager = new FakeDataManager();
+ sampleData1(dataManager);
+
+ ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+
+ helpProcess(plan, dataManager, expected);
+ }
}
Modified: trunk/engine/src/test/java/org/teiid/query/processor/relational/TestDuplicateFilter.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestDuplicateFilter.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/test/java/org/teiid/query/processor/relational/TestDuplicateFilter.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -22,13 +22,16 @@
package org.teiid.query.processor.relational;
+import java.util.Arrays;
+
import org.teiid.common.buffer.BufferManager;
import org.teiid.common.buffer.BufferManagerFactory;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.types.DataTypeManager;
import org.teiid.query.function.aggregate.Count;
-import org.teiid.query.processor.relational.DuplicateFilter;
+import org.teiid.query.processor.relational.SortingFilter;
+import org.teiid.query.sql.symbol.ElementSymbol;
import junit.framework.TestCase;
@@ -48,13 +51,17 @@
public void helpTestDuplicateFilter(Object[] input, Class dataType, int expected) throws TeiidComponentException, TeiidProcessingException {
BufferManager mgr = BufferManagerFactory.getStandaloneBufferManager();
- DuplicateFilter filter = new DuplicateFilter(new Count(), mgr, "test"); //$NON-NLS-1$
+ SortingFilter filter = new SortingFilter(new Count(), mgr, "test", true); //$NON-NLS-1$
filter.initialize(dataType, dataType);
+ ElementSymbol element = new ElementSymbol("val"); //$NON-NLS-1$
+ element.setType(dataType);
+ filter.setElements(Arrays.asList(element));
+ filter.setSortElements(filter.getElements());
filter.reset();
// Add inputs
for(int i=0; i<input.length; i++) {
- filter.addInput(input[i]);
+ filter.addInputDirect(input[i], null);
}
Integer actual = (Integer) filter.getResult();
Modified: trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java 2010-05-18 17:06:12 UTC (rev 2139)
+++ trunk/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java 2010-05-18 20:54:34 UTC (rev 2140)
@@ -44,13 +44,9 @@
import org.teiid.query.function.FunctionDescriptor;
import org.teiid.query.function.SystemFunctionManager;
import org.teiid.query.function.aggregate.AggregateFunction;
-import org.teiid.query.function.aggregate.NullFilter;
import org.teiid.query.processor.FakeDataManager;
import org.teiid.query.processor.FakeTupleSource;
import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.processor.relational.DuplicateFilter;
-import org.teiid.query.processor.relational.GroupingNode;
-import org.teiid.query.processor.relational.RelationalNode;
import org.teiid.query.sql.symbol.AggregateSymbol;
import org.teiid.query.sql.symbol.Constant;
import org.teiid.query.sql.symbol.ElementSymbol;
@@ -177,7 +173,7 @@
//ensure that the distinct input type is correct
AggregateFunction[] functions = node.getFunctions();
AggregateFunction countDist = functions[5];
- DuplicateFilter dup = (DuplicateFilter)((NullFilter)countDist).getProxy();
+ SortingFilter dup = (SortingFilter)countDist;
assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, ((ElementSymbol)dup.getElements().get(0)).getType());
}
15 years, 11 months
teiid SVN: r2139 - trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-18 13:06:12 -0400 (Tue, 18 May 2010)
New Revision: 2139
Modified:
trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.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/XMLProcedureExecution.java
Log:
TEIID-1077: adding the connector-ws module, ensuring that logging is conditional for debug, and removing the wrapping used in the rpc style invocation - this means that RPC modeled procedures are no longer valid. The user must pass a document as the parameter to the procedure call.
Modified: 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 2010-05-18 16:05:10 UTC (rev 2138)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/FileResultSetExecution.java 2010-05-18 17:06:12 UTC (rev 2139)
@@ -127,14 +127,13 @@
return null;
}
- private List<String> getXPaths() {
+ private List<String> getXPaths() throws TranslatorException {
XPathSplitter splitter = new XPathSplitter();
try {
return splitter.split(this.executionInfo.getTableXPath());
} catch (InvalidPathException e) {
- e.printStackTrace();
+ throw new TranslatorException(e);
}
- return null;
}
private Document getDocumentStream(final File xmlFile, int fileNumber) {
Modified: 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 2010-05-18 16:05:10 UTC (rev 2138)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLExecutionFactory.java 2010-05-18 17:06:12 UTC (rev 2139)
@@ -37,6 +37,9 @@
import org.teiid.language.Call;
import org.teiid.language.QueryExpression;
import org.teiid.language.Select;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
import org.teiid.metadata.RuntimeMetadata;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.ExecutionFactory;
@@ -95,7 +98,7 @@
@TranslatorProperty(description="Log the XML request/response documents", display="Log Request/Response Documents")
public boolean isLogRequestResponseDocs() {
- return logRequestResponseDocs;
+ return logRequestResponseDocs && LogManager.isMessageToBeRecorded(LogConstants.CTX_CONNECTOR, MessageLevel.DETAIL);
}
public void setLogRequestResponseDocs(Boolean logRequestResponseDocs) {
Modified: 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 2010-05-18 16:05:10 UTC (rev 2138)
+++ trunk/connectors/translator-xml/src/main/java/org/teiid/translator/xml/XMLProcedureExecution.java 2010-05-18 17:06:12 UTC (rev 2139)
@@ -23,6 +23,7 @@
package org.teiid.translator.xml;
import java.io.StringReader;
+import java.sql.Clob;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.util.Arrays;
@@ -34,7 +35,6 @@
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;
@@ -43,7 +43,6 @@
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.
@@ -61,7 +60,7 @@
/**
* @param env
*/
- public XMLProcedureExecution(Call procedure, RuntimeMetadata metadata, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch dispatch) {
+ public XMLProcedureExecution(Call procedure, RuntimeMetadata metadata, ExecutionContext context, XMLExecutionFactory executionFactory, Dispatch<Source> dispatch) {
this.metadata = metadata;
this.context = context;
this.procedure = procedure;
@@ -81,7 +80,12 @@
}
// execute the request
- Source result = this.dispatch.invoke(buildRequest(procedureName, procedure.getArguments()));
+ Source result;
+ try {
+ result = this.dispatch.invoke(buildRequest(procedure.getArguments()));
+ } catch (SQLException e1) {
+ throw new TranslatorException(e1);
+ }
this.returnValue = this.executionFactory.convertToXMLType(result);
if (executionFactory.isLogRequestResponseDocs()) {
try {
@@ -92,27 +96,24 @@
}
- 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());
- }
+ Source buildRequest(List<Argument> args) throws SQLException, TranslatorException{
+ if (args.size() != 1) {
+ throw new TranslatorException("Expected a single argument to the procedure execution"); //$NON-NLS-1$
}
-
- sb.append("</tns1:").append(procedureName).append(">");
-
- return new StreamSource(new StringReader(sb.toString()));
+ Argument arg = args.get(0);
+ Object value = arg.getArgumentValue().getValue();
+ if (value instanceof SQLXML) {
+ return new StreamSource(((SQLXML)value).getCharacterStream());
+ } else if (value instanceof Clob) {
+ return new StreamSource(((Clob)value).getCharacterStream());
+ } else if (value != null) {
+ return new StreamSource(new StringReader(value.toString()));
+ } else {
+ //TODO: work around for JBoss native
+ return new StreamSource(new StringReader("<none/>")); //$NON-NLS-1$
+ }
}
-
-
@Override
public List<?> next() throws TranslatorException, DataNotAvailableException {
if (!returnedResult) {
15 years, 11 months
teiid SVN: r2138 - in trunk/connectors/connector-ws/src/main: rar/META-INF and 1 other directory.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-18 12:05:10 -0400 (Tue, 18 May 2010)
New Revision: 2138
Modified:
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/META-INF/ra.xml
Log:
TEIID-1077: adding the connector-ws module
Modified: 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 2010-05-18 15:20:27 UTC (rev 2137)
+++ trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSConnection.java 2010-05-18 16:05:10 UTC (rev 2138)
@@ -1,6 +1,8 @@
package org.teiid.resource.adapter.ws;
import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -23,31 +25,31 @@
import javax.xml.ws.soap.SOAPBinding;
import org.jboss.ws.core.ConfigProvider;
-import org.teiid.resource.adapter.ws.WSManagedConnectionFactory.ParameterType;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.resource.adapter.ws.WSManagedConnectionFactory.InvocationType;
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 Dispatch<Source> delegate;
private WSManagedConnectionFactory mcf;
public WSConnection(WSManagedConnectionFactory mcf) {
- if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
- this.delegate = createSOAPDispatch(mcf);
+ this.mcf = mcf;
+ if (mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
+ this.delegate = createHTTPDispatch("GET"); //$NON-NLS-1$
}
- 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("POST"); //$NON-NLS-1$
+ } else {
+ this.delegate = createSOAPDispatch();
}
- 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){
+ private Dispatch<Source> createHTTPDispatch(String requestMethod){
Service svc = Service.create(svcQname);
svc.addPort(portQName, HTTPBinding.HTTP_BINDING, mcf.getEndPoint());
@@ -69,12 +71,12 @@
return dispatch;
}
- private Dispatch createSOAPDispatch(WSManagedConnectionFactory mcf) {
+ private Dispatch<Source> createSOAPDispatch() {
Service svc = Service.create(svcQname);
- svc.addPort(portQName, SOAPBinding.SOAP11HTTP_BINDING, mcf.getEndPoint());
+ svc.addPort(portQName, mcf.getInvocationType() == InvocationType.SOAP11 ? SOAPBinding.SOAP11HTTP_BINDING : SOAPBinding.SOAP12HTTP_BINDING, mcf.getEndPoint());
- Dispatch dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
+ Dispatch<Source> dispatch = svc.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
if (mcf.getSecurityType() == WSManagedConnectionFactory.SecurityType.WSSecurity) {
// JBoss WS-Security
((ConfigProvider) this.delegate).setSecurityConfig(mcf.getWsSecurityConfigURL());
@@ -118,36 +120,42 @@
}
if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.HTTP_GET) {
- if (isXMLInput() && xmlPayload != null) {
- getRequestContext().put(MessageContext.QUERY_STRING, this.mcf.getXMLParamName()+"="+xmlPayload); //$NON-NLS-1$
+ if (this.mcf.getXMLParamName() != null) {
+ if (xmlPayload != null) {
+ try {
+ getRequestContext().put(MessageContext.QUERY_STRING, this.mcf.getXMLParamName()+"="+URLEncoder.encode(xmlPayload, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LogManager.logDetail(LogConstants.CTX_CONNECTOR, "XML Param specified, but no request document was generated."); //$NON-NLS-1$
+ }
}
- else {
- if (getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY) == null) {
+ 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);
+ 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) {
+ if (xmlPayload != null) {
msg = new StreamSource(new StringReader(xmlPayload));
}
else {
msg = null;
}
}
- else if (this.mcf.getInvocationType() == WSManagedConnectionFactory.InvocationType.SOAP) {
+ else {
// 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) {
@@ -157,22 +165,18 @@
if (msg == null) {
// JBoss Native DispatchImpl throws exception when the source is null
- msg = new StreamSource(new StringReader("<none/>"));
+ msg = new StreamSource(new StringReader("<none/>")); //$NON-NLS-1$
}
- return (Source)delegate.invoke(msg);
+ return 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) {
+ public Future invokeAsync(Source msg, AsyncHandler<Source> handler) {
return delegate.invokeAsync(msg, handler);
}
@Override
- public Response invokeAsync(Source msg) {
+ public Response<Source> invokeAsync(Source msg) {
return delegate.invokeAsync(msg);
}
Modified: 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 2010-05-18 15:20:27 UTC (rev 2137)
+++ trunk/connectors/connector-ws/src/main/java/org/teiid/resource/adapter/ws/WSManagedConnectionFactory.java 2010-05-18 16:05:10 UTC (rev 2138)
@@ -22,7 +22,6 @@
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;
@@ -32,21 +31,18 @@
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};
+ public enum InvocationType {HTTP_GET, HTTP_POST, SOAP11, SOAP12};
+ public enum SecurityType {None,HTTPBasic,WSSecurity}
- private String invocationType;
+ private String invocationType = InvocationType.SOAP12.name();
private String endPoint;
- private String securityType; // None, HTTPBasic, WS-Security
+ private String securityType = SecurityType.None.name(); // 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;
-
+ private String xmlParamName;
@Override
public Object createConnectionFactory() throws ResourceException {
@@ -58,12 +54,10 @@
};
}
-
public InvocationType getInvocationType() {
return InvocationType.valueOf(invocationType);
}
-
public void setInvocationType(String invocationType) {
this.invocationType = invocationType;
}
@@ -116,19 +110,11 @@
this.wsSecurityConfigName = wsSecurityConfigName;
}
- public ParameterType getParameterMethod() {
- return ParameterType.valueOf(parameterMethod);
- }
-
- public void setParameterMethod(String parameterMethod) {
- this.parameterMethod = parameterMethod;
- }
-
public String getXMLParamName() {
- return xMLParamName;
+ return xmlParamName;
}
public void setXMLParamName(String xMLParamName) {
- this.xMLParamName = xMLParamName;
+ this.xmlParamName = xMLParamName;
}
}
Modified: trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml
===================================================================
--- trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml 2010-05-18 15:20:27 UTC (rev 2137)
+++ trunk/connectors/connector-ws/src/main/rar/META-INF/ra.xml 2010-05-18 16:05:10 UTC (rev 2138)
@@ -41,10 +41,10 @@
<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>
+ <description>{$display:"Invocation Type",$description:"Service Invocation type (HTTP or SOAP)", $allowed="HTTP_GET, HTTP_POST, SOAP11, SOAP12", $required="true", $defaultValue="SOAP12"}</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-value>SOAP12</config-property-value>
</config-property>
<config-property>
@@ -85,18 +85,11 @@
</config-property>
<config-property>
- <description>{$display:"XML Parameter Name", $description="only required for the HTTP with XML based request"}</description>
+ <description>{$display:"XML Parameter Name", $description="only required for HTTP_GET with an 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>
15 years, 11 months
teiid SVN: r2137 - in trunk: adminshell/src/main/java/org/teiid/adminshell and 11 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2010-05-18 11:20:27 -0400 (Tue, 18 May 2010)
New Revision: 2137
Added:
trunk/adminshell/src/test/java/org/
trunk/adminshell/src/test/java/org/teiid/
trunk/adminshell/src/test/java/org/teiid/adminshell/
trunk/adminshell/src/test/java/org/teiid/adminshell/TestAdminShell.java
trunk/adminshell/src/test/resources/foo/
trunk/adminshell/src/test/resources/foo/bar.txt
Modified:
trunk/adminshell/pom.xml
trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java
trunk/connectors/connector-ws/
trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java
Log:
TEIID-1088 ensuring that the vdb filename is set as just the filename and not the full path.
Modified: trunk/adminshell/pom.xml
===================================================================
--- trunk/adminshell/pom.xml 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/adminshell/pom.xml 2010-05-18 15:20:27 UTC (rev 2137)
@@ -18,6 +18,11 @@
</dependency>
<dependency>
<groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
<artifactId>teiid-client</artifactId>
<scope>provided</scope>
</dependency>
@@ -31,6 +36,12 @@
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.4</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>jline</groupId>
<artifactId>jline</artifactId>
Modified: trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
===================================================================
--- trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -27,8 +27,6 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import java.io.Reader;
-import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;
@@ -50,7 +48,6 @@
import org.teiid.adminapi.WorkerPoolStatistics;
import org.teiid.adminshell.Help.Doc;
import org.teiid.core.util.ObjectConverterUtil;
-import org.teiid.core.util.ReaderInputStream;
/**
@@ -62,7 +59,7 @@
static Properties p;
private static int connectionCount = 1;
- private static Admin internalAdmin;
+ static Admin internalAdmin;
private static String currentName;
private static HashMap<String, Admin> connections = new HashMap<String, Admin>();
private static Help help = new Help(AdminShell.class);
@@ -332,14 +329,6 @@
}
private static void writeFile(String deployedName, String fileName,
- Reader contents) throws IOException, AdminProcessingException {
- if (contents == null) {
- throw new AdminProcessingException(deployedName + " not found for exporting");
- }
- ObjectConverterUtil.write(new ReaderInputStream(contents, Charset.forName("UTF-8")), fileName); //$NON-NLS-1$
- }
-
- private static void writeFile(String deployedName, String fileName,
InputStream contents) throws IOException, AdminProcessingException {
if (contents == null) {
throw new AdminProcessingException(deployedName + " not found for exporting");
@@ -359,9 +348,10 @@
@Doc(text = "Deploy a VDB from file")
public static void deployVDB(
@Doc(text = "file name") String vdbFile) throws AdminException, FileNotFoundException {
- FileInputStream fis = new FileInputStream(new File(vdbFile));
+ File file = new File(vdbFile);
+ FileInputStream fis = new FileInputStream(file);
try {
- getAdmin().deployVDB(vdbFile, fis);
+ getAdmin().deployVDB(file.getName(), fis);
} finally {
try {
fis.close();
Added: trunk/adminshell/src/test/java/org/teiid/adminshell/TestAdminShell.java
===================================================================
--- trunk/adminshell/src/test/java/org/teiid/adminshell/TestAdminShell.java (rev 0)
+++ trunk/adminshell/src/test/java/org/teiid/adminshell/TestAdminShell.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -0,0 +1,55 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General public static
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General public static License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General public static
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.adminshell;
+
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.adminapi.Admin;
+import org.teiid.adminapi.AdminException;
+import org.teiid.core.util.UnitTestUtil;
+
+@SuppressWarnings("nls")
+public class TestAdminShell {
+
+ private static Admin admin;
+
+ @BeforeClass public static void oneTimeSetUp() {
+ admin = Mockito.mock(Admin.class);
+ AdminShell.internalAdmin = admin;
+ }
+
+ @AfterClass public static void oneTimeTearDown() {
+ AdminShell.internalAdmin = null;
+ }
+
+ @Test public void testDeployVDB() throws AdminException, FileNotFoundException {
+ AdminShell.deployVDB(UnitTestUtil.getTestDataPath() + "/foo/bar.txt");
+ Mockito.verify(admin).deployVDB(Mockito.eq("bar.txt"), (InputStream)Mockito.anyObject());
+ }
+
+}
Property changes on: trunk/adminshell/src/test/java/org/teiid/adminshell/TestAdminShell.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/adminshell/src/test/resources/foo/bar.txt
===================================================================
Property changes on: trunk/adminshell/src/test/resources/foo/bar.txt
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
===================================================================
--- trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -61,7 +61,6 @@
import org.teiid.core.types.InputStreamFactory;
import org.teiid.core.types.JDBCSQLTypeInfo;
import org.teiid.core.util.ArgCheck;
-import org.teiid.core.util.ObjectConverterUtil;
import org.teiid.core.util.SqlUtil;
import org.teiid.core.util.TimestampWithTimezone;
@@ -294,11 +293,7 @@
}
public void setBinaryStream(int parameterIndex, java.io.InputStream in, int length) throws SQLException {
- try {
- setObject(parameterIndex, new SerialBlob(ObjectConverterUtil.convertToByteArray(in, length)));
- } catch (IOException e) {
- throw TeiidSQLException.create(e);
- }
+ setBlob(parameterIndex, in);
}
/**
@@ -330,7 +325,7 @@
* @throws SQLException, if parameter type/datatype do not match
*/
public void setByte(int parameterIndex, byte value) throws SQLException {
- setObject(parameterIndex, new Byte(value));
+ setObject(parameterIndex, Byte.valueOf(value));
}
/**
@@ -416,7 +411,7 @@
* @throws SQLException, if parameter type/datatype do not match
*/
public void setInt(int parameterIndex, int value) throws SQLException {
- setObject(parameterIndex, new Integer(value));
+ setObject(parameterIndex, Integer.valueOf(value));
}
/**
@@ -427,7 +422,7 @@
* @throws SQLException, if parameter type/datatype do not match
*/
public void setLong(int parameterIndex, long value) throws SQLException {
- setObject(parameterIndex, new Long(value));
+ setObject(parameterIndex, Long.valueOf(value));
}
/**
@@ -545,7 +540,7 @@
val = TimestampWithTimezone.create((java.util.Date)value, getDefaultCalendar().getTimeZone(), serverCalendar, value.getClass());
} else val = value;
- parameterMap.put(new Integer(parameterIndex), val);
+ parameterMap.put(parameterIndex, val);
}
/**
@@ -556,7 +551,7 @@
* @throws SQLException, if there is an error setting the parameter value
*/
public void setShort(int parameterIndex, short value) throws SQLException {
- setObject(parameterIndex, new Short(value));
+ setObject(parameterIndex, value);
}
/**
Modified: trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java
===================================================================
--- trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/common-core/src/main/java/org/teiid/core/util/ObjectConverterUtil.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -33,7 +33,10 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
+import java.io.OutputStream;
import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@@ -50,24 +53,7 @@
try {
// Open a stream to read the BLOB data
InputStream l_blobStream = data.getBinaryStream();
-
- // Open a file stream to save the BLOB data
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- BufferedOutputStream bos = new BufferedOutputStream(out);
-
- // Read from the BLOB data input stream, and write to the file output stream
- byte[] l_buffer = new byte[1024]; // buffer holding bytes to be transferred
- int l_nbytes = 0; // Number of bytes read
- while ((l_nbytes = l_blobStream.read(l_buffer)) != -1) // Read from BLOB stream
- bos.write(l_buffer,0,l_nbytes); // Write to file stream
-
- // Flush and close the streams
- bos.flush();
- bos.close();
- l_blobStream.close();
-
- return out.toByteArray();
-
+ return convertToByteArray(l_blobStream);
} catch (IOException ioe) {
final Object[] params = new Object[]{data.getClass().getName()};
throw new TeiidException(ioe,CorePlugin.Util.getString("ObjectConverterUtil.Error_translating_results_from_data_type_to_a_byte[]._1",params)); //$NON-NLS-1$
@@ -91,28 +77,65 @@
throw new TeiidException(CorePlugin.Util.getString("ObjectConverterUtil.Object_type_not_supported_for_object_conversion._3",params)); //$NON-NLS-1$
}
-
public static byte[] convertToByteArray(final InputStream is) throws IOException {
+ return convertToByteArray(is, -1);
+ }
+
+ /**
+ * Returns the given input stream's contents as a byte array.
+ * If a length is specified (ie. if length != -1), only length bytes
+ * are returned. Otherwise all bytes in the stream are returned.
+ * Note this does close the stream, even if not all bytes are written,
+ * because the buffering does not guarantee the end position.
+ * @throws IOException if a problem occurred reading the stream.
+ */
+ public static byte[] convertToByteArray(final InputStream is, int length) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
- BufferedOutputStream bos = new BufferedOutputStream(out);
+ write(out, is, length);
+ return out.toByteArray();
+ }
+
+ public static void write(final OutputStream out, final InputStream is, int length) throws IOException {
+ int writen = 0;
try {
- byte[] l_buffer = new byte[1024]; // buffer holding bytes to be transferred
+ byte[] l_buffer = new byte[DEFAULT_READING_SIZE]; // buffer holding bytes to be transferred
int l_nbytes = 0; // Number of bytes read
- while ((l_nbytes = is.read(l_buffer)) != -1) // Read from BLOB stream
- bos.write(l_buffer,0,l_nbytes); // Write to file stream
+ while ((l_nbytes = is.read(l_buffer)) != -1) {
+ if (length != -1 && writen > length - l_nbytes) {
+ out.write(l_buffer, 0, writen + l_nbytes - length);
+ break;
+ }
+ out.write(l_buffer,0,l_nbytes);
+ writen += l_nbytes;
+ }
} finally {
- is.close();
- bos.close();
+ is.close();
+ out.close();
}
- byte[] data = out.toByteArray();
- return data;
}
+
+ public static void write(final Writer out, final Reader is, int length) throws IOException {
+ int writen = 0;
+ try {
+ char[] l_buffer = new char[DEFAULT_READING_SIZE]; // buffer holding bytes to be transferred
+ int l_nbytes = 0; // Number of bytes read
+ while ((l_nbytes = is.read(l_buffer)) != -1) {
+ if (length != -1 && writen > length - l_nbytes) {
+ out.write(l_buffer, 0, writen + l_nbytes - length);
+ break;
+ }
+ out.write(l_buffer,0,l_nbytes);
+ writen += l_nbytes;
+ }
+ } finally {
+ is.close();
+ out.close();
+ }
+ }
-
public static InputStream convertToInputStream(byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
InputStream isContent = new BufferedInputStream(bais);
-
return isContent;
}
@@ -126,47 +149,25 @@
public static void write(final InputStream is, final String fileName) throws IOException {
File f = new File(fileName);
- f.delete();
-
write(is, f);
}
public static void write(final Reader reader, final String fileName) throws IOException {
File f = new File(fileName);
- f.delete();
-
write(reader, f);
}
public static void write(final Reader reader, final File f) throws IOException {
- FileWriter fw = new FileWriter(f);
- try {
- char[] buff = new char[2048];
- int bytesRead;
-
- // Simple read/write loop.
- while (-1 != (bytesRead = reader.read(buff, 0, buff.length))) {
- fw.write(buff, 0, bytesRead);
- }
- } finally {
- fw.close();
- }
+ f.getParentFile().mkdirs();
+ FileWriter fw = new FileWriter(f);
+ write(fw, reader, -1);
}
public static void write(final InputStream is, final File f) throws IOException {
+ f.getParentFile().mkdirs();
FileOutputStream fio = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fio);
- try {
- byte[] buff = new byte[2048];
- int bytesRead;
-
- // Simple read/write loop.
- while (-1 != (bytesRead = is.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- } finally {
- bos.close();
- }
+ write(bos, is, -1);
}
public static void write(byte[] data, final String fileName) throws Exception {
@@ -191,46 +192,25 @@
}
/**
* Returns the contents of the given file as a byte array.
- * @throws IOException if a problem occured reading the file.
+ * @throws IOException if a problem occurred reading the file.
*/
public static byte[] convertFileToByteArray(File file) throws IOException {
- InputStream stream = null;
- try {
- stream = new BufferedInputStream(new FileInputStream(file));
- return convertToByteArray(stream, (int) file.length());
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- }
- }
- }
+ return convertToByteArray(new FileInputStream(file), (int) file.length());
}
/**
* Returns the contents of the given file as a char array.
* When encoding is null, then the platform default one is used
- * @throws IOException if a problem occured reading the file.
+ * @throws IOException if a problem occurred reading the file.
*/
public static char[] convertFileToCharArray(File file, String encoding) throws IOException {
- InputStream stream = null;
- try {
- stream = new BufferedInputStream(new FileInputStream(file));
- return convertToCharArray(stream, (int) file.length(), encoding);
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- }
- }
- }
+ InputStream stream = new FileInputStream(file);
+ return convertToCharArray(stream, (int) file.length(), encoding);
}
/**
* Returns the contents of the given file as a string.
- * @throws IOException if a problem occured reading the file.
+ * @throws IOException if a problem occurred reading the file.
*/
public static String convertFileToString(final File file) throws IOException {
return new String(convertFileToCharArray(file,null));
@@ -239,161 +219,37 @@
/**
* Returns the contents of the given InputStream as a string.
- * @throws IOException if a problem occured reading the file.
+ * @throws IOException if a problem occurred reading the file.
*/
public static String convertToString(final InputStream stream) throws IOException {
return new String(convertToCharArray(stream, -1, null));
}
-
/**
- * Returns the given input stream's contents as a byte array.
- * If a length is specified (ie. if length != -1), only length bytes
- * are returned. Otherwise all bytes in the stream are returned.
- * Note this doesn't close the stream.
- * @throws IOException if a problem occured reading the stream.
- */
- public static byte[] convertToByteArray(InputStream stream, int length)
- throws IOException {
- byte[] contents;
- if (length == -1) {
- contents = new byte[0];
- int contentsLength = 0;
- int amountRead = -1;
- do {
- int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
-
- // resize contents if needed
- if (contentsLength + amountRequested > contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new byte[contentsLength + amountRequested],
- 0,
- contentsLength);
- }
-
- // read as many bytes as possible
- amountRead = stream.read(contents, contentsLength, amountRequested);
-
- if (amountRead > 0) {
- // remember length of contents
- contentsLength += amountRead;
- }
- } while (amountRead != -1);
-
- // resize contents if necessary
- if (contentsLength < contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new byte[contentsLength],
- 0,
- contentsLength);
- }
- } else {
- contents = new byte[length];
- int len = 0;
- int readSize = 0;
- while ((readSize != -1) && (len != length)) {
- // See PR 1FMS89U
- // We record first the read size. In this case len is the actual read size.
- len += readSize;
- readSize = stream.read(contents, len, length - len);
- }
- }
-
- return contents;
- }
-
- /**
* Returns the given input stream's contents as a character array.
* If a length is specified (ie. if length != -1), only length chars
* are returned. Otherwise all chars in the stream are returned.
* Note this doesn't close the stream.
- * @throws IOException if a problem occured reading the stream.
+ * @throws IOException if a problem occurred reading the stream.
*/
public static char[] convertToCharArray(InputStream stream, int length, String encoding)
throws IOException {
- InputStreamReader reader = null;
- reader = encoding == null
- ? new InputStreamReader(stream)
- : new InputStreamReader(stream, encoding);
- char[] contents;
- if (length == -1) {
- contents = new char[0];
- int contentsLength = 0;
- int amountRead = -1;
- do {
- int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K
-
- // resize contents if needed
- if (contentsLength + amountRequested > contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new char[contentsLength + amountRequested],
- 0,
- contentsLength);
- }
-
- // read as many chars as possible
- amountRead = reader.read(contents, contentsLength, amountRequested);
-
- if (amountRead > 0) {
- // remember length of contents
- contentsLength += amountRead;
- }
- } while (amountRead != -1);
-
- // resize contents if necessary
- if (contentsLength < contents.length) {
- System.arraycopy(
- contents,
- 0,
- contents = new char[contentsLength],
- 0,
- contentsLength);
- }
- } else {
- contents = new char[length];
- int len = 0;
- int readSize = 0;
- while ((readSize != -1) && (len != length)) {
- // See PR 1FMS89U
- // We record first the read size. In this case len is the actual read size.
- len += readSize;
- readSize = reader.read(contents, len, length - len);
- }
- // See PR 1FMS89U
- // Now we need to resize in case the default encoding used more than one byte for each
- // character
- if (len != length)
- System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
- }
-
- return contents;
+ Reader r = null;
+ if (encoding == null) {
+ r = new InputStreamReader(stream);
+ } else {
+ r = new InputStreamReader(stream, encoding);
+ }
+ return convertToCharArray(r, length);
}
/**
* Returns the contents of the given zip entry as a byte array.
- * @throws IOException if a problem occured reading the zip entry.
+ * @throws IOException if a problem occurred reading the zip entry.
*/
public static byte[] convertToByteArray(ZipEntry ze, ZipFile zip)
throws IOException {
-
- InputStream stream = null;
- try {
- stream = new BufferedInputStream(zip.getInputStream(ze));
- return convertToByteArray(stream, (int) ze.getSize());
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- }
- }
- }
+ return convertToByteArray(zip.getInputStream(ze), (int) ze.getSize());
}
public static String convertToString(Reader reader) throws IOException {
@@ -401,11 +257,8 @@
}
public static char[] convertToCharArray(Reader reader, int length) throws IOException {
- StringBuilder sb = new StringBuilder();
- int chr = -1;
- for (int i = 0; i < length && (chr = reader.read()) != -1; i ++) {
- sb.append((char)chr);
- }
+ StringWriter sb = new StringWriter();
+ write(sb, reader, length);
return sb.toString().toCharArray();
}
Property changes on: trunk/connectors/connector-ws
___________________________________________________________________
Name: svn:ignore
+ target
.settings
.classpath
.project
Modified: trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java
===================================================================
--- trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/jboss-integration/src/main/java/org/teiid/adminapi/jboss/Admin.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -233,7 +233,6 @@
else {
Map<String, String> configProps = new HashMap<String, String>();
configProps.put(propertyName, propertyValue);
- configProps.put(propertyValue+".type", "java.lang.String"); //$NON-NLS-1$ //$NON-NLS-2$
MetaValue metaValue = ManagedUtil.compositeValueMap(configProps);
mc.getProperty("translator-property").setValue(metaValue); //$NON-NLS-1$
}
Modified: trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java
===================================================================
--- trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java 2010-05-18 15:08:58 UTC (rev 2136)
+++ trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java 2010-05-18 15:20:27 UTC (rev 2137)
@@ -29,7 +29,7 @@
import junit.framework.TestCase;
-
+@SuppressWarnings("nls")
public class TestLocalBufferService extends TestCase {
public TestLocalBufferService(String name) {
15 years, 11 months
teiid SVN: r2136 - trunk/build/kits/jboss-container/deploy/teiid/connectors.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2010-05-18 11:08:58 -0400 (Tue, 18 May 2010)
New Revision: 2136
Modified:
trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml
Log:
TEIID-1077: fixing the translator for the package name change
Modified: trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml
===================================================================
--- trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml 2010-05-18 12:15:39 UTC (rev 2135)
+++ trunk/build/kits/jboss-container/deploy/teiid/connectors/xml-translator.xml 2010-05-18 15:08:58 UTC (rev 2136)
@@ -2,7 +2,7 @@
<translator-factory>
<translator>
<name>xml</name>
- <execution-factory-class>org.teiid.translator.xml.base.XMLExecutionFactory</execution-factory-class>
+ <execution-factory-class>org.teiid.translator.xml.XMLExecutionFactory</execution-factory-class>
<template-name>translator-xml-${project.version}</template-name>
</translator>
</translator-factory>
\ No newline at end of file
15 years, 11 months