teiid SVN: r1498 - trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:06:51 -0400 (Wed, 30 Sep 2009)
New Revision: 1498
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-30 16:04:29 UTC (rev 1497)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-30 16:06:51 UTC (rev 1498)
@@ -4,61 +4,35 @@
*/
package org.teiid.test.framework.datasource;
+import java.io.File;
+import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
-import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
import java.util.Map;
import java.util.Properties;
-import java.util.Set;
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.JDOMException;
-import org.teiid.test.framework.ConfigPropertyLoader;
-import org.teiid.test.framework.ConfigPropertyNames;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
-import com.metamatrix.common.xml.XMLReaderWriter;
-import com.metamatrix.common.xml.XMLReaderWriterImpl;
-import com.metamatrix.core.util.StringUtil;
+
/**
- * The DataSourceMgr is responsible for loading and managing datasources defined by the datasource
- * mapping properties file {@see #DATASOURCE_MAPPING_FILE} and the mapped
- * datasource properties files. The {@link #getDatasourceProperties(String)}
- * returns the properties defined for that datasourceid, which is mapped in the
- * mnappings file. This mapping allows the test
+ * The DataSourceMgr is responsible for loading and managing the datasources defined by the datasource
+ * connection properties file. There's only a need to load the set of available datasources once for
+ * the duration of the entire test suite. And it will maintain one {@link DataSource} for each connection.properties
+ * file that it finds.
*
* @author vanhalbert
*
*/
public class DataSourceMgr {
-
- static final String RELATIVE_DIRECTORY = "datasources/";
- static final String DATASOURCE_MAPPING_FILE = "datasource_mapping.xml";
private static DataSourceMgr _instance = null;
- private Map<String, Map<String, DataSource>>dsGroupMap = new HashMap<String, Map<String, DataSource>>(); //key=datasourcetype
-
private Map<String, DataSource> allDatasourcesMap = new HashMap<String, DataSource>(); // key=datasource name
-
- private Map<String, DataSource> modelToDatasourceMap = new HashMap<String, DataSource>(); // key=modelname + "_" + datasourcename
- // key=modelname + "_" + groupname
-
- private Set<String> dbTypes = new HashSet<String>();
- // this set is use to track datasources that have already been assigned
- private Set<String> assignedDataSources = new HashSet<String>();
-
- private int lastassigned = 0;
-
private DataSourceMgr() {
}
@@ -68,240 +42,99 @@
try {
_instance.loadDataSourceMappings();
} catch (QueryTestFailedException e) {
- // TODO Auto-generated catch block
throw new TransactionRuntimeException(e);
} catch (TransactionRuntimeException e) {
- // TODO Auto-generated catch block
throw e;
}
}
return _instance;
}
+
+ public Map<String, DataSource> getDataSources() {
+ Map<String, DataSource> ds = new HashMap<String, DataSource>(allDatasourcesMap.size());
+ ds.putAll(allDatasourcesMap);
+ return ds;
+ }
- /**
- * reset is called when a predetermined set of datasources are going to be set
- * This is to ensure any exclusions / inclusions are considered for the
- * next executed set of test.
- *
- *
- * @since
- */
- public static synchronized void reset() {
- if (_instance == null) return;
- //
- _instance.modelToDatasourceMap.clear();
- _instance.assignedDataSources.clear();
-
- }
-
public int numberOfAvailDataSources() {
return allDatasourcesMap.size();
}
-
-// public boolean hasAvailableDataSource(int numRequiredDataSources) {
-// // reset the mapping at the start of each test
-// _instance.modelToDatasourceMap.clear();
-//
-// Set<String>excludedDBTypes = getExcludedDBTypes();
-//
-// Set<String> xSet = new HashSet<String>(dbTypes);
-//
-// xSet.removeAll(excludedDBTypes);
-//
-// return(numRequiredDataSources <= (xSet.size()));
-//
-// }
-
- private Set<String> getExcludedDBTypes() {
-
- String excludeprop = ConfigPropertyLoader.getProperty(ConfigPropertyNames.EXCLUDE_DATASBASE_TYPES_PROP);
- if (excludeprop == null || excludeprop.length() == 0) {
- return Collections.EMPTY_SET;
- }
- Set<String> excludedDBTypes = new HashSet<String>(3);
- List<String> eprops = StringUtil.split(excludeprop, ",");
- excludedDBTypes.addAll(eprops);
- return excludedDBTypes;
-
- }
-
-
- public DataSource getDatasource(String datasourceid, String modelName)
+ private void loadDataSourceMappings()
throws QueryTestFailedException {
- DataSource ds = null;
-
- // map the datasource to the model and datasourceid
- // this is so the next time this combination is requested,
- // the same datasource is returned to ensure when consecutive calls during the process
- // corresponds to the same datasource
- String key = null;
-
- key = modelName + "_"+datasourceid;
-
- // if the datasourceid represents a group name, then use the group name
- // so that all future request using that group name for a specified model
- // will use the same datasource
- if (modelToDatasourceMap.containsKey(key)) {
- return modelToDatasourceMap.get(key);
- }
-
- Set excludedDBTypes = getExcludedDBTypes();
-
- if (dsGroupMap.containsKey(datasourceid)) {
-
- Map datasources = dsGroupMap.get(datasourceid);
- Iterator<DataSource> it= datasources.values().iterator();
+
+
+ File[] dirs = findAllChildDirectories("./target/classes/datasources/");
+ if (dirs == null || dirs.length == 0) {
+ throw new TransactionRuntimeException("No datasource directories found at location " + "./target/classes/datasources/");
+ }
+ for (int i = 0; i < dirs.length; i++) {
+ File d = dirs[i];
- // need to go thru all the datasources to know if any has already been assigned
- // because the datasourceid passed in was a group name
- while(it.hasNext()) {
- DataSource checkit = it.next();
-
- if (excludedDBTypes.contains(checkit.getDBType())) {
- continue;
- }
-
- if (!assignedDataSources.contains(checkit.getName())) {
- ds = checkit;
- assignedDataSources.add(ds.getName());
- break;
- }
-
- }
-
-
- if (ds == null) {
- int cnt = 0;
- Iterator<DataSource> itds= datasources.values().iterator();
-
- // when all the datasources have been assigned, but a new model datasource id is
- // passed in, need to reassign a previously assigned datasource
- // This case will happen when more models are defined than there are defined datasources.
- while(itds.hasNext()) {
- DataSource datasource = itds.next();
- if (cnt == this.lastassigned) {
- ds = datasource;
+ String dname = d.getName();
- this.lastassigned++;
- if (lastassigned >= datasources.size()) {
- this.lastassigned = 0;
- }
-
- break;
- }
- }
-
- }
-
- } else {
- ds = allDatasourcesMap.get(datasourceid);
+ addDataSource(dname, d.getName(),allDatasourcesMap);
- if (excludedDBTypes.contains(ds.getDBType())) {
- ds = null;
- }
-
}
- if (ds == null) {
- throw new QueryTestFailedException("DatasourceID " + datasourceid
- + " is not a defined datasource in the mappings file ");
-
+
+ if (allDatasourcesMap == null || allDatasourcesMap.isEmpty()) {
+ throw new TransactionRuntimeException(
+ "Error: No Datasources were loaded.");
}
+
+ System.out.println("Number of total datasource mappings loaded " + allDatasourcesMap.size());
- modelToDatasourceMap.put(key, ds);
- return ds;
-
}
+
+ /**
+ * Returns a <code>File</code> array that will contain all the directories that exist in the directory
+ *
+ * @return File[] of directories in the directory
+ */
+ private static File[] findAllChildDirectories(String dir) {
-
- private void loadDataSourceMappings()
- throws QueryTestFailedException {
-
- Set<String> limitds = new HashSet<String>();
- String limitdsprop = ConfigPropertyLoader.getProperty(ConfigPropertyNames.USE_DATASOURCES_PROP);
- if (limitdsprop != null && limitdsprop.length() > 0) {
- System.out.println("Limit datasources to: " + limitdsprop);
- List<String> dss = StringUtil.split(limitdsprop, ",");
- limitds.addAll(dss);
- }
-
- Document doc = null;
- XMLReaderWriter readerWriter = new XMLReaderWriterImpl();
-
+ // Find all files in the specified directory
+ File mfile = new File(dir);
+
+ File modelsDirFile = null;
try {
- doc = readerWriter.readDocument(getInputStream());
- } catch (JDOMException e) {
- e.printStackTrace();
- throw new TransactionRuntimeException(e);
+ modelsDirFile = new File(mfile.getCanonicalPath());
} catch (IOException e) {
+ // TODO Auto-generated catch block
e.printStackTrace();
- throw new TransactionRuntimeException(e);
}
+ if (!modelsDirFile.exists()) {
+ return null;
+ }
+ FileFilter fileFilter = new FileFilter() {
- Element root = doc.getRootElement();
- List<Element> rootElements = root.getChildren();
- if (rootElements == null || rootElements.size() == 0) {
- throw new TransactionRuntimeException("No children defined under root element " + DSCONFIG);
- }
-
- for (Iterator<Element> it = rootElements.iterator(); it.hasNext();) {
- Element type = it.next();
- String groupname = type.getAttributeValue(Property.Attributes.NAME);
+ public boolean accept(File file) {
+ if (file.isDirectory()) {
+ return true;
+ }
- List<Element> typeElements = type.getChildren();
- if (typeElements != null) {
- Map<String, DataSource> datasources = new HashMap<String, DataSource>(typeElements.size());
+ return false;
+ }
+ };
- for (Iterator<Element> typeit = typeElements.iterator(); typeit.hasNext();) {
- Element e = typeit.next();
- addDataSource(e, groupname, datasources, limitds);
- }
- dsGroupMap.put(groupname, datasources);
- allDatasourcesMap.putAll(datasources);
+ File[] modelFiles = modelsDirFile.listFiles(fileFilter);
- }
-
-
- }
+ return modelFiles;
- if (dsGroupMap == null || dsGroupMap.isEmpty()) {
- throw new TransactionRuntimeException(
- "No Datasources were found in the mappings file");
- }
-
- System.out.println("Number of datasource groups loaded " + dsGroupMap.size());
- System.out.println("Number of total datasource mappings loaded " + allDatasourcesMap.size());
-
-
-
- }
+ }
- private void addDataSource(Element element, String group, Map<String, DataSource> datasources, Set<String> include) {
- String name = element.getAttributeValue(Property.Attributes.NAME);
+ private void addDataSource(String dirname, String dirloc, Map<String, DataSource> datasources) {
- Properties props = getProperties(element);
- String dir = props.getProperty(DataSource.DIRECTORY);
-
- if (include.size() > 0) {
- if (!include.contains(dir)) {
-// System.out.println("Excluded datasource: " + name);
- return;
- }
- }
-
- String dsfile = RELATIVE_DIRECTORY + dir + "/connection.properties";
+ String dsfile = "/datasources/" + dirloc + "/connection.properties";
Properties dsprops = loadProperties(dsfile);
-
- if (dsprops != null) {
- props.putAll(dsprops);
- DataSource ds = new DataSource(name,
- group,
- props);
- dbTypes.add(ds.getDBType());
+ if (dsprops != null) {
+ DataSource ds = new DataSource(dirname,
+ "dsgroup",
+ dsprops);
datasources.put(ds.getName(), ds);
System.out.println("Loaded datasource " + ds.getName());
@@ -314,8 +147,7 @@
Properties props = null;
try {
- InputStream in = DataSourceMgr.class.getResourceAsStream("/"
- + filename);
+ InputStream in = DataSourceMgr.class.getResourceAsStream(filename);
if (in != null) {
props = new Properties();
props.load(in);
@@ -328,123 +160,4 @@
}
}
- private static Properties getProperties(Element propertiesElement) {
- Properties props = new Properties();
-
- List<Element> properties = propertiesElement
- .getChildren(Property.ELEMENT);
- Iterator<Element> iterator = properties.iterator();
- while (iterator.hasNext()) {
- Element propertyElement = (Element) iterator.next();
- String propertyName = propertyElement
- .getAttributeValue(Property.Attributes.NAME);
- String propertyValue = propertyElement.getText();
-
- props.setProperty(propertyName, propertyValue);
-
- }
- return props;
- }
-
- private static InputStream getInputStream() {
-
- InputStream in = DataSourceMgr.class.getResourceAsStream("/"
- + RELATIVE_DIRECTORY + DATASOURCE_MAPPING_FILE);
- if (in != null) {
-
- return in;
- } else {
- throw new RuntimeException(
- "Failed to load datasource mapping file '" + RELATIVE_DIRECTORY
- + DATASOURCE_MAPPING_FILE + "'");
- }
-
- }
-
- static final String DSCONFIG = "datasourceconfig";
- static final String DATASOURCETYPE = "datasourcetype";
- static final String DATASOURCE = "datasource";
-
- static class Property {
-
- /**
- * This is the name of the Property Element.
- */
- public static final String ELEMENT = "property"; //$NON-NLS-1$
-
- /**
- * This class defines the Attributes of the Element class that contains
- * it.
- */
- public static class Attributes {
- public static final String NAME = "name"; //$NON-NLS-1$
- }
-
- }
-
- public static void main(String[] args) {
-
-
- DataSourceMgr mgr = DataSourceMgr.getInstance();
-
- try {
- DataSource ds1 = mgr.getDatasource("ds_oracle", "model1");
-
- DataSource ds2 = mgr.getDatasource("nonxa", "model1");
- if (ds1 != ds2) {
- throw new RuntimeException("Datasources are not the same");
- }
- System.out.println("Value for ds_mysql: "
- + mgr.getDatasource("ds_oracle", "model1").getProperties());
-
-// boolean shouldbeavail = mgr.hasAvailableDataSource("nonxa", DataSource.ExclusionTypeBitMask.ORACLE);
-// if (!shouldbeavail) {
-// throw new RuntimeException("Should have found one available");
-// }
-//
-// shouldbeavail = mgr.hasAvailableDataSource("nonxa", DataSource.ExclusionTypeBitMask.ORACLE | DataSource.ExclusionTypeBitMask.MYSQL);
-// if (!shouldbeavail) {
-// throw new RuntimeException("Should have found one available");
-// }
-//
-//
-// boolean shouldnot = mgr.hasAvailableDataSource("nonxa", DataSource.ExclusionTypeBitMask.ORACLE | DataSource.ExclusionTypeBitMask.MYSQL | DataSource.ExclusionTypeBitMask.SQLSERVER);
-// if (shouldnot) {
-// throw new RuntimeException("Should NOT have found one available");
-// }
- } catch (QueryTestFailedException e) {
- e.printStackTrace();
- }
-
- DataSourceMgr.reset();
-
- System.setProperty(ConfigPropertyNames.USE_DATASOURCES_PROP, "ds_sqlserver");
-
- mgr = DataSourceMgr.getInstance();
-
- try {
-
- DataSource dsfind = mgr.getDatasource("ds_sqlserver", "model1");
- if (dsfind == null) {
- throw new RuntimeException("The special included datasource was not found");
-
- }
- System.out.println("Datasource :" + dsfind.getName() + " was found");
-
- try {
- DataSource dsnotfound = mgr.getDatasource("ds_oracle", "model1");
- if (dsnotfound != null) {
- throw new RuntimeException("The special excluded datasource was found");
-
- }
- } catch (QueryTestFailedException qtf) {
-
- System.out.println("Datasource: ds_oracle: was not found and should not have");
- }
-
- } catch (QueryTestFailedException e) {
- e.printStackTrace();
- }
- }
-
}
15 years, 3 months
teiid SVN: r1497 - trunk/test-integration/db/src/main/java/org/teiid/test/framework.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:04:29 -0400 (Wed, 30 Sep 2009)
New Revision: 1497
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyLoader.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyNames.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionQueryTest.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyLoader.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyLoader.java 2009-09-30 16:04:02 UTC (rev 1496)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyLoader.java 2009-09-30 16:04:29 UTC (rev 1497)
@@ -2,64 +2,98 @@
import java.util.Properties;
+import org.teiid.test.framework.exception.TransactionRuntimeException;
import org.teiid.test.util.PropUtils;
+import com.metamatrix.common.util.PropertiesUtils;
-public class ConfigPropertyLoader {
-
-
- /**
- * The default config file to use when #CONFIG_FILE system property isn't set
- */
- protected static final String DEFAULT_CONFIG_FILE_NAME="default-config.properties";
-
- private static Properties props = null;
- public synchronized static void loadConfigurationProperties() {
- String filename = System.getProperty(ConfigPropertyNames.CONFIG_FILE);
- if (filename == null) {
- filename = DEFAULT_CONFIG_FILE_NAME;
- }
-
- loadProperties(filename); }
-
- public static String getProperty(String key) {
- return getProperties().getProperty(key);
- }
-
- public synchronized static Properties getProperties() {
- if (props == null) {
- loadConfigurationProperties();
+/**
+ * The ConfigProperteryLoader will load the configuration properties to be used by a test.
+ *
+ * @author vanhalbert
+ *
+ */
+public class ConfigPropertyLoader {
+
+ /**
+ * The default config file to use when #CONFIG_FILE system property isn't
+ * set
+ */
+ protected static final String DEFAULT_CONFIG_FILE_NAME = "default-config.properties";
+
+ private Properties props = null;
+
+ private ConfigPropertyLoader() {
+ }
+
+ public static synchronized ConfigPropertyLoader createInstance() {
+ ConfigPropertyLoader _instance = null;
+ _instance = new ConfigPropertyLoader();
+ try {
+ _instance.loadConfigurationProperties();
+ } catch (TransactionRuntimeException e) {
+ throw e;
}
- return props;
+
+ return _instance;
+ }
+
+ private void loadConfigurationProperties() {
+ String filename = System.getProperty(ConfigPropertyNames.CONFIG_FILE);
+ if (filename == null) {
+ filename = DEFAULT_CONFIG_FILE_NAME;
}
-
- private static void loadProperties(String filename) {
- props =PropUtils.loadProperties("/"+ filename, System.getProperties());
- }
+ loadProperties(filename);
- public static void cleanup() {
- Properties p = System.getProperties();
- p.remove(ConfigPropertyNames.CONFIG_FILE);
- p.remove(ConfigPropertyNames.EXCLUDE_DATASBASE_TYPES_PROP);
-
- }
- public static void main(String[] args) {
- System.setProperty("test", "value");
-
- ConfigPropertyLoader.loadConfigurationProperties();
- Properties p = ConfigPropertyLoader.getProperties();
- if (p == null || p.isEmpty()) {
- throw new RuntimeException("Failed to load config properties file");
+ Properties p = System.getProperties();
+ p.remove(ConfigPropertyNames.CONFIG_FILE);
+ p.remove(ConfigPropertyNames.EXCLUDE_DATASBASE_TYPES_PROP);
+ p.remove(ConfigPropertyNames.USE_DATASOURCES_PROP);
+ p.remove(ConfigPropertyNames.CONNECTION_TYPE);
+ p.remove(ConfigPropertyNames.TRANSACTION_TYPE);
- }
- if (p.getProperty("test") == null) {
- throw new RuntimeException("Failed to pickup system property");
- }
- System.out.println("Loaded Config Properties " + p.toString());
+
+ }
+
+ public String getProperty(String key) {
+ return getProperties().getProperty(key);
+ }
+
+ public void setProperty(String key, String value) {
+ props.setProperty(key, value);
+ }
+
+ public Properties getProperties() {
+ return props;
+ }
+
+ private void loadProperties(String filename) {
+
+ Properties sysprops = PropertiesUtils.clone(System.getProperties());
+
+ props = PropUtils
+ .loadProperties("/" + filename, sysprops);
+
+ }
+
+ public static void main(String[] args) {
+ System.setProperty("test", "value");
+
+ ConfigPropertyLoader _instance = ConfigPropertyLoader.createInstance();
+ Properties p = _instance.getProperties();
+ if (p == null || p.isEmpty()) {
+ throw new RuntimeException("Failed to load config properties file");
+
}
-
+ if (p.getProperty("test") == null) {
+ throw new RuntimeException("Failed to pickup system property");
+ }
+ System.out.println("Loaded Config Properties " + p.toString());
+
+ }
+
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyNames.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyNames.java 2009-09-30 16:04:02 UTC (rev 1496)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/ConfigPropertyNames.java 2009-09-30 16:04:29 UTC (rev 1497)
@@ -1,5 +1,7 @@
package org.teiid.test.framework;
+import com.metamatrix.jdbc.api.ExecutionProperties;
+
/**
* The following properties can be set in 2 ways:
* <li>set as a System property(..)</li>
@@ -64,6 +66,11 @@
public static final String CONNECTION_TYPE = "connection-type"; //$NON-NLS-1$
+ /**
+ * {@see #CONNECTION_TYPE} regarding setting the specific connection type to use
+ * @author vanhalbert
+ *
+ */
public interface CONNECTION_TYPES {
// used to create the jdb driver
@@ -75,5 +82,22 @@
}
+
+ /**
+ * Connection Props are the {@link CONNECTION_STRATEGY} execution options
+ * @author vanhalbert
+ *
+ */
+ public interface CONNECTION_STRATEGY_PROPS {
+ public static final String TXN_AUTO_WRAP = ExecutionProperties.PROP_TXN_AUTO_WRAP;
+ public static final String AUTOCOMMIT = "autocommit"; //$NON-NLS-1$
+ public static final String FETCH_SIZE = ExecutionProperties.PROP_FETCH_SIZE;
+ public static final String EXEC_IN_BATCH = "execute.in.batch"; //$NON-NLS-1$
+ public static final String CONNECTOR_BATCH = "connector-batch"; //$NON-NLS-1$
+ public static final String PROCESS_BATCH = "process-batch"; //$NON-NLS-1$
+ public static final String JNDINAME_USERTXN = "usertxn-jndiname"; //$NON-NLS-1$
+
+ }
+
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java 2009-09-30 16:04:02 UTC (rev 1496)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionContainer.java 2009-09-30 16:04:29 UTC (rev 1497)
@@ -8,6 +8,7 @@
import org.teiid.test.framework.connection.ConnectionStrategy;
import org.teiid.test.framework.connection.ConnectionStrategyFactory;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
@@ -16,20 +17,26 @@
private boolean debug = false;
+ protected ConfigPropertyLoader config = null;
protected Properties props;
protected ConnectionStrategy connStrategy;
+ protected DataSourceFactory dsfactory;
- protected TransactionContainer(){
-
+ protected TransactionContainer(ConfigPropertyLoader propertyconfig){
+ this.config = propertyconfig;
}
protected void setUp(TransactionQueryTest test) throws QueryTestFailedException {
- this.connStrategy = ConnectionStrategyFactory.getInstance().getConnectionStrategy();
+ this.dsfactory = new DataSourceFactory(config);
+
+ this.connStrategy = ConnectionStrategyFactory.createConnectionStrategy(config, dsfactory);
this.props = new Properties();
this.props.putAll(this.connStrategy.getEnvironment());
+
+ test.setConnectionStrategy(connStrategy);
- test.setDataSources(connStrategy.getDataSources());
- test.setupDataSources();
+ test.setupDataSource();
+
}
@@ -50,8 +57,14 @@
try {
test.cleanup();
} finally {
+
+ // cleanup all defined datasources for the last test and
+ // any overrides regarding inclusions and exclusions.
+ this.dsfactory.cleanup();
+
+
// cleanup all connections created for this test.
- ConnectionStrategyFactory.destroyInstance();
+ connStrategy.shutdown();
}
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionQueryTest.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionQueryTest.java 2009-09-30 16:04:02 UTC (rev 1496)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/TransactionQueryTest.java 2009-09-30 16:04:29 UTC (rev 1497)
@@ -6,7 +6,9 @@
import javax.sql.XAConnection;
+import org.teiid.test.framework.connection.ConnectionStrategy;
import org.teiid.test.framework.datasource.DataSource;
+import org.teiid.test.framework.exception.QueryTestFailedException;
/**
* The TransactionQueryTest interface represents the transaction test framework from which
@@ -31,18 +33,8 @@
*/
void setConnection(Connection conn);
-
+
/**
- * Called by the @link TransactionContainer to set the datasoures used to create the connector bindings and
- * used to create direct connection to the sources.
- * @param datasources
- *
- * @since
- */
- void setDataSources(Map<String, DataSource> datasources);
-
-
- /**
* Returns the connection being used in the test.
* @return
*
@@ -62,7 +54,16 @@
*/
void setExecutionProperties(Properties props) ;
+
/**
+ * Called to set the current connection strategy being used.
+ * @param connStrategy
+ *
+ * @since
+ */
+ void setConnectionStrategy(ConnectionStrategy connStrategy);
+
+ /**
* The test case has to specify how many sources its using so that the correct
* data setup is performed.
* @return int is the number of datasources in use
@@ -77,12 +78,12 @@
/**
* Called by the {@link TransactionContainer} prior to testcase processing so that
- * the datasources can be setup for the specific testcase.
+ * the responsibility for performing datasource setup can be done
*
*
* @since
*/
- void setupDataSources();
+ void setupDataSource() throws QueryTestFailedException;
/**
15 years, 3 months
teiid SVN: r1496 - trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:04:02 -0400 (Wed, 30 Sep 2009)
New Revision: 1496
Added:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceFactory.java
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSource.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSource.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSource.java 2009-09-30 16:03:33 UTC (rev 1495)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSource.java 2009-09-30 16:04:02 UTC (rev 1496)
@@ -1,30 +1,27 @@
package org.teiid.test.framework.datasource;
-import java.util.HashMap;
-import java.util.Map;
import java.util.Properties;
+/**
+ * DataSource represents a single database that was configured by a connection.properties file.
+ * @author vanhalbert
+ *
+ */
public class DataSource {
- public static final String CONNECTOR_TYPE="connectortype";
- public static final String DIRECTORY="dir";
+ public static final String CONNECTOR_TYPE="db.connectortype";
public static final String DB_TYPE="db.type";
- static Map<String, String> dbtypeBitMaskMap = null;
-
-
private Properties props;
private String name;
private String group;
private String dbtype;
- private int bitMask;
public DataSource(String name, String group, Properties properties) {
this.name = name;
this.group = group;
this.props = properties;
this.dbtype = this.props.getProperty(DB_TYPE);
- this.setBitMask();
}
@@ -51,10 +48,6 @@
public String getDBType() {
return this.dbtype;
}
-
- public int getBitMask() {
- return this.bitMask;
- }
/**
@@ -73,66 +66,6 @@
public static String DERBY = "derby";
}
-
-
- /**
- * These bitmask are used by the test to indicate which database type(s) a specific
- * test is not supported to run against.
- *
- * The exclusion postion was taken because the goal is that all test should be able to
- * run against all sources. However, there are cases where specific database type
- * test are needed.
- *
- *
- * @author vanhalbert
- *
- */
- public static interface ExclusionTypeBitMask{
- // Constants to hold bit masks for desired flags
- static final int NONE_EXCLUDED = 0; // 000...00000000 (empty mask)
- static final int MYSQL = 1; // 2^^0 000...00000001
- static final int ORACLE = 2; // 2^^1 000...00000010
- static final int POSTGRES = 4; // 2^^2 000...00000100
- static final int SQLSERVER = 8; // 2^^3 000...00001000
- static final int DB2 = 16; // 2^^4 000...00010000
- static final int SYBASE = 32; // 2^^5 000...00100000
- static final int DERBY = 64; // 2^^6 000...01000000
-
- }
- // don't include excluded
- public static int NumBitMasks = 7;
-//
-// static int ALLOWABLE_DATA_TYPES = ExclusionTypeBitMask.MYSQL |
-// ExclusionTypeBitMask.ORACLE |
-// ExclusionTypeBitMask.POSTGRES |
-// ExclusionTypeBitMask.SQLSERVER |
-// ExclusionTypeBitMask.DB2 |
-// ExclusionTypeBitMask.SYBASE |
-// ExclusionTypeBitMask.DERBY;
-
- static {
- dbtypeBitMaskMap = new HashMap<String, String>(NumBitMasks );
- dbtypeBitMaskMap.put(DataSourcTypes.MYSQL, String.valueOf(ExclusionTypeBitMask.MYSQL));
- dbtypeBitMaskMap.put(DataSourcTypes.ORACLE, String.valueOf(ExclusionTypeBitMask.ORACLE));
- dbtypeBitMaskMap.put(DataSourcTypes.POSTRES, String.valueOf(ExclusionTypeBitMask.POSTGRES));
- dbtypeBitMaskMap.put(DataSourcTypes.DB2, String.valueOf(ExclusionTypeBitMask.DB2));
- dbtypeBitMaskMap.put(DataSourcTypes.SQLSERVER, String.valueOf(ExclusionTypeBitMask.SQLSERVER));
- dbtypeBitMaskMap.put(DataSourcTypes.SYBASE, String.valueOf(ExclusionTypeBitMask.SYBASE));
- dbtypeBitMaskMap.put(DataSourcTypes.DERBY, String.valueOf(ExclusionTypeBitMask.DERBY));
-
- }
-
- public void setBitMask() {
- int rtn = ExclusionTypeBitMask.NONE_EXCLUDED;
-
- String bitmask = dbtypeBitMaskMap.get(dbtype);
- if (bitmask == null) {
- bitMask = rtn;
- } else {
- bitMask = new Integer(bitmask).intValue();
- }
- }
-
}
Added: trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceFactory.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceFactory.java (rev 0)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceFactory.java 2009-09-30 16:04:02 UTC (rev 1496)
@@ -0,0 +1,328 @@
+package org.teiid.test.framework.datasource;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.teiid.test.framework.ConfigPropertyLoader;
+import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.exception.QueryTestFailedException;
+
+import com.metamatrix.core.util.StringUtil;
+
+
+/**
+ * The DataSourceFactory is responsible for managing the datasources used during a single test.
+ * It ensures the same data source is used in both the connector binding and during validation.
+ * Otherwise, validation may be validating against a source for which the test didn't run.
+ *
+ * A test has the option of specifying the following properties to control which data sources are / or not used
+ *
+ * <li>{@link ConfigPropertyNames#USE_DATASOURCES_PROP} : is a comma delimited ordered list to control which data sources to use</li>
+ *
+ * This is an ordered list because based on the model:order mapping in the config.properties file will map to the ordered list
+ * respectfully.
+ *
+ * Example: in the config.properties may specify:
+ * pm1=1
+ * pm2=2
+ *
+ * Set ConfigPropertyNames.USE_DATASOURCES_PROP=oracle,sqlserver
+ *
+ * This indicates that when a datasource is requested for "pm1", then oracle datasource will be returned. And when a data source
+ * for "pm2" is requested, then a data source representing sqlserver will be returned.
+ *
+ * <li>{@link ConfigPropertyNames#EXCLUDE_DATASBASE_TYPES_PROP} : is a comma delimited list indicating which data sources not use
+ * during that specific test.
+ *
+ * @author vanhalbert
+ *
+ */
+public class DataSourceFactory {
+
+ // the DO_NO_USE_DEFAULT will be passed in when the test are run from maven and no property is passed in for UseDataSources
+ private static final String DO_NOT_USE_DEFAULT="${usedatasources}";
+ private ConfigPropertyLoader configprops;
+
+ // contains the names of the datasources when the -Dusedatasources option is
+ // used
+ private Map<String, String> useDS = null;
+ private Set<String> excludedDBTypes = null;
+
+ private Set<String> unmappedds = new HashSet<String>();
+
+ private Map<String, DataSource> allDatasourcesMap = null;
+
+ // map of the datasources assigned to with model
+ private Map<String, DataSource> modelToDatasourceMap = new HashMap<String, DataSource>(); // key
+ // =
+ // modelname
+ // +
+ // "_"
+ // +
+ // datasourceid
+
+ // this set is use to track datasources that have already been assigned
+ private Set<String> assignedDataSources = new HashSet<String>();
+
+ private int lastassigned = 0;
+
+ public DataSourceFactory(ConfigPropertyLoader config) {
+ this.configprops = config;
+ config();
+ }
+
+ /**
+ * config is called at the start / setup of the {@link
+ * TransactionContainer#} test. This is to ensure any exclusions /
+ * inclusions are considered for the next executed set of test.
+ *
+ *
+ * @since
+ */
+ private void config() {
+ System.out.println("Configure Datasource Factory ");
+
+ this.allDatasourcesMap = DataSourceMgr.getInstance().getDataSources();
+
+ String limitdsprop = configprops
+ .getProperty(ConfigPropertyNames.USE_DATASOURCES_PROP);
+ if (limitdsprop != null && limitdsprop.length() > 0 && ! limitdsprop.equalsIgnoreCase(DO_NOT_USE_DEFAULT)) {
+ System.out.println("Use ONLY datasources: " + limitdsprop);
+
+ List<String> dss = StringUtil.split(limitdsprop, ",");
+
+ useDS = new HashMap<String, String>(dss.size());
+ int i = 1;
+ for (Iterator<String> it = dss.iterator(); it.hasNext(); i++) {
+ useDS.put(String.valueOf(i), it.next());
+ }
+
+ }
+
+ String excludeprop = configprops
+ .getProperty(ConfigPropertyNames.EXCLUDE_DATASBASE_TYPES_PROP);
+
+ if (excludeprop != null && excludeprop.length() > 0) {
+ List<String> eprops = StringUtil.split(excludeprop, ",");
+ excludedDBTypes = new HashSet<String>(eprops.size());
+ excludedDBTypes.addAll(eprops);
+ System.out.println("EXCLUDE datasources: " + excludeprop);
+ }
+ }
+
+ public synchronized DataSource getDatasource(String datasourceid,
+ String modelName) throws QueryTestFailedException {
+ DataSource ds = null;
+
+ // map the datasource to the model and datasourceid
+ // this is so the next time this combination is requested,
+ // the same datasource is returned to ensure when consecutive calls
+ // during the process
+ // corresponds to the same datasource
+ String key = null;
+
+ key = modelName + "_" + datasourceid;
+
+ // if the datasourceid represents a group name, then use the group name
+ // so that all future request using that group name for a specified
+ // model
+ // will use the same datasource
+ if (modelToDatasourceMap.containsKey(key)) {
+ return modelToDatasourceMap.get(key);
+ }
+
+ if (useDS != null) {
+ String dsname = useDS.get(datasourceid);
+ if (dsname != null) {
+ ds = allDatasourcesMap.get(dsname);
+ if (ds == null) {
+ throw new QueryTestFailedException("Datasource name "
+ + dsname
+ + " was not found in the allDatasources map");
+
+ }
+ } else {
+ throw new QueryTestFailedException("Model:id " + modelName
+ + ":" + datasourceid
+ + " did not map to the usedatasources: "
+ + useDS.toString());
+
+ }
+
+ modelToDatasourceMap.put(key, ds);
+ return ds;
+
+ }
+
+ Iterator<DataSource> it = allDatasourcesMap.values().iterator();
+
+ // need to go thru all the datasources to know if any has already been
+ // assigned
+ // because the datasourceid passed in was a group name
+ while (it.hasNext()) {
+ DataSource checkit = it.next();
+
+ if (excludedDBTypes != null
+ && excludedDBTypes.contains(checkit.getDBType())) {
+ continue;
+ }
+
+ if (!assignedDataSources.contains(checkit.getName())) {
+ ds = checkit;
+ assignedDataSources.add(ds.getName());
+ break;
+ }
+
+ }
+
+ if (ds == null) {
+ int cnt = 0;
+ Iterator<String> itds = assignedDataSources.iterator();
+
+ // when all the datasources have been assigned, but a new model
+ // datasource id is
+ // passed in, need to reassign a previously assigned datasource
+ // This case will happen when more models are defined than there are
+ // defined datasources.
+ while (itds.hasNext()) {
+ String dsname = itds.next();
+
+ if (cnt == this.lastassigned) {
+
+ ds = allDatasourcesMap.get(dsname);
+
+ this.lastassigned++;
+ if (lastassigned >= assignedDataSources.size()) {
+ this.lastassigned = 0;
+ }
+
+ break;
+ }
+ }
+
+ }
+
+ if (ds == null) {
+ throw new QueryTestFailedException(
+ "Unable to assign a datasource for model:datasourceid "
+ + modelName + ":" + datasourceid);
+
+ }
+
+ modelToDatasourceMap.put(key, ds);
+ return ds;
+
+ }
+
+ public void cleanup() {
+
+ modelToDatasourceMap.clear();
+ unmappedds.clear();
+ assignedDataSources.clear();
+
+ useDS = null;
+ excludedDBTypes = null;
+
+ }
+
+ public static void main(String[] args) {
+ //NOTE: to run this test to validate the DataSourceMgr, do the following:
+ // --- need 3 datasources, Oracle, SqlServer and 1 other
+
+ ConfigPropertyLoader config = ConfigPropertyLoader.createInstance();
+
+ DataSourceFactory factory = new DataSourceFactory(config);
+
+ try {
+ if (factory.getDatasource("1", "model1") == null) {
+ throw new RuntimeException("No datasource was not found");
+ }
+
+
+ } catch (QueryTestFailedException e) {
+ e.printStackTrace();
+ }
+
+ factory.cleanup();
+
+
+ // the following verifies that order of "use" datasources is applied to request for datasources.
+ System.setProperty(ConfigPropertyNames.USE_DATASOURCES_PROP, "oracle,sqlserver");
+
+ config = ConfigPropertyLoader.createInstance();
+
+ factory = new DataSourceFactory(config);
+
+ try {
+
+ DataSource dsfind = factory.getDatasource("2", "model1");
+ if (dsfind == null) {
+ throw new RuntimeException("No datasource was not found as the 2nd datasource");
+
+ }
+
+ if (dsfind.getConnectorType() == null) {
+ throw new RuntimeException("Connector types was not defined");
+ }
+
+ if (!dsfind.getName().equalsIgnoreCase("sqlserver")) {
+ throw new RuntimeException("Sqlserver was not found as the 2nd datasource");
+
+ }
+
+ dsfind = factory.getDatasource("1", "model1");
+ if (dsfind == null) {
+ throw new RuntimeException("No datasource was not found as the 2nd datasource");
+
+ }
+ if (!dsfind.getName().equalsIgnoreCase("oracle")) {
+ throw new RuntimeException("Oracle was not found as the 2nd datasource");
+
+ }
+ System.out.println("Datasource :" + dsfind.getName() + " was found");
+
+
+ // the following test verifies that a sqlserver datasource is not
+ // returned (excluded)
+ factory.cleanup();
+
+
+
+ System.setProperty(ConfigPropertyNames.EXCLUDE_DATASBASE_TYPES_PROP, "sqlserver");
+
+ config = ConfigPropertyLoader.createInstance();
+
+
+ factory = new DataSourceFactory(config);
+
+
+ DataSource ds1 = factory.getDatasource("1", "model1");
+ if (ds1 == null) {
+ throw new RuntimeException("No 1st datasource was found");
+
+ }
+
+ DataSource ds2 = factory.getDatasource("2", "model1");
+ if (ds2 == null) {
+ throw new RuntimeException("No 2nd datasource was found");
+
+ }
+
+ DataSource reuse = factory.getDatasource("3", "model1");
+ if (reuse == ds1 || reuse == ds2) {
+
+ } else {
+ throw new RuntimeException("The process was not able to reassign an already used datasource");
+
+ }
+
+ } catch (QueryTestFailedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
Property changes on: trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 3 months
teiid SVN: r1495 - trunk/test-integration/db/src/main/java/org/teiid/test/util.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:03:33 -0400 (Wed, 30 Sep 2009)
New Revision: 1495
Added:
trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Added: trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java (rev 0)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java 2009-09-30 16:03:33 UTC (rev 1495)
@@ -0,0 +1,906 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * Copyright (c) 2000, 2008 IBM Corporation and others.
+ * All rights reserved.
+ * This code is made available under the terms of the Eclipse Public
+ * License, version 1.0.
+ */
+
+package org.teiid.test.util;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.regex.Pattern;
+
+/**
+ * This is a common place to put String utility methods.
+ */
+public final class StringUtil {
+
+// public interface Constants {
+// char CARRIAGE_RETURN_CHAR = '\r';
+// char LINE_FEED_CHAR = '\n';
+// char NEW_LINE_CHAR = LINE_FEED_CHAR;
+// char SPACE_CHAR = ' ';
+// char DOT_CHAR = '.';
+// char TAB_CHAR = '\t';
+//
+// String CARRIAGE_RETURN = String.valueOf(CARRIAGE_RETURN_CHAR);
+// String EMPTY_STRING = ""; //$NON-NLS-1$
+// String DBL_SPACE = " "; //$NON-NLS-1$
+// String LINE_FEED = String.valueOf(LINE_FEED_CHAR);
+// String NEW_LINE = String.valueOf(NEW_LINE_CHAR);
+// String SPACE = String.valueOf(SPACE_CHAR);
+// String DOT = String.valueOf(DOT_CHAR);
+// String TAB = String.valueOf(TAB_CHAR);
+//
+// String[] EMPTY_STRING_ARRAY = new String[0];
+//
+// // all patterns below copied from Eclipse's PatternConstructor class.
+// final Pattern PATTERN_BACK_SLASH = Pattern.compile("\\\\"); //$NON-NLS-1$
+// final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); //$NON-NLS-1$
+// final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
+// }
+//
+ /**
+ * The String "'"
+ */
+// public static final String SINGLE_QUOTE = "'"; //$NON-NLS-1$
+//
+// /**
+// * The name of the System property that specifies the string that should be used to separate
+// * lines. This property is a standard environment property that is usually set automatically.
+// */
+// public static final String LINE_SEPARATOR_PROPERTY_NAME = "line.separator"; //$NON-NLS-1$
+//
+// /**
+// * The String that should be used to separate lines; defaults to
+// * {@link #NEW_LINE}
+// */
+// public static final String LINE_SEPARATOR = System.getProperty(LINE_SEPARATOR_PROPERTY_NAME, Constants.NEW_LINE);
+//
+// public static final Comparator CASE_INSENSITIVE_ORDER = String.CASE_INSENSITIVE_ORDER;
+//
+// public static final Comparator CASE_SENSITIVE_ORDER = new Comparator() {
+// /**
+// * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
+// * @since 4.2
+// */
+// public int compare(Object o1, Object o2) {
+// if ( o1 == o2 ) {
+// return 0;
+// }
+// return ((String)o1).compareTo((String)o2);
+// }
+// };
+//
+// public static String getLineSeparator() {
+// return LINE_SEPARATOR;
+// }
+
+ /**
+ * Utility to return a string enclosed in ''.
+ * Creation date: (12/2/99 12:05:10 PM)
+ */
+// public static String enclosedInSingleQuotes(String aString) {
+// StringBuffer sb = new StringBuffer();
+// sb.append(SINGLE_QUOTE);
+// sb.append(aString);
+// sb.append(SINGLE_QUOTE);
+// return sb.toString();
+// }
+
+ public static String removeChars(final String value, final char[] chars) {
+ final StringBuffer result = new StringBuffer();
+ if (value != null && chars != null && chars.length > 0) {
+ final String removeChars = String.valueOf(chars);
+ for (int i = 0; i < value.length(); i++) {
+ final String character = value.substring(i, i + 1);
+ if (removeChars.indexOf(character) == -1) {
+ result.append(character);
+ }
+ }
+ } else {
+ result.append(value);
+ }
+ return result.toString();
+ }
+
+ /**
+ * Join string pieces and separate with a delimiter. Similar to the perl function of
+ * the same name. If strings or delimiter are null, null is returned. Otherwise, at
+ * least an empty string will be returned.
+ * @see #split
+ *
+ * @param strings String pieces to join
+ * @param delimiter Delimiter to put between string pieces
+ * @return One merged string
+ */
+// public static String join(List strings, String delimiter) {
+// if(strings == null || delimiter == null) {
+// return null;
+// }
+//
+// StringBuffer str = new StringBuffer();
+//
+// // This is the standard problem of not putting a delimiter after the last
+// // string piece but still handling the special cases. A typical way is to check every
+// // iteration if it is the last one and skip the delimiter - this is avoided by
+// // looping up to the last one, then appending just the last one.
+//
+// // First we loop through all but the last one (if there are at least 2) and
+// // put the piece and a delimiter after it. An iterator is used to walk the list.
+// int most = strings.size()-1;
+// if(strings.size() > 1) {
+// Iterator iter = strings.iterator();
+// for(int i=0; i<most; i++) {
+// str.append(iter.next());
+// str.append(delimiter);
+// }
+// }
+//
+// // If there is at least one element, put the last one on with no delimiter after.
+// if(strings.size() > 0) {
+// str.append(strings.get(most));
+// }
+//
+// return str.toString();
+// }
+//
+// /**
+// * Return a stringified version of the array.
+// * @param array the array
+// * @param delim the delimiter to use between array components
+// * @return the string form of the array
+// */
+// public static String toString( final Object[] array, final String delim ) {
+// if ( array == null ) {
+// return ""; //$NON-NLS-1$
+// }
+// if ( array.length == 0 ) {
+// return "[]"; //$NON-NLS-1$
+// }
+// final StringBuffer sb = new StringBuffer();
+// sb.append('[');
+// for (int i = 0; i < array.length; ++i) {
+// if ( i != 0 ) {
+// sb.append(delim);
+// }
+// sb.append(array[i]);
+// }
+// sb.append(']');
+// return sb.toString();
+// }
+//
+// /**
+// * Return a stringified version of the array, using a ',' as a delimiter
+// * @param array the array
+// * @return the string form of the array
+// * @see #toString(Object[], String)
+// */
+// public static String toString( final Object[] array ) {
+// return toString(array,","); //$NON-NLS-1$
+// }
+//
+// /**
+// * Split a string into pieces based on delimiters. Similar to the perl function of
+// * the same name. The delimiters are not included in the returned strings.
+// * @see #join
+// *
+// * @param str Full string
+// * @param splitter Characters to split on
+// * @return List of String pieces from full string
+// */
+// public static List split(String str, String splitter) {
+// StringTokenizer tokens = new StringTokenizer(str, splitter);
+// ArrayList l = new ArrayList(tokens.countTokens());
+// while(tokens.hasMoreTokens()) {
+// l.add(tokens.nextToken());
+// }
+// return l;
+// }
+//
+// /**
+// * Break a string into pieces based on matching the full delimiter string in the text.
+// * The delimiter is not included in the returned strings.
+// * @param target The text to break up.
+// * @param delimiter The sub-string which is used to break the target.
+// * @return List of String from the target.
+// */
+// public static List splitOnEntireString(String target, String delimiter) {
+// ArrayList result = new ArrayList();
+// if (delimiter.length() > 0) {
+// int index = 0;
+// int indexOfNextMatch = target.indexOf(delimiter);
+// while (indexOfNextMatch > -1) {
+// result.add(target.substring(index, indexOfNextMatch));
+// index = indexOfNextMatch + delimiter.length();
+// indexOfNextMatch = target.indexOf(delimiter, index);
+// }
+// if (index <= target.length()) {
+// result.add(target.substring(index));
+// }
+// } else {
+// result.add(target);
+// }
+// return result;
+// }
+//
+// /**
+// * Split a string into pieces based on delimiters preserving spaces in
+// * quoted substring as on element in the returned list. The delimiters are
+// * not included in the returned strings.
+// * @see #join
+// *
+// * @param str Full string
+// * @param splitter Characters to split on
+// * @return List of String pieces from full string
+// */
+// public static List splitPreservingQuotedSubstring(String str, String splitter) {
+// ArrayList l = new ArrayList();
+// StringTokenizer tokens = new StringTokenizer(str, splitter);
+// StringBuffer token = new StringBuffer();
+// while(tokens.hasMoreTokens()) {
+// token.setLength(0);
+// token.append(tokens.nextToken());
+// if ( token.charAt(0) == '"' ) {
+// token.deleteCharAt(0);
+// while ( tokens.hasMoreTokens() ) {
+// token.append(Constants.SPACE + tokens.nextToken());
+// if ( token.charAt(token.length() -1) == '"' ) {
+// token.deleteCharAt(token.length() - 1);
+// break;
+// }
+// }
+// }
+// l.add(token.toString().trim());
+// }
+// return l;
+// }
+//
+// /*
+// * Replace a single occurrence of the search string with the replace string
+// * in the source string. If any of the strings is null or the search string
+// * is zero length, the source string is returned.
+// * @param source the source string whose contents will be altered
+// * @param search the string to search for in source
+// * @param replace the string to substitute for search if present
+// * @return source string with the *first* occurrence of the search string
+// * replaced with the replace string
+// */
+// public static String replace(String source, String search, String replace) {
+// if (source != null && search != null && search.length() > 0 && replace != null) {
+// int start = source.indexOf(search);
+// if (start > -1) {
+// return new StringBuffer(source).replace(start, start + search.length(), replace).toString();
+// }
+// }
+// return source;
+// }
+//
+// /*
+// * Replace all occurrences of the search string with the replace string
+// * in the source string. If any of the strings is null or the search string
+// * is zero length, the source string is returned.
+// * @param source the source string whose contents will be altered
+// * @param search the string to search for in source
+// * @param replace the string to substitute for search if present
+// * @return source string with *all* occurrences of the search string
+// * replaced with the replace string
+// */
+// public static String replaceAll(String source, String search, String replace) {
+// if (source != null && search != null && search.length() > 0 && replace != null) {
+// int start = source.indexOf(search);
+// if (start > -1) {
+// StringBuffer newString = new StringBuffer(source);
+// replaceAll(newString, search, replace);
+// return newString.toString();
+// }
+// }
+// return source;
+// }
+//
+// public static void replaceAll(StringBuffer source, String search, String replace) {
+// if (source != null && search != null && search.length() > 0 && replace != null) {
+// int start = source.toString().indexOf(search);
+// while (start > -1) {
+// int end = start + search.length();
+// source.replace(start, end, replace);
+// start = source.toString().indexOf(search, start + replace.length());
+// }
+// }
+// }
+//
+// /**
+// * Simple static method to tuncate Strings to given length.
+// * @param in the string that may need tuncating.
+// * @param len the lenght that the string should be truncated to.
+// * @return a new String containing chars with length <= len or <code>null</code>
+// * if input String is <code>null</code>.
+// */
+// public static String truncString(String in, int len) {
+// String out = in;
+// if ( in != null && len > 0 && in.length() > len ) {
+// out = in.substring(0, len);
+// }
+// return out;
+// }
+//
+// /**
+// * Simple utility method to wrap a string by inserting line separators creating
+// * multiple lines each with length no greater than the user specified maximum.
+// * The method parses the given string into tokens using a space delimiter then
+// * reassembling the tokens into the resulting string while inserting separators
+// * when required. If the number of characters in a single token is greater
+// * than the specified maximum, the token will not be split but instead the
+// * maximum will be exceeded.
+// * @param str the string that may need tuncating.
+// * @param maxCharPerLine the max number of characters per line
+// * @return a new String containing line separators or the original string
+// * if its length was less than the maximum.
+// */
+// public static String wrap(String str, int maxCharPerLine) {
+// int strLength = str.length();
+// if (strLength > maxCharPerLine) {
+// StringBuffer sb = new StringBuffer(str.length()+(strLength/maxCharPerLine)+1);
+// strLength = 0;
+// List tokens = StringUtil.split(str,Constants.SPACE);
+// Iterator itr = tokens.iterator();
+// while (itr.hasNext()) {
+// String token = (String) itr.next();
+// if ( strLength+token.length() > maxCharPerLine ) {
+//// sb.append(getLineSeparator());
+// sb.append(Constants.NEW_LINE);
+// strLength = 0;
+// }
+// sb.append(token);
+// sb.append(Constants.SPACE);
+// strLength += token.length()+1;
+// }
+// return sb.toString();
+// }
+// return str;
+// }
+//
+// /**
+// * Return the tokens in a string in a list. This is particularly
+// * helpful if the tokens need to be processed in reverse order. In that case,
+// * a list iterator can be acquired from the list for reverse order traversal.
+// *
+// * @param str String to be tokenized
+// * @param delimiter Characters which are delimit tokens
+// * @return List of string tokens contained in the tokenized string
+// */
+// public static List getTokens(String str, String delimiter) {
+// ArrayList l = new ArrayList();
+// StringTokenizer tokens = new StringTokenizer(str, delimiter);
+// while(tokens.hasMoreTokens()) {
+// l.add(tokens.nextToken());
+// }
+// return l;
+// }
+//
+// /**
+// * Return the number of tokens in a string that are seperated by the delimiter.
+// *
+// * @param str String to be tokenized
+// * @param delimiter Characters which are delimit tokens
+// * @return Number of tokens seperated by the delimiter
+// */
+// public static int getTokenCount(String str, String delimiter) {
+// StringTokenizer tokens = new StringTokenizer(str, delimiter);
+// return tokens.countTokens();
+// }
+//
+// /**
+// * Return the number of occurrences of token string that occurs in input string.
+// * Note: token is case sensitive.
+// *
+// * @param input
+// * @param token
+// * @return int
+// */
+// public static int occurrences(String input, String token) {
+// int num = 0;
+// int index = input.indexOf(token);
+// while (index >= 0) {
+// num++;
+// index = input.indexOf(token, index+1);
+// }
+// return num;
+// }
+//
+// /**
+// * Return the last token in the string.
+// *
+// * @param str String to be tokenized
+// * @param delimiter Characters which are delimit tokens
+// * @return the last token contained in the tokenized string
+// */
+// public static String getLastToken(String str, String delimiter) {
+// if (str == null) {
+// return Constants.EMPTY_STRING;
+// }
+// int beginIndex = 0;
+// if (str.lastIndexOf(delimiter) > 0) {
+// beginIndex = str.lastIndexOf(delimiter)+1;
+// }
+// return str.substring(beginIndex,str.length());
+// }
+//
+//
+// /**
+// * Return the first token in the string.
+// *
+// * @param str String to be tokenized
+// * @param delimiter Characters which are delimit tokens
+// * @return the first token contained in the tokenized string
+// */
+// public static String getFirstToken(String str, String delimiter) {
+// if (str == null) {
+// return Constants.EMPTY_STRING;
+// }
+// int endIndex = str.indexOf(delimiter);
+// if (endIndex < 0) {
+// endIndex = str.length();
+// }
+// return str.substring(0,endIndex);
+// }
+//
+//
+// public static String computePluralForm(String str) {
+// return computePluralForm(str, Constants.EMPTY_STRING);
+// }
+//
+// public static String computePluralForm(String str, String defaultValue ) {
+// if ( str == null || str.length() == 0 ) {
+// return defaultValue;
+// }
+// String result = str;
+// if ( result.endsWith("es") ) { //$NON-NLS-1$
+// // do nothing
+// } else if ( result.endsWith("ss") || //$NON-NLS-1$
+// result.endsWith("x") || //$NON-NLS-1$
+// result.endsWith("ch") || //$NON-NLS-1$
+// result.endsWith("sh") ) { //$NON-NLS-1$
+// result = result + "es"; //$NON-NLS-1$
+// } else if ( result.endsWith("y") && ! ( //$NON-NLS-1$
+// result.endsWith("ay") || //$NON-NLS-1$
+// result.endsWith("ey") || //$NON-NLS-1$
+// result.endsWith("iy") || //$NON-NLS-1$
+// result.endsWith("oy") || //$NON-NLS-1$
+// result.endsWith("uy") || //$NON-NLS-1$
+// result.equalsIgnoreCase("any") ) ) { //$NON-NLS-1$
+// result = result.substring(0, result.length()-1) + "ies"; //$NON-NLS-1$
+// } else {
+// result += "s"; //$NON-NLS-1$
+// }
+// return result;
+// }
+//
+// public static String getStackTrace( final Throwable t ) {
+// final ByteArrayOutputStream bas = new ByteArrayOutputStream();
+// final PrintWriter pw = new PrintWriter(bas);
+// t.printStackTrace(pw);
+// pw.close();
+// return bas.toString();
+// }
+//
+// /**
+// * Returns whether the specified text represents a boolean value, i.e., whether it equals "true" or "false"
+// * (case-insensitive).
+// * @since 4.0
+// */
+// public static boolean isBoolean(final String text) {
+// return (Boolean.TRUE.toString().equalsIgnoreCase(text) || Boolean.FALSE.toString().equalsIgnoreCase(text));
+// }
+//
+// /**<p>
+// * Returns whether the specified text is either empty or null.
+// * </p>
+// * @param text The text to check; may be null;
+// * @return True if the specified text is either empty or null.
+// * @since 4.0
+// */
+// public static boolean isEmpty(final String text) {
+// return (text == null || text.length() == 0);
+// }
+//
+// /**
+// * Returns the index within this string of the first occurrence of the
+// * specified substring. The integer returned is the smallest value
+// * <i>k</i> such that:
+// * <blockquote><pre>
+// * this.startsWith(str, <i>k</i>)
+// * </pre></blockquote>
+// * is <code>true</code>.
+// *
+// * @param text any string.
+// * @param str any string.
+// * @return if the str argument occurs as a substring within text,
+// * then the index of the first character of the first
+// * such substring is returned; if it does not occur as a
+// * substring, <code>-1</code> is returned. If the text or
+// * str argument is null or empty then <code>-1</code> is returned.
+// */
+// public static int indexOfIgnoreCase(final String text, final String str) {
+// if (isEmpty(text)) {
+// return -1;
+// }
+// if (isEmpty(str)) {
+// return -1;
+// }
+// final String lowerText = text.toLowerCase();
+// final String lowerStr = str.toLowerCase();
+// return lowerText.indexOf(lowerStr);
+// }
+//
+// /**
+// * Tests if the string starts with the specified prefix.
+// *
+// * @param text the string to test.
+// * @param prefix the prefix.
+// * @return <code>true</code> if the character sequence represented by the
+// * argument is a prefix of the character sequence represented by
+// * this string; <code>false</code> otherwise.
+// * Note also that <code>true</code> will be returned if the
+// * prefix is an empty string or is equal to the text
+// * <code>String</code> object as determined by the
+// * {@link #equals(Object)} method. If the text or
+// * prefix argument is null <code>false</code> is returned.
+// * @since JDK1. 0
+// */
+// public static boolean startsWithIgnoreCase(final String text, final String prefix) {
+// if (isEmpty(text)) {
+// return false;
+// }
+// if (prefix == null) {
+// return false;
+// }
+// int textLength = text.length();
+// int prefixLength = prefix.length();
+// if (prefixLength == 0) {
+// return true;
+// }
+// if (prefixLength > textLength) {
+// return false;
+// }
+// char[] chArray = prefix.toCharArray();
+// for (int i = 0; i != chArray.length; ++i) {
+// char ch1 = chArray[i];
+// char ch2 = text.charAt(i);
+// if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2)) {
+// // continue
+// } else {
+// return false;
+// }
+// }
+// return true;
+// }
+//
+// /**
+// * Tests if the string ends with the specified suffix.
+// *
+// * @param text the string to test.
+// * @param suffix the suffix.
+// * @return <code>true</code> if the character sequence represented by the
+// * argument is a suffix of the character sequence represented by
+// * this object; <code>false</code> otherwise. Note that the
+// * result will be <code>true</code> if the suffix is the
+// * empty string or is equal to this <code>String</code> object
+// * as determined by the {@link #equals(Object)} method. If the text or
+// * suffix argument is null <code>false</code> is returned.
+// */
+// public static boolean endsWithIgnoreCase(final String text, final String suffix) {
+// if (isEmpty(text)) {
+// return false;
+// }
+// if (suffix == null) {
+// return false;
+// }
+// int textLength = text.length();
+// int suffixLength = suffix.length();
+// if (suffixLength == 0) {
+// return true;
+// }
+// if (suffixLength > textLength) {
+// return false;
+// }
+// int offset = textLength - suffixLength;
+// char[] chArray = suffix.toCharArray();
+// for (int i = 0; i != chArray.length; ++i) {
+// char ch1 = chArray[i];
+// char ch2 = text.charAt(offset + i);
+// if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2)) {
+// // continue
+// } else {
+// return false;
+// }
+// }
+// return true;
+// }
+//
+// /**
+// * Determine if the string passed in has all digits as its contents
+// * @param str
+// * @return true if digits; false otherwise
+// */
+// public static boolean isDigits(String str) {
+// for(int i=0; i<str.length(); i++) {
+// if(!StringUtil.isDigit(str.charAt(i))) {
+// return false;
+// }
+// }
+// return true;
+// }
+// //============================================================================================================================
+// // Constructors
+//
+// /**<p>
+// * Prevents instantiation.
+// * </p>
+// * @since 4.0
+// */
+// private StringUtil() {
+// }
+//
+// /*
+// * Converts user string to regular expres '*' and '?' to regEx variables.
+// * copied from eclipse's PatternConstructor
+// */
+// static String asRegEx(String pattern) {
+// // Replace \ with \\, * with .* and ? with .
+// // Quote remaining characters
+// String result1 = Constants.PATTERN_BACK_SLASH.matcher(pattern).replaceAll(
+// "\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
+// String result2 = Constants.PATTERN_STAR.matcher(result1).replaceAll(
+// "\\\\E.*\\\\Q"); //$NON-NLS-1$
+// String result3 = Constants.PATTERN_QUESTION.matcher(result2).replaceAll(
+// "\\\\E.\\\\Q"); //$NON-NLS-1$
+// return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
+// }
+//
+// /**
+// * Creates a regular expression pattern from the pattern string (which is
+// * our old 'StringMatcher' format). Copied from Eclipse's PatternConstructor class.
+// *
+// * @param pattern
+// * The search pattern
+// * @param isCaseSensitive
+// * Set to <code>true</code> to create a case insensitve pattern
+// * @return The created pattern
+// */
+// public static Pattern createPattern(String pattern, boolean isCaseSensitive) {
+// if (isCaseSensitive)
+// return Pattern.compile(asRegEx(pattern));
+// return Pattern.compile(asRegEx(pattern), Pattern.CASE_INSENSITIVE
+// | Pattern.UNICODE_CASE);
+// }
+//
+// /**
+// * Removes extraneous whitespace from a string. By it's nature, it will be trimmed also.
+// * @param raw
+// * @return
+// * @since 5.0
+// */
+// public static String collapseWhitespace(String raw) {
+// StringBuffer rv = new StringBuffer(raw.length());
+//
+// StringTokenizer izer = new StringTokenizer(raw, " "); //$NON-NLS-1$
+// while (izer.hasMoreTokens()) {
+// String tok = izer.nextToken();
+// // Added one last check here so we don't append a "space" on the end of the string
+// rv.append(tok);
+// if( izer.hasMoreTokens() ) {
+// rv.append(' ');
+// }
+// } // endwhile
+//
+// return rv.toString();
+// }
+//
+// /**
+// * If input == null OR input.length() < desiredLength, pad to desiredLength with spaces.
+// * If input.length() > desiredLength, chop at desiredLength.
+// * @param input Input text
+// * @param desiredLength Desired length
+// * @return
+// * @since 5.0
+// */
+// public static String toFixedLength(String input, int desiredLength) {
+// if(input == null) {
+// input = ""; //$NON-NLS-1$
+// }
+//
+// if(input.length() == desiredLength) {
+// return input;
+// }
+//
+// if(input.length() < desiredLength) {
+// StringBuffer str = new StringBuffer(input);
+// int needSpaces = desiredLength - input.length();
+// for(int i=0; i<needSpaces; i++) {
+// str.append(' ');
+// }
+// return str.toString();
+// }
+//
+// // Else too long - chop
+// return input.substring(0, desiredLength);
+// }
+//
+//
+// public static boolean isLetter(char c) {
+// return isBasicLatinLetter(c) || Character.isLetter(c);
+// }
+// public static boolean isDigit(char c) {
+// return isBasicLatinDigit(c) || Character.isDigit(c);
+// }
+// public static boolean isLetterOrDigit(char c) {
+// return isBasicLatinLetter(c) || isBasicLatinDigit(c) || Character.isLetterOrDigit(c);
+// }
+//
+// public static String toUpperCase(String str) {
+// String newStr = convertBasicLatinToUpper(str);
+// if (newStr == null) {
+// return str.toUpperCase();
+// }
+// return newStr;
+// }
+//
+// public static String toLowerCase(String str) {
+// String newStr = convertBasicLatinToLower(str);
+// if (newStr == null) {
+// return str.toLowerCase();
+// }
+// return newStr;
+// }
+//
+// /**
+// * Create a valid filename from the given String.
+// *
+// * @param str The String to convert to a valid filename.
+// * @param defaultName The default name to use if only special characters exist.
+// * @return String A valid filename.
+// */
+// public static String createFileName(String str) {
+//
+// /** Replace some special chars */
+// str = str.replaceAll(" \\| ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+// str = str.replaceAll(">", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+// str = str.replaceAll(": ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+// str = str.replaceAll(" ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+// str = str.replaceAll("\\?", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+// str = str.replaceAll("/", "_"); //$NON-NLS-1$ //$NON-NLS-2$
+//
+// /** If filename only contains of special chars */
+// if (str.matches("[_]+")) //$NON-NLS-1$
+// str = "file"; //$NON-NLS-1$
+//
+// return str;
+// }
+//
+//
+// /**
+// * Make the first letter uppercase
+// * @param str
+// * @return The string with the first letter being changed to uppercase
+// * @since 5.5
+// */
+// public static String firstLetterUppercase(String str) {
+// if(str == null || str.length() == 0) {
+// return null;
+// }
+// if(str.length() == 1) {
+// return str.toUpperCase();
+// }
+// return str.substring(0, 1).toUpperCase() + str.substring(1);
+// }
+//
+// private static String convertBasicLatinToUpper(String str) {
+// char[] chars = str.toCharArray();
+// for (int i = 0; i < chars.length; i++) {
+// if (isBasicLatinLowerCase(chars[i])) {
+// chars[i] = (char)('A' + (chars[i] - 'a'));
+// } else if (!isBasicLatinChar(chars[i])) {
+// return null;
+// }
+// }
+// return new String(chars);
+// }
+//
+// private static String convertBasicLatinToLower(String str) {
+// char[] chars = str.toCharArray();
+// for (int i = 0; i < chars.length; i++) {
+// if (isBasicLatinUpperCase(chars[i])) {
+// chars[i] = (char)('a' + (chars[i] - 'A'));
+// } else if (!isBasicLatinChar(chars[i])) {
+// return null;
+// }
+// }
+// return new String(chars);
+// }
+//
+// private static boolean isBasicLatinUpperCase(char c) {
+// return c >= 'A' && c <= 'Z';
+// }
+// private static boolean isBasicLatinLowerCase(char c) {
+// return c >= 'a' && c <= 'z';
+// }
+// private static boolean isBasicLatinLetter(char c) {
+// return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+// }
+// private static boolean isBasicLatinDigit(char c) {
+// return c >= '0' && c <= '9';
+// }
+// private static boolean isBasicLatinChar(char c) {
+// return c <= '\u007F';
+// }
+//
+// /**
+// * Convert the given value to specified type.
+// * @param value
+// * @param type
+// * @return
+// */
+// @SuppressWarnings("unchecked")
+// public static <T> T valueOf(String value, Class type){
+//
+// if(type == String.class) {
+// return (T) value;
+// }
+// else if(type == Boolean.class || type == Boolean.TYPE) {
+// return (T) Boolean.valueOf(value);
+// }
+// else if (type == Integer.class || type == Integer.TYPE) {
+// return (T) Integer.decode(value);
+// }
+// else if (type == Float.class || type == Float.TYPE) {
+// return (T) Float.valueOf(value);
+// }
+// else if (type == Double.class || type == Double.TYPE) {
+// return (T) Double.valueOf(value);
+// }
+// else if (type == Long.class || type == Long.TYPE) {
+// return (T) Long.decode(value);
+// }
+// else if (type == Short.class || type == Short.TYPE) {
+// return (T) Short.decode(value);
+// }
+// else if (type.isAssignableFrom(List.class)) {
+// return (T)new ArrayList<String>(Arrays.asList(value.split(","))); //$NON-NLS-1$
+// }
+// else if (type == Void.class) {
+// return null;
+// }
+// else if (type.isEnum()) {
+// return (T)Enum.valueOf(type, value);
+// }
+//
+// else if (type.isAssignableFrom(Map.class)) {
+// List<String> l = Arrays.asList(value.split(",")); //$NON-NLS-1$
+// Map m = new HashMap<String, String>();
+// for(String key: l) {
+// int index = key.indexOf('=');
+// if (index != -1) {
+// m.put(key.substring(0, index), key.substring(index+1));
+// }
+// }
+// return (T)m;
+// }
+//
+// throw new IllegalArgumentException("Conversion from String to "+ type.getName() + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$
+// }
+}
Property changes on: trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 3 months
teiid SVN: r1494 - trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:03:06 -0400 (Wed, 30 Sep 2009)
New Revision: 1494
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/JNDITransaction.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/LocalTransaction.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/TransactionFactory.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/XATransaction.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/JNDITransaction.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/JNDITransaction.java 2009-09-30 16:02:12 UTC (rev 1493)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/JNDITransaction.java 2009-09-30 16:03:06 UTC (rev 1494)
@@ -7,9 +7,10 @@
import javax.naming.InitialContext;
import javax.transaction.UserTransaction;
+import org.teiid.test.framework.ConfigPropertyLoader;
import org.teiid.test.framework.TransactionContainer;
import org.teiid.test.framework.TransactionQueryTest;
-import org.teiid.test.framework.connection.ConnectionStrategy;
+import org.teiid.test.framework.ConfigPropertyNames.CONNECTION_STRATEGY_PROPS;
import org.teiid.test.framework.exception.TransactionRuntimeException;
@@ -18,12 +19,12 @@
public class JNDITransaction extends TransactionContainer {
UserTransaction userTxn = null;
- public JNDITransaction() {
- super();
+ public JNDITransaction(ConfigPropertyLoader config) {
+ super(config);
}
protected void before(TransactionQueryTest test) {
- if (this.props.getProperty(ConnectionStrategy.JNDINAME_USERTXN) == null) {
+ if (this.props.getProperty(CONNECTION_STRATEGY_PROPS.JNDINAME_USERTXN) == null) {
throw new TransactionRuntimeException("No JNDI name found for the User Transaction to look up in application server");
}
@@ -31,7 +32,7 @@
// begin the transaction
InitialContext ctx = new InitialContext();
- this.userTxn = (UserTransaction)ctx.lookup(this.props.getProperty(ConnectionStrategy.JNDINAME_USERTXN));
+ this.userTxn = (UserTransaction)ctx.lookup(this.props.getProperty(CONNECTION_STRATEGY_PROPS.JNDINAME_USERTXN));
this.userTxn.begin();
} catch (Exception e) {
throw new TransactionRuntimeException(e);
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/LocalTransaction.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/LocalTransaction.java 2009-09-30 16:02:12 UTC (rev 1493)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/LocalTransaction.java 2009-09-30 16:03:06 UTC (rev 1494)
@@ -4,21 +4,24 @@
*/
package org.teiid.test.framework.transaction;
+
import java.sql.SQLException;
+import org.teiid.test.framework.ConfigPropertyLoader;
import org.teiid.test.framework.TransactionContainer;
import org.teiid.test.framework.TransactionQueryTest;
import org.teiid.test.framework.exception.TransactionRuntimeException;
+
/**
* A transaction which is user controlled.
*/
public class LocalTransaction extends TransactionContainer {
- public LocalTransaction() {
- super();
+ public LocalTransaction(ConfigPropertyLoader config) {
+ super(config);
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/TransactionFactory.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/TransactionFactory.java 2009-09-30 16:02:12 UTC (rev 1493)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/TransactionFactory.java 2009-09-30 16:03:06 UTC (rev 1494)
@@ -9,8 +9,6 @@
import org.teiid.test.framework.TransactionContainer;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.framework.connection.ConnectionStrategy;
-import org.teiid.test.framework.connection.ConnectionStrategyFactory;
@@ -21,35 +19,24 @@
private TransactionFactory(){}
- public static TransactionContainer create() throws QueryTestFailedException {
+ public static TransactionContainer create(ConfigPropertyLoader config) throws QueryTestFailedException {
TransactionContainer transacton = null;
-
- // load the configuration properties defined at this time for the test
- ConfigPropertyLoader.loadConfigurationProperties();
-
-
- // ConnectionStrategy connstrategy = ConnectionStrategyFactory.getInstance().getConnectionStrategy();
-
-// Properties props = ConfigPropertyLoader.getProperties();
-
-
- String type = ConfigPropertyLoader.getProperty(ConfigPropertyNames.TRANSACTION_TYPE);
- //connstrategy.getEnvironment().getProperty(ConfigPropertyNames.TRANSACTION_TYPE, ConfigPropertyNames.TRANSACTION_TYPES.LOCAL_TRANSACTION);
+
+ String type = config.getProperty(ConfigPropertyNames.TRANSACTION_TYPE);
if (type == null) {
type = ConfigPropertyNames.TRANSACTION_TYPES.LOCAL_TRANSACTION;
-// throw new RuntimeException("Property " + ConfigPropertyNames.TRANSACTION_TYPE + " was specified");
}
System.out.println("Create TransactionContainer: " + type);
if (type.equalsIgnoreCase(ConfigPropertyNames.TRANSACTION_TYPES.LOCAL_TRANSACTION)) {
- transacton = new LocalTransaction();
+ transacton = new LocalTransaction(config);
}
else if (type.equalsIgnoreCase(ConfigPropertyNames.TRANSACTION_TYPES.XATRANSACTION)) {
- transacton = new XATransaction();
+ transacton = new XATransaction(config);
}
else if (type.equalsIgnoreCase(ConfigPropertyNames.TRANSACTION_TYPES.JNDI_TRANSACTION)) {
- transacton = new JNDITransaction();
+ transacton = new JNDITransaction(config);
} else {
throw new TransactionRuntimeException("Invalid property value of " + type + " for " + ConfigPropertyNames.TRANSACTION_TYPE );
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/XATransaction.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/XATransaction.java 2009-09-30 16:02:12 UTC (rev 1493)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/transaction/XATransaction.java 2009-09-30 16:03:06 UTC (rev 1494)
@@ -9,6 +9,7 @@
import javax.sql.XAConnection;
import javax.transaction.xa.XAResource;
+import org.teiid.test.framework.ConfigPropertyLoader;
import org.teiid.test.framework.TransactionContainer;
import org.teiid.test.framework.TransactionQueryTest;
import org.teiid.test.framework.exception.QueryTestFailedException;
@@ -20,8 +21,8 @@
private static Random RANDOM = new Random();
private MMXid xid;
- public XATransaction() {
- super();
+ public XATransaction(ConfigPropertyLoader config) {
+ super(config);
}
protected void before(TransactionQueryTest test) {
15 years, 3 months
teiid SVN: r1493 - trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection.
by teiid-commits@lists.jboss.org
Author: vhalbert(a)redhat.com
Date: 2009-09-30 12:02:12 -0400 (Wed, 30 Sep 2009)
New Revision: 1493
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategy.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionUtil.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DataSourceConnection.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DriverConnection.java
trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/JEEConnection.java
Log:
Teiid 773 - changed the following:
- the testcase will not use system property to pass in overrides/additions to the loaded config.properties file. Now will use an addProperty() method provided on the abstract testcase that will apply the properties per test.
- remove the datasource_mapping.xml. There is no need to distinquish between xa and nonxa connector types. The connector type will be specified in the connection.properties file.
- if using the -DuserDataSources property to control datasource, it will imply order based on whats specified. The config.properties file will now map the model to order (i.e., pm1:1), where this order determines which datasource it will correspond to based on the userDataSources property. This mapping is done so that the nightly testing process can control which datasources are being used and can ensure retestability.
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategy.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategy.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategy.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -20,36 +20,28 @@
import org.teiid.adminapi.AdminOptions;
import org.teiid.adminapi.Model;
import org.teiid.adminapi.VDB;
+import org.teiid.test.framework.ConfigPropertyNames.CONNECTION_STRATEGY_PROPS;
import org.teiid.test.framework.datasource.DataSource;
-import org.teiid.test.framework.datasource.DataSourceMgr;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
-import com.metamatrix.jdbc.api.ExecutionProperties;
-
-
public abstract class ConnectionStrategy {
- public static final String JNDINAME_USERTXN = "usertxn-jndiname"; //$NON-NLS-1$
-
- public static final String PROCESS_BATCH = "process-batch"; //$NON-NLS-1$
- public static final String CONNECTOR_BATCH = "connector-batch"; //$NON-NLS-1$
+ private Map<String, ConnectionStrategy> driversources = null;
+ private Map<String, ConnectionStrategy> datasourcesources = null;
+ private Map<String, ConnectionStrategy> jeesources = null;
- public static final String AUTOCOMMIT = "autocommit"; //$NON-NLS-1$
- public static final String TXN_AUTO_WRAP = ExecutionProperties.PROP_TXN_AUTO_WRAP;
+ private Map<String, DataSource> datasources = null;
- public static final String FETCH_SIZE = ExecutionProperties.PROP_FETCH_SIZE;
+ private DataSourceFactory dsFactory;
- public static final String EXEC_IN_BATCH = "execute.in.batch"; //$NON-NLS-1$
-
- private Map<String, DataSource> datasources = null;
-
-
- public ConnectionStrategy(Properties props) throws QueryTestFailedException {
+ public ConnectionStrategy(Properties props, DataSourceFactory dsFactory) throws QueryTestFailedException {
this.env = props;
+ this.dsFactory = dsFactory;
}
@@ -69,8 +61,37 @@
*
* @since
*/
- public abstract void shutdown();
+ public void shutdown() {
+ if (driversources != null) {
+ shutDownSources(driversources);
+ driversources = null;
+ }
+
+ if (datasourcesources != null) {
+ shutDownSources(datasourcesources);
+ datasourcesources = null;
+ }
+
+ if (jeesources != null) {
+ shutDownSources(jeesources);
+ jeesources = null;
+ }
+ }
+
+ private void shutDownSources(Map<String, ConnectionStrategy> sources) {
+ for (Iterator it=sources.keySet().iterator(); it.hasNext(); ){
+ ConnectionStrategy cs = sources.get(it.next());
+ try {
+ cs.shutdown();
+ } catch (Exception e) {
+
+ }
+
+ }
+ sources.clear();
+ }
+
public Connection getAdminConnection() throws QueryTestFailedException{
return null;
}
@@ -121,7 +142,7 @@
datasources = new HashMap<String, DataSource>(3);
- String ac = this.env.getProperty(AUTOCOMMIT, "true");
+ String ac = this.env.getProperty(CONNECTION_STRATEGY_PROPS.AUTOCOMMIT, "true");
this.autoCommit = Boolean.getBoolean(ac);
com.metamatrix.jdbc.api.Connection c =null;
@@ -193,7 +214,7 @@
useName = mappedName;
}
- org.teiid.test.framework.datasource.DataSource ds = DataSourceMgr.getInstance().getDatasource(useName, m.getName());
+ org.teiid.test.framework.datasource.DataSource ds = this.dsFactory.getDatasource(useName, m.getName());
if (ds != null) {
datasources.put(m.getName(), ds);
@@ -222,6 +243,70 @@
}
+
+ public synchronized ConnectionStrategy createDriverStrategy(String identifier, Properties props) throws QueryTestFailedException {
+ if (driversources == null) {
+ driversources = new HashMap<String, ConnectionStrategy>();
+ }
+
+ if (identifier == null) {
+ return new DriverConnection(props, dsFactory);
+ }
+
+ ConnectionStrategy strategy = null;
+ if (driversources.containsKey(identifier)) {
+ strategy = driversources.get(identifier);
+ } else {
+ strategy = new DriverConnection(props, dsFactory);
+ driversources.put(identifier, strategy);
+ }
+
+ return strategy;
+
+ }
+
+ public synchronized ConnectionStrategy createDataSourceStrategy(String identifier, Properties props) throws QueryTestFailedException {
+ if (datasourcesources == null) {
+ datasourcesources = new HashMap<String, ConnectionStrategy>();
+ }
+
+ if (identifier == null) {
+ return new DataSourceConnection(props, dsFactory);
+ }
+
+ ConnectionStrategy strategy = null;
+ if (datasourcesources.containsKey(identifier)) {
+ strategy = datasourcesources.get(identifier);
+ } else {
+ strategy = new DataSourceConnection(props, dsFactory);
+ datasourcesources.put(identifier, strategy);
+ }
+
+ return strategy;
+
+ }
+
+ public synchronized ConnectionStrategy createJEEStrategy(String identifier, Properties props) throws QueryTestFailedException {
+ if (jeesources == null) {
+ jeesources = new HashMap<String, ConnectionStrategy>();
+ }
+
+ if (identifier == null) {
+ return new JEEConnection(props, dsFactory);
+ }
+
+ ConnectionStrategy strategy = null;
+ if (jeesources.containsKey(identifier)) {
+ strategy = jeesources.get(identifier);
+ } else {
+ strategy = new JEEConnection(props, dsFactory);
+ jeesources.put(identifier, strategy);
+ }
+
+ return strategy;
+
+ }
+
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionStrategyFactory.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -4,102 +4,27 @@
*/
package org.teiid.test.framework.connection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
import java.util.Properties;
import org.teiid.test.framework.ConfigPropertyLoader;
import org.teiid.test.framework.ConfigPropertyNames;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
+/**
+ * The ConnectionStrategyFactory is responsible for creating a connection strategy that is to be used to provide the type of
+ * connection.
+ * @author vanhalbert
+ *
+ */
public class ConnectionStrategyFactory {
- private static ConnectionStrategyFactory _instance = null;
- /**
- * this strategy represents the connection strategy used to connect to Teiid
- * and is based on the properties loaded by the {@link ConfigPropertyLoader}
- */
- private ConnectionStrategy strategy = null;
- private Map<String, ConnectionStrategy> driversources = null;
- private Map<String, ConnectionStrategy> datasourcesources = null;
- private Map<String, ConnectionStrategy> jeesources = null;
-
-
- private ConnectionStrategyFactory(){
- }
-
- public static synchronized ConnectionStrategyFactory getInstance() {
- if (_instance == null) {
- _instance = new ConnectionStrategyFactory();
- }
- return _instance;
- }
-
- public static synchronized void destroyInstance() {
- if (_instance != null) {
- _instance.shutdown();
-
- _instance = null;
- }
- }
-
- private void shutdown() {
- ConfigPropertyLoader.cleanup();
-
- if (driversources != null) {
- shutDownSources(driversources);
- driversources = null;
- }
-
- if (datasourcesources != null) {
- shutDownSources(datasourcesources);
- datasourcesources = null;
- }
-
- if (jeesources != null) {
- shutDownSources(jeesources);
- jeesources = null;
- }
-
- try {
- strategy.shutdown();
- } catch (Exception e) {
-
- } finally {
- strategy = null;
- }
-
- }
-
- private void shutDownSources(Map<String, ConnectionStrategy> sources) {
- for (Iterator it=sources.keySet().iterator(); it.hasNext(); ){
- ConnectionStrategy cs = sources.get(it.next());
- try {
- cs.shutdown();
- } catch (Exception e) {
-
- }
-
- }
- sources.clear();
-
- }
-
- public synchronized ConnectionStrategy getConnectionStrategy() throws QueryTestFailedException {
- if (strategy == null) {
- this.strategy = create(ConfigPropertyLoader.getProperties());
- }
- return this.strategy;
- }
-
-
- private ConnectionStrategy create(Properties props) throws QueryTestFailedException {
-
+ public static ConnectionStrategy createConnectionStrategy(ConfigPropertyLoader configprops, DataSourceFactory dsFactory) throws QueryTestFailedException {
ConnectionStrategy strategy = null;
-
+ Properties props = configprops.getProperties();
+
String type = props.getProperty(ConfigPropertyNames.CONNECTION_TYPE, ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION);
if (type == null) {
throw new RuntimeException("Property " + ConfigPropertyNames.CONNECTION_TYPE + " was specified");
@@ -107,15 +32,15 @@
if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DRIVER_CONNECTION)) {
// pass in null to create new strategy
- strategy = createDriverStrategy(null, props);
+ strategy = new DriverConnection(props, dsFactory);
System.out.println("Created Driver Strategy");
}
else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.DATASOURCE_CONNECTION)) {
- strategy = createDataSourceStrategy(null, props);
+ strategy = new DataSourceConnection(props, dsFactory);
System.out.println("Created DataSource Strategy");
}
else if (type.equalsIgnoreCase(ConfigPropertyNames.CONNECTION_TYPES.JNDI_CONNECTION)) {
- strategy = createJEEStrategy(null, props);
+ strategy = new JEEConnection(props, dsFactory);
System.out.println("Created JEE Strategy");
}
@@ -126,75 +51,6 @@
// direct connections to the datasource use the static call directly to create strategy and don't need to configure
strategy.configure();
return strategy;
- }
-
- public synchronized ConnectionStrategy createDriverStrategy(String identifier, Properties props) throws QueryTestFailedException {
- if (driversources == null) {
- driversources = new HashMap<String, ConnectionStrategy>();
- }
-
- if (identifier == null) {
- return new DriverConnection(props);
- }
-
- ConnectionStrategy strategy = null;
- if (driversources.containsKey(identifier)) {
- strategy = driversources.get(identifier);
- } else {
- strategy = new DriverConnection(props);
- driversources.put(identifier, strategy);
- }
-
- return strategy;
-
- }
-
- public synchronized ConnectionStrategy createDataSourceStrategy(String identifier, Properties props) throws QueryTestFailedException {
- if (datasourcesources == null) {
- datasourcesources = new HashMap<String, ConnectionStrategy>();
- }
-
- if (identifier == null) {
- return new DataSourceConnection(props);
- }
-
- ConnectionStrategy strategy = null;
- if (datasourcesources.containsKey(identifier)) {
- strategy = datasourcesources.get(identifier);
- } else {
- strategy = new DataSourceConnection(props);
- datasourcesources.put(identifier, strategy);
- }
-
- return strategy;
-
- }
-
- public synchronized ConnectionStrategy createJEEStrategy(String identifier, Properties props) throws QueryTestFailedException {
- if (jeesources == null) {
- jeesources = new HashMap<String, ConnectionStrategy>();
- }
-
- if (identifier == null) {
- return new JEEConnection(props);
- }
-
- ConnectionStrategy strategy = null;
- if (jeesources.containsKey(identifier)) {
- strategy = jeesources.get(identifier);
- } else {
- strategy = new JEEConnection(props);
- jeesources.put(identifier, strategy);
- }
-
- return strategy;
-
- }
-
-
-// public static void main(String[] args) {
-// ConnectionStrategyFactory cf = ConnectionStrategyFactory.getInstance();
-//
-// }
-
+
+ }
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionUtil.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionUtil.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/ConnectionUtil.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -11,7 +11,7 @@
// identifier should be the model name that is identfied in the config properties
public class ConnectionUtil {
- public static final Connection getConnection(String identifier, Map<String, DataSource> datasources) throws QueryTestFailedException {
+ public static final Connection getConnection(String identifier, Map<String, DataSource> datasources, ConnectionStrategy connstrategy) throws QueryTestFailedException {
DataSource ds = null;
if (identifier != null) {
ds = datasources.get(identifier);
@@ -22,7 +22,7 @@
}
- Connection conn = ConnectionStrategyFactory.getInstance().createDriverStrategy(identifier,
+ Connection conn = connstrategy.createDriverStrategy(identifier,
ds.getProperties()).getConnection();
// force autocommit back to true, just in case the last user didnt
try {
@@ -35,7 +35,7 @@
}
- public static final XAConnection getXAConnection(String identifier, Map<String, DataSource> datasources) throws QueryTestFailedException {
+ public static final XAConnection getXAConnection(String identifier, Map<String, DataSource> datasources, ConnectionStrategy connstrategy) throws QueryTestFailedException {
DataSource ds = null;
if (identifier != null) {
ds = datasources.get(identifier);
@@ -46,7 +46,7 @@
}
- return ConnectionStrategyFactory.getInstance().createDataSourceStrategy(
+ return connstrategy.createDataSourceStrategy(
identifier, ds.getProperties()).getXAConnection();
}
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DataSourceConnection.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DataSourceConnection.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DataSourceConnection.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -13,6 +13,7 @@
import org.teiid.connector.jdbc.JDBCPropertyNames;
import org.teiid.jdbc.TeiidDataSource;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
@@ -33,14 +34,12 @@
// driver class
public static final String DS_DRIVER = "driver"; //$NON-NLS-1$
- public static final String DS_SERVERNAME = "servername"; //$NON-NLS-1$
- public static final String DS_SERVERPORT = "portnumber"; //$NON-NLS-1$
+ public static final String DS_SERVERNAME = "ServerName"; //$NON-NLS-1$
+ public static final String DS_SERVERPORT = "PortNumber"; //$NON-NLS-1$
public static final String DS_JNDINAME = "ds-jndiname"; //$NON-NLS-1$
- public static final String DS_DATABASENAME = "databasename"; //$NON-NLS-1$
+ public static final String DS_DATABASENAME = "DatabaseName"; //$NON-NLS-1$
public static final String DS_APPLICATION_NAME = "application-name"; //$NON-NLS-1$
- // public static final String JNDINAME_USERTXN = "usertxn-jndiname"; //$NON-NLS-1$
-
private String driver = null;
private String username = null;
private String pwd = null;
@@ -51,9 +50,9 @@
private XAConnection xaConnection;
- public DataSourceConnection(Properties props)
+ public DataSourceConnection(Properties props, DataSourceFactory dsFactory)
throws QueryTestFailedException {
- super(props);
+ super(props, dsFactory);
}
public void validate() {
@@ -73,8 +72,8 @@
this.applName = this.getEnvironment().getProperty(DS_APPLICATION_NAME);
- driver = this.getEnvironment().getProperty(DS_DRIVER);
- if (driver == null || driver.length() == 0) {
+ this.driver = this.getEnvironment().getProperty(DS_DRIVER);
+ if (this.driver == null || this.driver.length() == 0) {
throw new TransactionRuntimeException("Property " + DS_DRIVER
+ " was not specified");
}
@@ -142,6 +141,7 @@
}
public void shutdown() {
+ super.shutdown();
try {
if (this.xaConnection != null) {
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DriverConnection.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DriverConnection.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/DriverConnection.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -10,6 +10,7 @@
import java.util.Properties;
import org.teiid.connector.jdbc.JDBCPropertyNames;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
@@ -43,8 +44,8 @@
private Connection connection;
- public DriverConnection(Properties props) throws QueryTestFailedException {
- super(props);
+ public DriverConnection(Properties props, DataSourceFactory dsFactory) throws QueryTestFailedException {
+ super(props, dsFactory);
validate();
}
@@ -128,6 +129,7 @@
}
public void shutdown() {
+ super.shutdown();
if (this.connection != null) {
try {
this.connection.close();
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/JEEConnection.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/JEEConnection.java 2009-09-29 20:44:35 UTC (rev 1492)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/connection/JEEConnection.java 2009-09-30 16:02:12 UTC (rev 1493)
@@ -10,6 +10,7 @@
import javax.naming.InitialContext;
import javax.sql.DataSource;
+import org.teiid.test.framework.datasource.DataSourceFactory;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
@@ -26,8 +27,8 @@
private String jndi_name = null;
- public JEEConnection(Properties props) throws QueryTestFailedException {
- super(props);
+ public JEEConnection(Properties props, DataSourceFactory dsFactory) throws QueryTestFailedException {
+ super(props, dsFactory);
}
public Connection getConnection() throws QueryTestFailedException {
@@ -53,6 +54,7 @@
}
public void shutdown() {
+ super.shutdown();
// no connection management here; app server takes care of these..
}
15 years, 3 months
teiid SVN: r1492 - in trunk: common-internal/src/main/java/com/metamatrix/platform/vm and 14 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2009-09-29 16:44:35 -0400 (Tue, 29 Sep 2009)
New Revision: 1492
Added:
trunk/runtime/src/main/java/org/teiid/transport/SocketListenerStats.java
Removed:
trunk/common-internal/src/main/java/com/metamatrix/platform/service/
trunk/common-internal/src/main/java/com/metamatrix/platform/vm/controller/
trunk/common-internal/src/main/java/com/metamatrix/vdb/edit/
trunk/engine/src/main/java/com/metamatrix/common/application/Application.java
trunk/engine/src/main/java/com/metamatrix/dqp/ResourceFinder.java
Modified:
trunk/engine/src/main/java/com/metamatrix/common/application/ApplicationEnvironment.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCollapseSource.java
trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
trunk/engine/src/test/java/com/metamatrix/dqp/config/TestDQPLauncher.java
trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManagerImpl.java
trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
trunk/runtime/src/main/java/com/metamatrix/jdbc/EmbeddedConnectionFactoryImpl.java
trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java
trunk/runtime/src/main/java/org/teiid/transport/SocketTransport.java
trunk/runtime/src/test/java/com/metamatrix/dqp/embedded/services/TestEmbeddedVDBService.java
trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java
trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java
Log:
TEIID-286: moving socketlistenerstats, removing ResourceFinder and the Application class.
Deleted: trunk/engine/src/main/java/com/metamatrix/common/application/Application.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/application/Application.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/com/metamatrix/common/application/Application.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -1,72 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.common.application;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import com.metamatrix.common.CommonPlugin;
-import com.metamatrix.common.application.exception.ApplicationInitializationException;
-import com.metamatrix.common.application.exception.ApplicationLifecycleException;
-
-/**
- */
-public class Application {
-
- protected ApplicationEnvironment environment = new ApplicationEnvironment();
- private ArrayList<String> installedServices = new ArrayList<String>();
-
- /*
- * @see com.metamatrix.common.application.Application#installService(com.metamatrix.common.application.ApplicationService)
- */
- public final void installService(String type, ApplicationService service) throws ApplicationInitializationException {
- if(service == null) {
- return;
- }
-
- try {
- service.start(this.environment);
- this.environment.bindService(type, service);
- installedServices.add(0, type);
- } catch(ApplicationLifecycleException e) {
- throw new ApplicationInitializationException(e, CommonPlugin.Util.getString("BasicApplication.Failed_while_installing_service_of_type__1") + type); //$NON-NLS-1$
- }
- }
-
- public ApplicationEnvironment getEnvironment() {
- return this.environment;
- }
- /**
- * @see com.metamatrix.common.application.Application#stop()
- */
- public void stop() throws ApplicationLifecycleException {
- for (Iterator i = installedServices.iterator(); i.hasNext();) {
- String type = (String)i.next();
- ApplicationService service = environment.findService(type);
- environment.unbindService(type);
- service.stop();
- i.remove();
- }
- }
-
-}
Modified: trunk/engine/src/main/java/com/metamatrix/common/application/ApplicationEnvironment.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/common/application/ApplicationEnvironment.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/com/metamatrix/common/application/ApplicationEnvironment.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -22,9 +22,14 @@
package com.metamatrix.common.application;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Map;
+import com.metamatrix.cache.CacheFactory;
+import com.metamatrix.common.CommonPlugin;
+import com.metamatrix.common.application.exception.ApplicationInitializationException;
+import com.metamatrix.common.application.exception.ApplicationLifecycleException;
+
/**
* The environment is available internally to the application as a means
* of finding application services of a particular type or to retrieve
@@ -32,7 +37,13 @@
*/
public class ApplicationEnvironment {
- private Map<String, ApplicationService> services = new HashMap<String, ApplicationService>();
+ private LinkedHashMap<String, ApplicationService> services = new LinkedHashMap<String, ApplicationService>();
+
+ private CacheFactory cache;
+
+ public ApplicationEnvironment() {
+
+ }
/*
* @see com.metamatrix.common.application.ApplicationEnvironment#bindService(java.lang.String, com.metamatrix.common.application.ApplicationService)
@@ -41,18 +52,42 @@
this.services.put(type, service);
}
+ public ApplicationService findService(String type) {
+ return this.services.get(type);
+ }
+
+ public CacheFactory getCacheFactory() {
+ return cache;
+ }
+
+ public void setCacheFactory(CacheFactory cache) {
+ this.cache = cache;
+ }
+
/*
- * @see com.metamatrix.common.application.ApplicationEnvironment#unbindService(java.lang.String)
+ * @see com.metamatrix.common.application.Application#installService(com.metamatrix.common.application.ApplicationService)
*/
- public void unbindService(String type) {
- this.services.remove(type);
+ public final void installService(String type, ApplicationService service) throws ApplicationInitializationException {
+ if(service == null) {
+ return;
+ }
+
+ try {
+ service.start(this);
+ this.bindService(type, service);
+ } catch(ApplicationLifecycleException e) {
+ throw new ApplicationInitializationException(e, CommonPlugin.Util.getString("BasicApplication.Failed_while_installing_service_of_type__1") + type); //$NON-NLS-1$
+ }
}
- /*
- * @see com.metamatrix.common.application.ApplicationEnvironment#findService(java.lang.String)
+ /**
+ * @see com.metamatrix.common.application.Application#stop()
*/
- public ApplicationService findService(String type) {
- return this.services.get(type);
+ public void stop() throws ApplicationLifecycleException {
+ for (Map.Entry<String, ApplicationService> entry : services.entrySet()) {
+ entry.getValue().stop();
+ }
+ services.clear();
}
}
Deleted: trunk/engine/src/main/java/com/metamatrix/dqp/ResourceFinder.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/dqp/ResourceFinder.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/com/metamatrix/dqp/ResourceFinder.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -1,42 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.dqp;
-
-
-import com.google.inject.Injector;
-import com.metamatrix.cache.CacheFactory;
-
-public class ResourceFinder {
- protected static Injector injector;
-
- public static CacheFactory getCacheFactory() {
- if (injector == null) {
- throw new IllegalStateException();
- }
- return injector.getInstance(CacheFactory.class);
- }
-
- public static void setInjector(Injector i) {
- injector = i;
- }
-}
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCollapseSource.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCollapseSource.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RuleCollapseSource.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -434,17 +434,11 @@
List clauses = from.getClauses();
FromClause rootClause = (FromClause) clauses.get(0);
- // If only one group, this is as good as we can do
- if(rootClause instanceof UnaryFromClause) {
- return;
- }
-
// If all joins are inner joins, move criteria to WHERE and make
// FROM a list of groups instead of a tree of JoinPredicates
if(! hasOuterJoins(rootClause)) {
from.setClauses(new ArrayList());
shredJoinTree(rootClause, query);
-
} // else leave as is
}
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/datamgr/impl/ConnectorManager.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -73,7 +73,6 @@
import com.metamatrix.core.util.ReflectionHelper;
import com.metamatrix.core.util.StringUtil;
import com.metamatrix.dqp.DQPPlugin;
-import com.metamatrix.dqp.ResourceFinder;
import com.metamatrix.dqp.internal.datamgr.ConnectorID;
import com.metamatrix.dqp.message.AtomicRequestID;
import com.metamatrix.dqp.message.AtomicRequestMessage;
@@ -356,7 +355,7 @@
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_MAX_SIZE, props.getProperty(ConnectorPropertyNames.MAX_RESULTSET_CACHE_SIZE, DEFAULT_MAX_RESULTSET_CACHE_SIZE));
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_MAX_AGE, props.getProperty(ConnectorPropertyNames.MAX_RESULTSET_CACHE_AGE, DEFAULT_MAX_RESULTSET_CACHE_AGE));
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_SCOPE, props.getProperty(ConnectorPropertyNames.RESULTSET_CACHE_SCOPE, ResultSetCache.RS_CACHE_SCOPE_VDB));
- this.rsCache = createResultSetCache(rsCacheProps);
+ this.rsCache = new ResultSetCache(rsCacheProps, env.getCacheFactory());
}
this.workItemFactory = new ConnectorWorkItemFactory(this, this.rsCache, synchWorkers);
this.state = ConnectorStatus.OPEN;
@@ -479,10 +478,6 @@
return new ConnectorWrapper(c);
}
- protected ResultSetCache createResultSetCache(Properties rsCacheProps) {
- return new ResultSetCache(rsCacheProps, ResourceFinder.getCacheFactory());
- }
-
/**
* Stop this connector.
*/
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -44,11 +44,12 @@
import org.teiid.dqp.internal.cache.ResultSetCache;
import org.teiid.dqp.internal.cache.ResultSetCacheUtil;
+import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.metamatrix.api.exception.MetaMatrixComponentException;
import com.metamatrix.api.exception.MetaMatrixProcessingException;
import com.metamatrix.api.exception.query.QueryMetadataException;
-import com.metamatrix.common.application.Application;
+import com.metamatrix.cache.CacheFactory;
import com.metamatrix.common.application.ApplicationEnvironment;
import com.metamatrix.common.application.ApplicationService;
import com.metamatrix.common.application.DQPConfigSource;
@@ -67,7 +68,6 @@
import com.metamatrix.core.log.MessageLevel;
import com.metamatrix.core.util.LRUCache;
import com.metamatrix.dqp.DQPPlugin;
-import com.metamatrix.dqp.ResourceFinder;
import com.metamatrix.dqp.client.ClientSideDQP;
import com.metamatrix.dqp.client.MetadataResult;
import com.metamatrix.dqp.client.ResultsFuture;
@@ -99,7 +99,7 @@
* Implements the core DQP processing.
*/
@Singleton
-public class DQPCore extends Application implements ClientSideDQP {
+public class DQPCore implements ClientSideDQP {
static class ConnectorCapabilitiesCache {
@@ -188,12 +188,14 @@
private Map<String, ClientState> clientState = Collections.synchronizedMap(new HashMap<String, ClientState>());
private DQPContextCache contextCache;
private ServiceLoader loader = new ServiceLoader();
+ private CacheFactory cacheFactory;
+
+ private ApplicationEnvironment environment = new ApplicationEnvironment();
/**
* perform a full shutdown and wait for 10 seconds for all threads to finish
* @throws ApplicationLifecycleException
*/
- @Override
public void stop() throws ApplicationLifecycleException {
LogManager.logDetail(LogConstants.CTX_DQP, "Stopping the DQP"); //$NON-NLS-1$
processWorkerPool.shutdownNow();
@@ -202,7 +204,11 @@
} catch (InterruptedException e) {
}
contextCache.shutdown();
- super.stop();
+ this.environment.stop();
+
+ if (cacheFactory != null) {
+ cacheFactory.destroy();
+ }
}
/**
@@ -282,7 +288,7 @@
request = new Request();
}
ClientState state = this.getClientState(workContext.getConnectionID(), true);
- request.initialize(requestMsg, getEnvironment(), bufferManager,
+ request.initialize(requestMsg, environment, bufferManager,
dataTierMgr, vdbCapabilties, transactionService,
processorDebugAllowed, state.tempTableStoreImpl,
workContext, chunkSize);
@@ -636,11 +642,11 @@
}
appService.initialize(configSource.getProperties());
- installService(serviceName, appService);
+ this.environment.installService(serviceName, appService);
LogManager.logInfo(LogConstants.CTX_DQP, DQPPlugin.Util.getString("DQPLauncher.InstallService_ServiceInstalled", serviceName)); //$NON-NLS-1$
}
- ConfigurationService cs = (ConfigurationService)this.getEnvironment().findService(DQPServiceNames.CONFIGURATION_SERVICE);
+ ConfigurationService cs = (ConfigurationService)this.environment.findService(DQPServiceNames.CONFIGURATION_SERVICE);
Properties p = configSource.getProperties();
if (cs != null) {
p = cs.getSystemProperties();
@@ -650,8 +656,6 @@
public void start(Properties props) {
- ApplicationEnvironment env = this.getEnvironment();
-
PropertiesUtils.setBeanProperties(this, props, null);
this.processorTimeslice = PropertiesUtils.getIntProperty(props, DQPEmbeddedProperties.PROCESS_TIMESLICE, DEFAULT_PROCESSOR_TIMESLICE);
@@ -669,7 +673,7 @@
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_MAX_SIZE, props.getProperty(DQPEmbeddedProperties.MAX_RESULTSET_CACHE_SIZE, DEFAULT_MAX_RESULTSET_CACHE_SIZE));
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_MAX_AGE, props.getProperty(DQPEmbeddedProperties.MAX_RESULTSET_CACHE_AGE, DEFAULT_MAX_RESULTSET_CACHE_AGE));
rsCacheProps.setProperty(ResultSetCache.RS_CACHE_SCOPE, props.getProperty(DQPEmbeddedProperties.RESULTSET_CACHE_SCOPE, ResultSetCache.RS_CACHE_SCOPE_VDB));
- this.rsCache = new ResultSetCache(rsCacheProps, ResourceFinder.getCacheFactory());
+ this.rsCache = new ResultSetCache(rsCacheProps, cacheFactory);
}
//prepared plan cache
@@ -680,20 +684,20 @@
LogManager.logInfo(LogConstants.CTX_DQP, DQPPlugin.Util.getString("DQPCore.Processor_debug_allowed_{0}", this.processorDebugAllowed)); //$NON-NLS-1$
//get buffer manager
- BufferService bufferService = (BufferService) env.findService(DQPServiceNames.BUFFER_SERVICE);
+ BufferService bufferService = (BufferService) this.environment.findService(DQPServiceNames.BUFFER_SERVICE);
bufferManager = bufferService.getBufferManager();
contextCache = bufferService.getContextCache();
- transactionService = (TransactionService )env.findService(DQPServiceNames.TRANSACTION_SERVICE);
- metadataService = (MetadataService) env.findService(DQPServiceNames.METADATA_SERVICE);
+ transactionService = (TransactionService )this.environment.findService(DQPServiceNames.TRANSACTION_SERVICE);
+ metadataService = (MetadataService) this.environment.findService(DQPServiceNames.METADATA_SERVICE);
// Create the worker pools to tie the queues together
processWorkerPool = WorkerPoolFactory.newWorkerPool(PROCESS_PLAN_QUEUE_NAME, PropertiesUtils.getIntProperty(props, DQPEmbeddedProperties.PROCESS_POOL_MAX_THREADS, DEFAULT_MAX_PROCESS_WORKERS));
dataTierMgr = new DataTierManagerImpl(this,
- (DataService) env.findService(DQPServiceNames.DATA_SERVICE),
- (VDBService) env.findService(DQPServiceNames.VDB_SERVICE),
- (BufferService) env.findService(DQPServiceNames.BUFFER_SERVICE),
+ (DataService) this.environment.findService(DQPServiceNames.DATA_SERVICE),
+ (VDBService) this.environment.findService(DQPServiceNames.VDB_SERVICE),
+ (BufferService) this.environment.findService(DQPServiceNames.BUFFER_SERVICE),
this.maxCodeTables,
this.maxCodeRecords,
this.maxCodeTableRecords);
@@ -782,7 +786,7 @@
public MetadataResult getMetadata(long requestID)
throws MetaMatrixComponentException, MetaMatrixProcessingException {
DQPWorkContext workContext = DQPWorkContext.getWorkContext();
- MetaDataProcessor processor = new MetaDataProcessor(this.metadataService, this, this.prepPlanCache, getEnvironment());
+ MetaDataProcessor processor = new MetaDataProcessor(this.metadataService, this, this.prepPlanCache, this.environment);
return processor.processMessage(workContext.getRequestID(requestID), workContext, null, true);
}
@@ -790,7 +794,21 @@
boolean allowDoubleQuotedVariable)
throws MetaMatrixComponentException, MetaMatrixProcessingException {
DQPWorkContext workContext = DQPWorkContext.getWorkContext();
- MetaDataProcessor processor = new MetaDataProcessor(this.metadataService, this, this.prepPlanCache, getEnvironment());
+ MetaDataProcessor processor = new MetaDataProcessor(this.metadataService, this, this.prepPlanCache, this.environment);
return processor.processMessage(workContext.getRequestID(requestID), workContext, preparedSql, allowDoubleQuotedVariable);
}
+
+ public ApplicationEnvironment getEnvironment() {
+ return environment;
+ }
+
+ @Inject
+ public void setCacheFactory(CacheFactory cacheFactory) {
+ this.cacheFactory = cacheFactory;
+ this.environment.setCacheFactory(cacheFactory);
+ }
+
+ public void setEnvironment(ApplicationEnvironment environment) {
+ this.environment = environment;
+ }
}
\ No newline at end of file
Modified: trunk/engine/src/test/java/com/metamatrix/dqp/config/TestDQPLauncher.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/dqp/config/TestDQPLauncher.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/test/java/com/metamatrix/dqp/config/TestDQPLauncher.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -22,7 +22,6 @@
package com.metamatrix.dqp.config;
-import java.util.HashMap;
import java.util.Properties;
import junit.framework.TestCase;
@@ -30,7 +29,6 @@
import org.mockito.Mockito;
import org.teiid.dqp.internal.process.DQPCore;
-import com.metamatrix.common.application.ApplicationService;
import com.metamatrix.common.application.DQPConfigSource;
import com.metamatrix.dqp.service.AutoGenDataService;
import com.metamatrix.dqp.service.BufferService;
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManagerImpl.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManagerImpl.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/datamgr/impl/TestConnectorManagerImpl.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -41,7 +41,6 @@
import org.teiid.connector.api.ConnectorIdentity;
import org.teiid.connector.api.ConnectorPropertyNames;
import org.teiid.connector.api.ExecutionContext;
-import org.teiid.dqp.internal.cache.ResultSetCache;
import org.teiid.dqp.internal.datamgr.impl.TestConnectorWorkItem.QueueResultsReceiver;
import org.teiid.dqp.internal.pooling.connector.ConnectionPool;
import org.teiid.dqp.internal.pooling.connector.FakeSourceConnectionFactory;
@@ -130,6 +129,7 @@
ApplicationEnvironment env = new ApplicationEnvironment();
env.bindService(DQPServiceNames.METADATA_SERVICE, new FakeMetadataService());
env.bindService(DQPServiceNames.TRANSACTION_SERVICE, new FakeTransactionService());
+ env.setCacheFactory(new FakeCache.FakeCacheFactory());
cm.start(env);
}
@@ -157,13 +157,7 @@
}
@Test public void testCaching() throws Exception {
- ConnectorManager cm = new ConnectorManager() {
- @Override
- protected ResultSetCache createResultSetCache(Properties rsCacheProps) {
- assertEquals(String.valueOf(3600000), rsCacheProps.get(ResultSetCache.RS_CACHE_MAX_AGE));
- return new ResultSetCache(rsCacheProps, new FakeCache.FakeCacheFactory());
- }
- };
+ ConnectorManager cm = new ConnectorManager();
Properties props = new Properties();
props.setProperty(ConnectorPropertyNames.CONNECTOR_CLASS, FakeConnector.class.getName());
props.setProperty(ConnectorPropertyNames.USE_RESULTSET_CACHE, Boolean.TRUE.toString());
Modified: trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
===================================================================
--- trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -86,11 +86,8 @@
vdbService.addModel(vdbName, vdbVersion, "BQT3", ModelInfo.PRIVATE, false); //$NON-NLS-1$
env.bindService(DQPServiceNames.VDB_SERVICE, vdbService);
- core = new DQPCore() {
- public ApplicationEnvironment getEnvironment() {
- return env;
- }
- };
+ core = new DQPCore();
+ core.setEnvironment(env);
core.start(new Properties());
}
Modified: trunk/runtime/src/main/java/com/metamatrix/jdbc/EmbeddedConnectionFactoryImpl.java
===================================================================
--- trunk/runtime/src/main/java/com/metamatrix/jdbc/EmbeddedConnectionFactoryImpl.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/main/java/com/metamatrix/jdbc/EmbeddedConnectionFactoryImpl.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -41,6 +41,7 @@
import org.teiid.transport.AdminAuthorizationInterceptor;
import org.teiid.transport.LocalServerConnection;
import org.teiid.transport.LogonImpl;
+import org.teiid.transport.SocketListenerStats;
import org.teiid.transport.SocketTransport;
import com.google.inject.Guice;
@@ -64,7 +65,6 @@
import com.metamatrix.core.MetaMatrixCoreException;
import com.metamatrix.core.MetaMatrixRuntimeException;
import com.metamatrix.core.util.MixinProxy;
-import com.metamatrix.dqp.ResourceFinder;
import com.metamatrix.dqp.client.ClientSideDQP;
import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
import com.metamatrix.dqp.embedded.DQPEmbeddedProperties;
@@ -78,7 +78,6 @@
import com.metamatrix.dqp.util.LogConstants;
import com.metamatrix.platform.security.api.ILogon;
import com.metamatrix.platform.security.api.service.SessionServiceInterface;
-import com.metamatrix.platform.vm.controller.SocketListenerStats;
/**
@@ -152,7 +151,6 @@
EmbeddedGuiceModule config = new EmbeddedGuiceModule(bootstrapURL, props, this.jmxServer, address);
Injector injector = Guice.createInjector(config);
- ResourceFinder.setInjector(injector);
config.setInjector(injector);
// start the DQP
@@ -341,9 +339,6 @@
this.socketTransport = null;
}
- // shutdown the cache.
- ResourceFinder.getCacheFactory().destroy();
-
this.restart = restart;
}
Modified: trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/main/java/org/teiid/transport/SocketListener.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -45,7 +45,6 @@
import com.metamatrix.core.log.MessageLevel;
import com.metamatrix.core.util.NamedThreadFactory;
import com.metamatrix.platform.security.api.service.SessionServiceInterface;
-import com.metamatrix.platform.vm.controller.SocketListenerStats;
/**
* Server-side class to listen for new connection requests and create a SocketClientConnection for each connection request.
Copied: trunk/runtime/src/main/java/org/teiid/transport/SocketListenerStats.java (from rev 1488, trunk/common-internal/src/main/java/com/metamatrix/platform/vm/controller/SocketListenerStats.java)
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SocketListenerStats.java (rev 0)
+++ trunk/runtime/src/main/java/org/teiid/transport/SocketListenerStats.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -0,0 +1,40 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package org.teiid.transport;
+
+import java.io.Serializable;
+
+
+/**
+ * Data holder for statistics about the server-side SocketListener.
+ * @since 4.3
+ */
+public class SocketListenerStats implements Serializable {
+
+ public long objectsRead = 0;
+ public long objectsWritten = 0;
+
+ public int sockets = 0;
+ public int maxSockets = 0;
+}
+
Modified: trunk/runtime/src/main/java/org/teiid/transport/SocketTransport.java
===================================================================
--- trunk/runtime/src/main/java/org/teiid/transport/SocketTransport.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/main/java/org/teiid/transport/SocketTransport.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -37,7 +37,6 @@
import com.metamatrix.dqp.embedded.DQPEmbeddedPlugin;
import com.metamatrix.dqp.embedded.DQPEmbeddedProperties;
import com.metamatrix.platform.security.api.service.SessionServiceInterface;
-import com.metamatrix.platform.vm.controller.SocketListenerStats;
/**
* This class starts a Socket for DQP connections and listens on the port and hands out the connections to the
Modified: trunk/runtime/src/test/java/com/metamatrix/dqp/embedded/services/TestEmbeddedVDBService.java
===================================================================
--- trunk/runtime/src/test/java/com/metamatrix/dqp/embedded/services/TestEmbeddedVDBService.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/test/java/com/metamatrix/dqp/embedded/services/TestEmbeddedVDBService.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -30,7 +30,7 @@
import junit.framework.TestCase;
import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.application.Application;
+import com.metamatrix.common.application.ApplicationEnvironment;
import com.metamatrix.common.config.api.ConnectorBinding;
import com.metamatrix.common.config.api.ConnectorBindingType;
import com.metamatrix.common.vdb.api.VDBArchive;
@@ -51,7 +51,7 @@
protected void setUp() throws Exception {
EmbeddedTestUtil.createTestDirectory();
- Application registry = new Application();
+ ApplicationEnvironment registry = new ApplicationEnvironment();
configService = new EmbeddedConfigurationService();
registry.installService(DQPServiceNames.CONFIGURATION_SERVICE, configService);
vdbService = new EmbeddedVDBService();
@@ -155,7 +155,7 @@
vdbService.stopService();
configService.stopService();
- Application registry = new Application();
+ ApplicationEnvironment registry = new ApplicationEnvironment();
configService = new EmbeddedConfigurationService();
configService.setUserPreferences(p);
configService.initializeService(p);
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 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/test/java/com/metamatrix/dqp/service/buffer/TestLocalBufferService.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -26,7 +26,7 @@
import junit.framework.TestCase;
-import com.metamatrix.common.application.Application;
+import com.metamatrix.common.application.ApplicationEnvironment;
import com.metamatrix.common.application.exception.ApplicationInitializationException;
import com.metamatrix.common.buffer.impl.BufferConfig;
import com.metamatrix.common.buffer.impl.BufferManagerImpl;
@@ -46,7 +46,7 @@
public void testMissingRequiredProperties() throws Exception {
try {
- Application r = new Application();
+ ApplicationEnvironment r = new ApplicationEnvironment();
ConfigurationService cs = new EmbeddedConfigurationService();
Properties p = EmbeddedTestUtil.getProperties(UnitTestUtil.getTestDataPath() + "/admin/buffertest1.properties"); //$NON-NLS-1$
p.setProperty(DQPEmbeddedProperties.DQP_WORKDIR, System.getProperty("java.io.tmpdir")+"/teiid/1"); //$NON-NLS-1$ //$NON-NLS-2$
@@ -70,7 +70,7 @@
public void testCheckMemPropertyGotSet() throws Exception {
EmbeddedBufferService svc = null;
ConfigurationService cs = null;
- Application r = new Application();
+ ApplicationEnvironment r = new ApplicationEnvironment();
cs = new EmbeddedConfigurationService();
Properties p = EmbeddedTestUtil.getProperties(UnitTestUtil.getTestDataPath() + "/admin/buffertest2.properties"); //$NON-NLS-1$
p.setProperty(DQPEmbeddedProperties.DQP_WORKDIR, System.getProperty("java.io.tmpdir")+"/teiid/1"); //$NON-NLS-1$ //$NON-NLS-2$
@@ -97,7 +97,7 @@
public void testCheckMemPropertyGotSet2() throws Exception {
EmbeddedBufferService svc = null;
- Application r = new Application();
+ ApplicationEnvironment r = new ApplicationEnvironment();
ConfigurationService cs = new EmbeddedConfigurationService();
Properties p = EmbeddedTestUtil.getProperties(UnitTestUtil.getTestDataPath() + "/admin/buffertest3.properties"); //$NON-NLS-1$
p.setProperty(DQPEmbeddedProperties.DQP_WORKDIR, System.getProperty("java.io.tmpdir")+"/teiid/1"); //$NON-NLS-1$ //$NON-NLS-2$
Modified: trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java
===================================================================
--- trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java 2009-09-29 17:30:43 UTC (rev 1491)
+++ trunk/runtime/src/test/java/org/teiid/transport/TestCommSockets.java 2009-09-29 20:44:35 UTC (rev 1492)
@@ -50,7 +50,6 @@
import com.metamatrix.platform.security.api.ILogon;
import com.metamatrix.platform.security.api.LogonResult;
import com.metamatrix.platform.security.api.service.SessionServiceInterface;
-import com.metamatrix.platform.vm.controller.SocketListenerStats;
public class TestCommSockets {
15 years, 3 months
teiid SVN: r1491 - in branches: JCA/connectors/sandbox/connector-exec and 2 other directories.
by teiid-commits@lists.jboss.org
Author: rareddy
Date: 2009-09-29 13:30:43 -0400 (Tue, 29 Sep 2009)
New Revision: 1491
Added:
branches/JCA/
branches/JCA/connectors/sandbox/connector-exec/pom.xml
branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java
branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java
branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java
Removed:
branches/JCA/connectors/sandbox/connector-exec/pom.xml
branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java
branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java
branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java
Log:
TEIID-833 Related changes
Copied: branches/JCA (from rev 1472, trunk)
Deleted: branches/JCA/connectors/sandbox/connector-exec/pom.xml
===================================================================
--- trunk/connectors/sandbox/connector-exec/pom.xml 2009-09-23 20:35:59 UTC (rev 1472)
+++ branches/JCA/connectors/sandbox/connector-exec/pom.xml 2009-09-29 17:30:43 UTC (rev 1491)
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
- <parent>
- <artifactId>sandbox</artifactId>
- <groupId>org.jboss.teiid.connectors</groupId>
- <version>6.3.0-SNAPSHOT</version>
- </parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>connector-exec</artifactId>
- <groupId>org.jboss.teiid.connectors.sandbox</groupId>
- <name>Exec Connector</name>
- <description>This connector executes Admin API calls and System.exec calls through the connector using SQL representation</description>
- <dependencies>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-connector-api</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-core</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>ant</groupId>
- <artifactId>ant</artifactId>
- <version>1.6.5</version>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-common-internal</artifactId>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.teiid</groupId>
- <artifactId>teiid-server</artifactId>
- <version>${project.version}</version>
- </dependency>
- </dependencies>
-</project>
\ No newline at end of file
Copied: branches/JCA/connectors/sandbox/connector-exec/pom.xml (from rev 1473, trunk/connectors/sandbox/connector-exec/pom.xml)
===================================================================
--- branches/JCA/connectors/sandbox/connector-exec/pom.xml (rev 0)
+++ branches/JCA/connectors/sandbox/connector-exec/pom.xml 2009-09-29 17:30:43 UTC (rev 1491)
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <parent>
+ <artifactId>sandbox</artifactId>
+ <groupId>org.jboss.teiid.connectors</groupId>
+ <version>6.3.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>connector-exec</artifactId>
+ <groupId>org.jboss.teiid.connectors.sandbox</groupId>
+ <name>Exec Connector</name>
+ <description>This connector executes Admin API calls and System.exec calls through the connector using SQL representation</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-connector-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-core</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>1.6.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.teiid</groupId>
+ <artifactId>teiid-common-internal</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Deleted: branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java
===================================================================
--- trunk/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java 2009-09-23 20:35:59 UTC (rev 1472)
+++ branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -1,348 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.connector.exec;
-
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Random;
-
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.Location;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.taskdefs.ExecTask;
-import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
-import org.apache.tools.ant.taskdefs.PumpStreamHandler;
-import org.apache.tools.ant.types.Commandline.Argument;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.DataNotAvailableException;
-import org.teiid.connector.api.ResultSetExecution;
-import org.teiid.connector.basic.BasicExecution;
-import org.teiid.connector.language.IQuery;
-import org.teiid.connector.metadata.runtime.RuntimeMetadata;
-
-import com.metamatrix.common.config.CurrentConfiguration;
-import com.metamatrix.common.config.api.Host;
-import com.metamatrix.common.util.CommonPropertyNames;
-import com.metamatrix.common.util.OSPlatformUtil;
-import com.metamatrix.core.util.Assertion;
-import com.metamatrix.core.util.StringUtil;
-import com.metamatrix.core.util.TempDirectory;
-
-/**
- * Represents the execution of a command.
- */
-public class ExecAntExecution extends BasicExecution implements ResultSetExecution {
-
- private static final Random random = new Random(System.currentTimeMillis());
-
- private static String INSTALL_DIR = ".";//$NON-NLS-1$
-
- private static final String WIN_EXEC = "win.executable"; //$NON-NLS-1$
- private static final String UNIX_EXEC = "unix.executable"; //$NON-NLS-1$
-
- private static final String DEFAUTL_WIN_EXEC = "cmd.exe"; //$NON-NLS-1$
- private static final String DEFAUTL_UNIX_EXEC = "/bin/sh"; //$NON-NLS-1$
-
- // Connector resources
- private ConnectorEnvironment env;
- private List responses = new ArrayList();
- private String execcommand;
- private boolean isWin = false;
-
- // Execution state
- int[] neededColumns;
- int returnIndex = 0;
-
- private Process p = null;
-
- private List exclusionList;
- private IQuery query;
-
- public ExecAntExecution(IQuery query, ConnectorEnvironment env, RuntimeMetadata metadata, ConnectorLogger logger, List exclusionThese) {
- this.env = env;
- this.query = query;
- if (exclusionThese != null)
- exclusionList = exclusionThese;
- else
- exclusionList = Collections.EMPTY_LIST;
- Properties props = env.getProperties();
-
- if (OSPlatformUtil.isWindows()) {
- execcommand = props.getProperty(WIN_EXEC, DEFAUTL_WIN_EXEC);
- Assertion.isNotNull(execcommand, WIN_EXEC+ " property was not defined for os type"); //$NON-NLS-1$
- isWin = true;
-
- } else {
- execcommand = props.getProperty(UNIX_EXEC, DEFAUTL_UNIX_EXEC);
- Assertion.isNotNull(execcommand, UNIX_EXEC + " property was not defined for os type"); //$NON-NLS-1$
- }
- }
-
- /*
- * @see com.metamatrix.data.SynchQueryExecution#execute(com.metamatrix.data.language.IQuery,
- * int)
- */
- public void execute()
- throws ConnectorException {
-
- env.getLogger().logTrace("Exec executing command: " + query); //$NON-NLS-1$
- org.teiid.connector.language.ICriteria crit = query.getWhere();
- if (crit == null)
- throw new ConnectorException(ExecPlugin.Util
- .getString("ExecExecution.Must_have_criteria")); //$NON-NLS-1$
- Map whereVariables = ExecVisitor.getWhereClauseMap(crit);
- if (whereVariables.isEmpty())
- throw new ConnectorException(ExecPlugin.Util
- .getString("ExecExecution.Must_have_criteria")); //$NON-NLS-1$
-
- String command = ""; //$NON-NLS-1$
- int i = 2;
- for (Iterator it = whereVariables.keySet().iterator(); it.hasNext();) {
- String whereKey = (String) it.next();
- String v = ((String) whereVariables.get(whereKey)).trim();
- isValid(v);
- command += v;
- i++;
- }
- try {
- execute(command);
- } catch (Exception e) {
- env.getLogger().logError("Execution Error", e); //$NON-NLS-1$
- throw new ConnectorException(e);
- }
- }
-
- private boolean isValid(String command) throws ConnectorException {
- boolean isvalid = true;
- List tokens = StringUtil.getTokens(command.toLowerCase(), " "); //$NON-NLS-1$
- for (Iterator it = tokens.iterator(); it.hasNext();) {
- String v = (String) it.next();
- if (exclusionList.contains(v))
- throw new ConnectorException(ExecPlugin.Util.getString(
- "ExecExecution.Execution_of_statement_not_allowed", v));//$NON-NLS-1$
- }
-
- return isvalid;
- }
-
- protected void execute(String command) throws Exception {
-
- ExecuteMMTask task = createClass();
-
- env.getLogger().logTrace(
- "Exec: " + execcommand + " command: " + command); //$NON-NLS-1$ //$NON-NLS-2$
-
- Project p = new Project();
- p.init();
- p.setBasedir(INSTALL_DIR);
- p.setCoreLoader(this.getClass().getClassLoader());
-
- task.setProject(p);
-
- task.setDir(new File((INSTALL_DIR)));
-
- task.setLogError(true);
-
- task.setFailonerror(false);
-
- task.setTaskType("MMExecutionTask"); //$NON-NLS-1$
- task.setTaskName("ExecAntExecution"); //$NON-NLS-1$
- task.setExecutable(execcommand);
-
- Argument a = task.createArg();
-
- if (isWin) {
- // do not set for unix
- task.setVMLauncher(true);
-
- a.setValue("/c"); //$NON-NLS-1$
- a = task.createArg();
- }
- a.setLine(command);
- // a.setValue(command);
- a.setProject(p);
-
- task.setAppend(true);
- task.setLocation(Location.UNKNOWN_LOCATION);
-
- task.execute();
- task.addToRows(responses);
-
- }
-
- private ExecuteMMTask createClass() {
-
- ExecuteMMTask rep = new ExecuteMMTask();
-
- return rep;
- }
-
- @Override
- public List next() throws ConnectorException, DataNotAvailableException {
- if (returnIndex < responses.size()) {
- return (List)responses.get(returnIndex++);
- }
-
- return null;
- }
-
- /**
- * @param row
- * @param neededColumns
- */
- static List projectRow(List row, int[] neededColumns) {
- List output = new ArrayList(neededColumns.length);
-
- for (int i = 0; i < neededColumns.length; i++) {
- output.add(row.get(neededColumns[i]));
- }
-
- return output;
- }
-
- /*
- * @see com.metamatrix.data.Execution#close()
- */
- public void close() throws ConnectorException {
- // nothing to do
-
- exclusionList = null;
- responses = null;
-
- if (p != null) {
- try {
- p.destroy();
- } catch (Exception e) {
-
- } finally {
- p = null;
-
- }
- }
-
- }
-
- /*
- * @see com.metamatrix.data.Execution#cancel()
- */
- public void cancel() throws ConnectorException {
- this.close();
-
- }
-
- final class ExecuteMMTask extends ExecTask {
- protected ByteArrayOutputStream os = null;
- protected ByteArrayOutputStream erros = null;
- protected ByteArrayInputStream in = null;
- protected BufferedOutputStream bos = null;
- protected BufferedOutputStream bose = null;
-
- public ExecuteMMTask() {
- }
-
- /**
- * Create the StreamHandler to use with our Execute instance.
- *
- * @return the execute stream handler to manage the input, output and
- * error streams.
- *
- * @throws BuildException
- * if the execute stream handler cannot be created.
- */
- public synchronized ExecuteStreamHandler createHandler()
- throws BuildException {
- super.createHandler();
-
- os = new ByteArrayOutputStream();
- bos = new BufferedOutputStream(os);
-
- erros = new ByteArrayOutputStream();
- bose = new BufferedOutputStream(erros);
-
- in = new ByteArrayInputStream(new byte[] { ' ' });
-
- return new PumpStreamHandler(bos, bose);
- }
-
- public void addToRows(List responseRows) throws Exception {
-
- try {
- bos.flush();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(os
- .toByteArray());
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(bais));
- String oneline;
- while ((oneline = reader.readLine()) != null) {
- List row = new ArrayList(1);
- row.add(oneline);
- responseRows.add(row);
- }
- reader.close();
-
- boolean first = true;
- bose.flush();
- ByteArrayInputStream baise = new ByteArrayInputStream(erros
- .toByteArray());
- BufferedReader ereader = new BufferedReader(
- new InputStreamReader(baise));
- while ((oneline = ereader.readLine()) != null) {
- if (first) {
- env.getLogger().logError("Error Message:"); //$NON-NLS-1$
- first = false;
- }
- List row = new ArrayList(1);
- row.add(oneline);
- responseRows.add(row);
- env.getLogger().logError(oneline);
- }
- ereader.close();
- } finally {
- if (os != null) {
- os.close();
- os = null;
- }
-
- if (erros != null) {
- erros.close();
- erros = null;
- }
- }
- }
-
- }
-
-}
Copied: branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java (from rev 1473, trunk/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java)
===================================================================
--- branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java (rev 0)
+++ branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecAntExecution.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -0,0 +1,344 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package com.metamatrix.connector.exec;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.Location;
+import org.apache.tools.ant.Project;
+import org.apache.tools.ant.taskdefs.ExecTask;
+import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
+import org.apache.tools.ant.taskdefs.PumpStreamHandler;
+import org.apache.tools.ant.types.Commandline.Argument;
+import org.teiid.connector.api.ConnectorEnvironment;
+import org.teiid.connector.api.ConnectorException;
+import org.teiid.connector.api.ConnectorLogger;
+import org.teiid.connector.api.DataNotAvailableException;
+import org.teiid.connector.api.ResultSetExecution;
+import org.teiid.connector.basic.BasicExecution;
+import org.teiid.connector.language.IQuery;
+import org.teiid.connector.metadata.runtime.RuntimeMetadata;
+
+import com.metamatrix.common.util.OSPlatformUtil;
+import com.metamatrix.core.util.Assertion;
+import com.metamatrix.core.util.StringUtil;
+
+/**
+ * Represents the execution of a command.
+ */
+public class ExecAntExecution extends BasicExecution implements ResultSetExecution {
+
+ private static final Random random = new Random(System.currentTimeMillis());
+
+ private static String INSTALL_DIR = ".";//$NON-NLS-1$
+
+ private static final String WIN_EXEC = "win.executable"; //$NON-NLS-1$
+ private static final String UNIX_EXEC = "unix.executable"; //$NON-NLS-1$
+
+ private static final String DEFAUTL_WIN_EXEC = "cmd.exe"; //$NON-NLS-1$
+ private static final String DEFAUTL_UNIX_EXEC = "/bin/sh"; //$NON-NLS-1$
+
+ // Connector resources
+ private ConnectorEnvironment env;
+ private List responses = new ArrayList();
+ private String execcommand;
+ private boolean isWin = false;
+
+ // Execution state
+ int[] neededColumns;
+ int returnIndex = 0;
+
+ private Process p = null;
+
+ private List exclusionList;
+ private IQuery query;
+
+ public ExecAntExecution(IQuery query, ConnectorEnvironment env, RuntimeMetadata metadata, ConnectorLogger logger, List exclusionThese) {
+ this.env = env;
+ this.query = query;
+ if (exclusionThese != null)
+ exclusionList = exclusionThese;
+ else
+ exclusionList = Collections.EMPTY_LIST;
+ Properties props = env.getProperties();
+
+ if (OSPlatformUtil.isWindows()) {
+ execcommand = props.getProperty(WIN_EXEC, DEFAUTL_WIN_EXEC);
+ Assertion.isNotNull(execcommand, WIN_EXEC+ " property was not defined for os type"); //$NON-NLS-1$
+ isWin = true;
+
+ } else {
+ execcommand = props.getProperty(UNIX_EXEC, DEFAUTL_UNIX_EXEC);
+ Assertion.isNotNull(execcommand, UNIX_EXEC + " property was not defined for os type"); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * @see com.metamatrix.data.SynchQueryExecution#execute(com.metamatrix.data.language.IQuery,
+ * int)
+ */
+ public void execute()
+ throws ConnectorException {
+
+ env.getLogger().logTrace("Exec executing command: " + query); //$NON-NLS-1$
+ org.teiid.connector.language.ICriteria crit = query.getWhere();
+ if (crit == null)
+ throw new ConnectorException(ExecPlugin.Util
+ .getString("ExecExecution.Must_have_criteria")); //$NON-NLS-1$
+ Map whereVariables = ExecVisitor.getWhereClauseMap(crit);
+ if (whereVariables.isEmpty())
+ throw new ConnectorException(ExecPlugin.Util
+ .getString("ExecExecution.Must_have_criteria")); //$NON-NLS-1$
+
+ String command = ""; //$NON-NLS-1$
+ int i = 2;
+ for (Iterator it = whereVariables.keySet().iterator(); it.hasNext();) {
+ String whereKey = (String) it.next();
+ String v = ((String) whereVariables.get(whereKey)).trim();
+ isValid(v);
+ command += v;
+ i++;
+ }
+ try {
+ execute(command);
+ } catch (Exception e) {
+ env.getLogger().logError("Execution Error", e); //$NON-NLS-1$
+ throw new ConnectorException(e);
+ }
+ }
+
+ private boolean isValid(String command) throws ConnectorException {
+ boolean isvalid = true;
+ List tokens = StringUtil.getTokens(command.toLowerCase(), " "); //$NON-NLS-1$
+ for (Iterator it = tokens.iterator(); it.hasNext();) {
+ String v = (String) it.next();
+ if (exclusionList.contains(v))
+ throw new ConnectorException(ExecPlugin.Util.getString(
+ "ExecExecution.Execution_of_statement_not_allowed", v));//$NON-NLS-1$
+ }
+
+ return isvalid;
+ }
+
+ protected void execute(String command) throws Exception {
+
+ ExecuteMMTask task = createClass();
+
+ env.getLogger().logTrace(
+ "Exec: " + execcommand + " command: " + command); //$NON-NLS-1$ //$NON-NLS-2$
+
+ Project p = new Project();
+ p.init();
+ p.setBasedir(INSTALL_DIR);
+ p.setCoreLoader(this.getClass().getClassLoader());
+
+ task.setProject(p);
+
+ task.setDir(new File((INSTALL_DIR)));
+
+ task.setLogError(true);
+
+ task.setFailonerror(false);
+
+ task.setTaskType("MMExecutionTask"); //$NON-NLS-1$
+ task.setTaskName("ExecAntExecution"); //$NON-NLS-1$
+ task.setExecutable(execcommand);
+
+ Argument a = task.createArg();
+
+ if (isWin) {
+ // do not set for unix
+ task.setVMLauncher(true);
+
+ a.setValue("/c"); //$NON-NLS-1$
+ a = task.createArg();
+ }
+ a.setLine(command);
+ // a.setValue(command);
+ a.setProject(p);
+
+ task.setAppend(true);
+ task.setLocation(Location.UNKNOWN_LOCATION);
+
+ task.execute();
+ task.addToRows(responses);
+
+ }
+
+ private ExecuteMMTask createClass() {
+
+ ExecuteMMTask rep = new ExecuteMMTask();
+
+ return rep;
+ }
+
+ @Override
+ public List next() throws ConnectorException, DataNotAvailableException {
+ if (returnIndex < responses.size()) {
+ return (List)responses.get(returnIndex++);
+ }
+
+ return null;
+ }
+
+ /**
+ * @param row
+ * @param neededColumns
+ */
+ static List projectRow(List row, int[] neededColumns) {
+ List output = new ArrayList(neededColumns.length);
+
+ for (int i = 0; i < neededColumns.length; i++) {
+ output.add(row.get(neededColumns[i]));
+ }
+
+ return output;
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#close()
+ */
+ public void close() throws ConnectorException {
+ // nothing to do
+
+ exclusionList = null;
+ responses = null;
+
+ if (p != null) {
+ try {
+ p.destroy();
+ } catch (Exception e) {
+
+ } finally {
+ p = null;
+
+ }
+ }
+
+ }
+
+ /*
+ * @see com.metamatrix.data.Execution#cancel()
+ */
+ public void cancel() throws ConnectorException {
+ this.close();
+
+ }
+
+ final class ExecuteMMTask extends ExecTask {
+ protected ByteArrayOutputStream os = null;
+ protected ByteArrayOutputStream erros = null;
+ protected ByteArrayInputStream in = null;
+ protected BufferedOutputStream bos = null;
+ protected BufferedOutputStream bose = null;
+
+ public ExecuteMMTask() {
+ }
+
+ /**
+ * Create the StreamHandler to use with our Execute instance.
+ *
+ * @return the execute stream handler to manage the input, output and
+ * error streams.
+ *
+ * @throws BuildException
+ * if the execute stream handler cannot be created.
+ */
+ public synchronized ExecuteStreamHandler createHandler()
+ throws BuildException {
+ super.createHandler();
+
+ os = new ByteArrayOutputStream();
+ bos = new BufferedOutputStream(os);
+
+ erros = new ByteArrayOutputStream();
+ bose = new BufferedOutputStream(erros);
+
+ in = new ByteArrayInputStream(new byte[] { ' ' });
+
+ return new PumpStreamHandler(bos, bose);
+ }
+
+ public void addToRows(List responseRows) throws Exception {
+
+ try {
+ bos.flush();
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(os
+ .toByteArray());
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(bais));
+ String oneline;
+ while ((oneline = reader.readLine()) != null) {
+ List row = new ArrayList(1);
+ row.add(oneline);
+ responseRows.add(row);
+ }
+ reader.close();
+
+ boolean first = true;
+ bose.flush();
+ ByteArrayInputStream baise = new ByteArrayInputStream(erros
+ .toByteArray());
+ BufferedReader ereader = new BufferedReader(
+ new InputStreamReader(baise));
+ while ((oneline = ereader.readLine()) != null) {
+ if (first) {
+ env.getLogger().logError("Error Message:"); //$NON-NLS-1$
+ first = false;
+ }
+ List row = new ArrayList(1);
+ row.add(oneline);
+ responseRows.add(row);
+ env.getLogger().logError(oneline);
+ }
+ ereader.close();
+ } finally {
+ if (os != null) {
+ os.close();
+ os = null;
+ }
+
+ if (erros != null) {
+ erros.close();
+ erros = null;
+ }
+ }
+ }
+
+ }
+
+}
Deleted: branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java
===================================================================
--- trunk/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java 2009-09-23 20:35:59 UTC (rev 1472)
+++ branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -1,136 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.connector.exec;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.teiid.connector.api.Connection;
-import org.teiid.connector.api.ConnectorCapabilities;
-import org.teiid.connector.api.ConnectorEnvironment;
-import org.teiid.connector.api.ConnectorException;
-import org.teiid.connector.api.ConnectorLogger;
-import org.teiid.connector.api.ExecutionContext;
-import org.teiid.connector.basic.BasicConnector;
-
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.extensionmodule.ExtensionModuleManager;
-import com.metamatrix.common.extensionmodule.exception.ExtensionModuleNotFoundException;
-import com.metamatrix.core.util.ObjectConverterUtil;
-
-/**
- * Implementation of text connector.
- */
-public class ExecConnector extends BasicConnector {
-
- private ConnectorLogger logger;
- private ConnectorEnvironment env;
- private boolean start = false;
- private List exclusionList= Collections.EMPTY_LIST;
- private String exclusionFile;
-
- /**
- * Initialization with environment.
- */
- @Override
- public void start( ConnectorEnvironment environment ) throws ConnectorException {
- logger = environment.getLogger();
- this.env = environment;
-
- exclusionFile = environment.getProperties().getProperty("exclusionFile"); //$NON-NLS-1$
- if(exclusionFile != null && exclusionFile.trim().length() > 0)
- {
- loadExclusionFile(exclusionFile);
- }
-
- // logging
- logger = environment.getLogger();
- start = true;
- logger.logInfo("Exec Connector is started."); //$NON-NLS-1$
- }
-
- public void stop() {
- if(!start){
- return;
- }
-
- start = false;
- logger.logInfo("Exec Connector is stoped."); //$NON-NLS-1$
- }
-
- @Override
- public ConnectorCapabilities getCapabilities() {
- return new ExecCapabilities();
- }
-
- /*
- * @see com.metamatrix.data.Connector#getConnection(com.metamatrix.data.SecurityContext)
- */
- public Connection getConnection(ExecutionContext context) throws ConnectorException {
- return new ExecConnection(this.env, exclusionList);
- }
-
- protected void loadExclusionFile(String file)
- throws ConnectorException
-{
- try
- {
- if (!ExtensionModuleManager.getInstance().isSourceInUse(file)) {
- return;
- }
- byte data[] = ExtensionModuleManager.getInstance().getSource(file);
- java.io.InputStream is = ObjectConverterUtil.convertToInputStream(data);
- Properties props = new Properties();
- props.load(is);
- exclusionList = new ArrayList(props.size());
- String key;
- for(Iterator it = props.keySet().iterator(); it.hasNext(); exclusionList.add(((String)props.get(key)).trim().toLowerCase()))
- {
- key = (String)it.next();
- logger.logInfo("Exec Connector - exclude: " + props.get(key));//$NON-NLS-1$
- }
-
- }
- catch(IOException err)
- {
- throw new ConnectorException(err, ExecPlugin.Util.getString("ExecConnector.Error_loading_exclusion_properties", file)); //$NON-NLS-1$
- }
- catch(ExtensionModuleNotFoundException err)
- {
- throw new ConnectorException(ExecPlugin.Util.getString("ExecConnector.Exclusion_file_not_found", file)); //$NON-NLS-1$
- }
- catch(MetaMatrixComponentException err1)
- {
- throw new ConnectorException(err1, ExecPlugin.Util.getString("ExecConnector.Unable_to_load_extension_module", file)); //$NON-NLS-1$
- }
-}
-
- protected void setExclusionList(List list) {
- this.exclusionList = new ArrayList(list);
- }
-
-
-}
Copied: branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java (from rev 1473, trunk/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java)
===================================================================
--- branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java (rev 0)
+++ branches/JCA/connectors/sandbox/connector-exec/src/main/java/com/metamatrix/connector/exec/ExecConnector.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -0,0 +1,110 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package com.metamatrix.connector.exec;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.teiid.connector.api.Connection;
+import org.teiid.connector.api.ConnectorCapabilities;
+import org.teiid.connector.api.ConnectorEnvironment;
+import org.teiid.connector.api.ConnectorException;
+import org.teiid.connector.api.ConnectorLogger;
+import org.teiid.connector.api.ExecutionContext;
+import org.teiid.connector.basic.BasicConnector;
+
+/**
+ * Implementation of text connector.
+ */
+public class ExecConnector extends BasicConnector {
+
+ private ConnectorLogger logger;
+ private ConnectorEnvironment env;
+ private boolean start = false;
+ private List exclusionList= Collections.EMPTY_LIST;
+ private String exclusionFile;
+
+ /**
+ * Initialization with environment.
+ */
+ @Override
+ public void start( ConnectorEnvironment environment ) throws ConnectorException {
+ logger = environment.getLogger();
+ this.env = environment;
+
+ exclusionFile = environment.getProperties().getProperty("exclusionFile"); //$NON-NLS-1$
+ if(exclusionFile != null && exclusionFile.trim().length() > 0)
+ {
+ loadExclusionFile(exclusionFile);
+ }
+
+ // logging
+ logger = environment.getLogger();
+ start = true;
+ logger.logInfo("Exec Connector is started."); //$NON-NLS-1$
+ }
+
+ public void stop() {
+ if(!start){
+ return;
+ }
+
+ start = false;
+ logger.logInfo("Exec Connector is stoped."); //$NON-NLS-1$
+ }
+
+ @Override
+ public ConnectorCapabilities getCapabilities() {
+ return new ExecCapabilities();
+ }
+
+ /*
+ * @see com.metamatrix.data.Connector#getConnection(com.metamatrix.data.SecurityContext)
+ */
+ public Connection getConnection(ExecutionContext context) throws ConnectorException {
+ return new ExecConnection(this.env, exclusionList);
+ }
+
+ protected void loadExclusionFile(String file) throws ConnectorException {
+ try {
+ Properties props = new Properties();
+ props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(file));
+ exclusionList = new ArrayList(props.size());
+ String key;
+ for (Iterator it = props.keySet().iterator(); it.hasNext(); exclusionList.add(((String) props.get(key)).trim().toLowerCase())) {
+ key = (String) it.next();
+ logger.logInfo("Exec Connector - exclude: " + props.get(key));//$NON-NLS-1$
+ }
+
+ } catch (IOException err) {
+ throw new ConnectorException(err, ExecPlugin.Util.getString("ExecConnector.Error_loading_exclusion_properties", file)); //$NON-NLS-1$
+ }
+ }
+
+ protected void setExclusionList(List list) {
+ this.exclusionList = new ArrayList(list);
+ }
+}
Deleted: branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java
===================================================================
--- trunk/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java 2009-09-23 20:35:59 UTC (rev 1472)
+++ branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -1,69 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package com.metamatrix.connector.exec;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.teiid.connector.api.ConnectorException;
-
-
-/**
- * Implmentation of text connector.
- */
-public class FakeExecConnector extends ExecConnector {
-
-
-
-
- protected void loadExclusionFile(String file)
- throws ConnectorException
-{
- try
- {
- FileInputStream is = new FileInputStream(file);
-//
-// byte data[] = ExtensionModuleManager.getInstance().getSource(file);
-// java.io.InputStream is = ObjectConverterUtil.convertToInputStream(data);
- Properties props = new Properties();
- props.load(is);
- List exclusionList = new ArrayList(props.size());
- String key;
- for(Iterator it = props.keySet().iterator(); it.hasNext(); exclusionList.add(((String)props.get(key)).trim().toLowerCase()))
- {
- key = (String)it.next();
- }
- this.setExclusionList(exclusionList);
-
- }
- catch(IOException err)
- {
- throw new ConnectorException(err, ExecPlugin.Util.getString("ExecConnector.Error_loading_exclusion_properties", file)); //$NON-NLS-1$
- }
-}
-
-
-}
Copied: branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java (from rev 1473, trunk/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java)
===================================================================
--- branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java (rev 0)
+++ branches/JCA/connectors/sandbox/connector-exec/src/test/java/com/metamatrix/connector/exec/FakeExecConnector.java 2009-09-29 17:30:43 UTC (rev 1491)
@@ -0,0 +1,56 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ * 02110-1301 USA.
+ */
+
+package com.metamatrix.connector.exec;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import org.teiid.connector.api.ConnectorException;
+
+
+
+public class FakeExecConnector extends ExecConnector {
+
+ protected void loadExclusionFile(String file) throws ConnectorException {
+ try {
+ FileInputStream is = new FileInputStream(file);
+ //
+ Properties props = new Properties();
+ props.load(is);
+ List exclusionList = new ArrayList(props.size());
+ String key;
+ for (Iterator it = props.keySet().iterator(); it.hasNext(); exclusionList.add(((String) props.get(key)).trim().toLowerCase())) {
+ key = (String) it.next();
+ }
+ this.setExclusionList(exclusionList);
+
+ } catch (IOException err) {
+ throw new ConnectorException(err, ExecPlugin.Util.getString("ExecConnector.Error_loading_exclusion_properties", file)); //$NON-NLS-1$
+ }
+ }
+
+
+}
15 years, 3 months
teiid SVN: r1490 - in trunk/test-integration/db/src/main/java/org/teiid/test: util and 1 other directory.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2009-09-29 10:23:43 -0400 (Tue, 29 Sep 2009)
New Revision: 1490
Removed:
trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java
trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
Modified:
trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
Log:
removing duplicate classes
Modified: trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-29 13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/framework/datasource/DataSourceMgr.java 2009-09-29 14:23:43 UTC (rev 1490)
@@ -22,10 +22,10 @@
import org.teiid.test.framework.ConfigPropertyNames;
import org.teiid.test.framework.exception.QueryTestFailedException;
import org.teiid.test.framework.exception.TransactionRuntimeException;
-import org.teiid.test.util.StringUtil;
import com.metamatrix.common.xml.XMLReaderWriter;
import com.metamatrix.common.xml.XMLReaderWriterImpl;
+import com.metamatrix.core.util.StringUtil;
/**
* The DataSourceMgr is responsible for loading and managing datasources defined by the datasource
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java 2009-09-29 13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/ArgCheck.java 2009-09-29 14:23:43 UTC (rev 1490)
@@ -1,534 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.util.Collection;
-import java.util.Map;
-
-/**
- * This class contains a set of static utility methods for checking method arguments.
- * It contains many of the common checks that are done, such as checking that an
- * Object is non-null, checking the range of a value, etc. All of these methods
- * throw {@link #java.lang.IllegalArgumentException}.
- */
-public class ArgCheck {
-
- /**
- * Can't construct - utility class
- */
- private ArgCheck() {
- }
-
- /**
- * Check that the boolean condition is true; throw an
- * IllegalArgumentException if not.
- * @param condition The boolean condition to check
- * @param message Exception message if check fails
- * @throws IllegalArgumentException if condition is false
- */
- public static final void isTrue(boolean condition, String message){
- if(!condition) {
- throw new IllegalArgumentException(message);
- }
- }
-
- // ########################## int METHODS ###################################
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(int value) {
- isNonNegative(value,null);
- }
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(int value, String message) {
- if(value < 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(int value) {
- isNonPositive(value,null);
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(int value, String message) {
- if(value > 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(int value) {
- isNegative(value,null);
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(int value, String message) {
- if(value >= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(int value) {
- isPositive(value,null);
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(int value, String message) {
- if(value <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## long METHODS ###################################
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(long value) {
- isNonNegative(value,null);
- }
-
- /**
- * Check that the value is non-negative (>=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is negative (<0)
- */
- public static final void isNonNegative(long value, String message) {
- if(value < 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(long value) {
- isNonPositive(value,null);
- }
-
- /**
- * Check that the value is non-positive (<=0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is positive (>0)
- */
- public static final void isNonPositive(long value, String message) {
- if(value > 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(long value) {
- isNegative(value,null);
- }
-
- /**
- * Check that the value is negative (<0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-negative (>=0)
- */
- public static final void isNegative(long value, String message) {
- if(value >= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNegativeInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(long value) {
- isPositive(value,null);
- }
-
- /**
- * Check that the value is positive (>0).
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-positive (<=0)
- */
- public static final void isPositive(long value, String message) {
- if(value <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isPositiveInt"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## String METHODS ###################################
-
- /**
- * Check that the string is non-null and has length > 0
- * @param value Value
- * @throws IllegalArgumentException If value is null or length == 0
- */
- public static final void isNotZeroLength(String value) {
- isNotZeroLength(value,null);
- }
-
- /**
- * Check that the string is non-null and has length > 0
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null or length == 0
- */
- public static final void isNotZeroLength(String value, String message) {
- isNotNull(value);
- if(value.length() <= 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isStringNonZeroLength"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## Object METHODS ###################################
-
- /**
- * Check that the object is non-null
- * @param value Value
- * @throws IllegalArgumentException If value is null
- */
- public static final void isNotNull(Object value) {
- isNotNull(value,null);
- }
-
- /**
- * Check that the object is non-null
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null
- */
- public static final void isNotNull(Object value, String message) {
- if(value == null) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNonNull"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the object is null
- * @param value Value
- * @throws IllegalArgumentException If value is non-null
- */
- public static final void isNull(Object value) {
- isNull(value,null);
- }
-
- /**
- * Check that the object is null
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is non-null
- */
- public static final void isNull(Object value, String message) {
- if(value != null) {
- final String msg = message != null ?
- message :
- "ArgCheck.isNull"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the object is an instance of the specified Class
- * @param theClass Class
- * @param value Value
- * @throws IllegalArgumentException If value is null
- */
- public static final void isInstanceOf(Class theClass, Object value) {
- isInstanceOf(theClass,value,null);
- }
-
- /**
- * Check that the object is an instance of the specified Class
- * @param theClass Class
- * @param value Value
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If value is null
- */
- public static final void isInstanceOf(Class theClass, Object value, String message) {
- isNotNull(value);
- if( ! theClass.isInstance(value) ) {
- final String msg = message != null ?
- message :
- "ArgCheck.isInstanceOf "; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- // ########################## COLLECTION METHODS ###################################
-
- /**
- * Check that the collection is not empty
- * @param collection Collection
- * @throws IllegalArgumentException If collection is null or empty
- */
- public static final void isNotEmpty(Collection collection) {
- isNotEmpty(collection,null);
- }
-
- /**
- * Check that the collection is not empty
- * @param collection Collection
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If collection is null or empty
- */
- public static final void isNotEmpty(Collection collection, String message) {
- isNotNull(collection);
- if(collection.isEmpty()) {
- final String msg = message != null ?
- message :
- "ArgCheck.isCollectionNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the map is not empty
- * @param map Map
- * @throws IllegalArgumentException If map is null or empty
- */
- public static final void isNotEmpty(Map map) {
- isNotEmpty(map,null);
- }
-
- /**
- * Check that the map is not empty
- * @param map Map
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If map is null or empty
- */
- public static final void isNotEmpty(Map map, String message) {
- isNotNull(map);
- if(map.isEmpty()) {
- final String msg = message != null ?
- message :
- "ArgCheck.isMapNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the array is not empty
- * @param array Array
- * @throws IllegalArgumentException If array is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(Object[] array) {
- isNotEmpty(array,null);
- }
-
- /**
- * Check that the array is not empty
- * @param array Array
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If array is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(Object[] array, String message) {
- isNotNull(array);
- if(array.length == 0) {
- final String msg = message != null ?
- message :
- "ArgCheck.isArrayNotEmpty"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the string is not empty
- * @param string String
- * @throws IllegalArgumentException If string is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(String string) {
- isNotZeroLength(string,null);
- }
-
- /**
- * Check that the string is not empty
- * @param string String
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If string is null or empty
- * @since 3.1
- */
- public static final void isNotEmpty(String string, String message) {
- isNotZeroLength(string,message);
- }
-
- /**
- * Asserts that the specified first object is not the same as (==) the specified second object.
- * @param firstObject The first object to assert as not the same as the second object.
- * @param firstName The name that will be used within the exception message for the first object, should an exception be
- * thrown; if null and <code>firstObject</code> is not null, <code>firstObject.toString()</code> will be
- * used.
- * @param secondObject The second object to assert as not the same as the first object.
- * @param secondName The name that will be used within the exception message for the second object, should an exception be
- * thrown; if null and <code>secondObject</code> is not null, <code>secondObject.toString()</code> will
- * be used.
- * @throws IllegalArgumentException If the specified objects are the same.
- * @since 3.1
- */
- public static void isNotSame(final Object firstObject, String firstName, final Object secondObject, String secondName) {
- if (firstObject == secondObject) {
- if (firstName == null && firstObject != null) {
- firstName = firstObject.toString();
- }
- if (secondName == null && secondObject != null) {
- secondName = secondObject.toString();
- }
- throw new IllegalArgumentException("ArgCheck.isNotSame"); //$NON-NLS-1$
- }
- }
-
- /**
- * Check that the collection contains the value
- * @param collection Collection to check
- * @param value Value to check for, may be null
- * @throws IllegalArgumentException If collection is null or doesn't contain value
- */
- public static final void contains(Collection collection, Object value) {
- contains(collection, value, null);
- }
-
- /**
- * Check that the collection contains the value
- * @param collection Collection to check
- * @param value Value to check for, may be null
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If collection is null or doesn't contain value
- */
- public static final void contains(Collection collection, Object value, String message) {
- isNotNull(collection);
- if(! collection.contains(value)) {
- final String msg = message != null ?
- message :
- "ArgCheck.contains"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
- /**
- * Check that the map contains the key
- * @param map Map to check
- * @param key Key to check for, may be null
- * @throws IllegalArgumentException If map is null or doesn't contain key
- */
- public static final void containsKey(Map map, Object key) {
- containsKey(map, key, null);
- }
-
- /**
- * Check that the map contains the key
- * @param map Map to check
- * @param key Key to check for, may be null
- * @param message Exception message if check fails
- * @throws IllegalArgumentException If map is null or doesn't contain key
- */
- public static final void containsKey(Map map, Object key, String message) {
- isNotNull(map);
- if(! map.containsKey(key)) {
- final String msg = message != null ?
- message :
- "ArgCheck.containsKey"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- }
-
-}
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java 2009-09-29 13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/ChecksumUtil.java 2009-09-29 14:23:43 UTC (rev 1490)
@@ -1,97 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.zip.CRC32;
-import java.util.zip.Checksum;
-
-/**
- * This utility class provides mechanisms for computing the checksum.
- */
-public class ChecksumUtil {
-
- protected static final int BUFFER_SIZE = 1024;
-
- /**
- * Compute and return the checksum (using the default CRC-32 algorithm)
- * of the contents on the specified stream.
- * This method closes the stream upon completion.
- * @param stream the stream containing the contents for which
- * the checksum is to be computed; may not be null
- * @return the Checksum for the contents
- * @throws AssertionError if <code>stream</code> is null
- * @throws IOException if there is an error reading the stream
- */
- public static Checksum computeChecksum( InputStream stream ) throws IOException {
- Checksum checksum = new CRC32();
- computeChecksum(stream,checksum);
- return checksum;
- }
-
- /**
- * Compute the checksum of the contents on the specified stream
- * using the supplied Checksum algorithm, and modify that
- * Checksum instance with the checksum value.
- * This method closes the stream upon completion.
- * @param stream the stream containing the contents for which
- * the checksum is to be computed; may not be null
- * @param algorithm the checksum algorithm to be used.
- * @return the number of bytes from <code>stream</code>
- * that were processed
- * @throws AssertionError if <code>stream</code> or
- * <code>algorithm</code> is null
- * @throws IOException if there is an error reading the stream
- */
- public static long computeChecksum( InputStream stream, Checksum algorithm ) throws IOException {
- byte[] buffer = new byte[BUFFER_SIZE];
- int n = 0;
- long sizeInBytes = 0;
-
- // Compute the checksum ...
- IOException ioe = null;
- try {
- while ((n = stream.read(buffer)) > -1){
- algorithm.update(buffer, 0, n);
- sizeInBytes += n;
- }
- } catch ( IOException e ) {
- ioe = e;
- } finally {
- try {
- stream.close();
- } catch ( IOException e ) {
- //Throw this only if there was no IOException from processing above
- if ( ioe == null ) {
- ioe = e;
- }
- }
- }
- if ( ioe != null ) {
- throw ioe;
- }
- return sizeInBytes;
- }
-
-}
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java 2009-09-29 13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/FileUtils.java 2009-09-29 14:23:43 UTC (rev 1490)
@@ -1,871 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- */
-
-package org.teiid.test.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-
-public final class FileUtils {
-
- public interface Constants {
- char CURRENT_FOLDER_SYMBOL_CHAR = '.';
- char DRIVE_SEPARATOR_CHAR = ':';
- char FILE_EXTENSION_SEPARATOR_CHAR = '.';
- char FILE_NAME_WILDCARD_CHAR = '*';
-
- String CURRENT_FOLDER_SYMBOL = String.valueOf(CURRENT_FOLDER_SYMBOL_CHAR);
- String DRIVE_SEPARATOR = String.valueOf(DRIVE_SEPARATOR_CHAR);
- String FILE_EXTENSION_SEPARATOR = String.valueOf(FILE_EXTENSION_SEPARATOR_CHAR);
- String FILE_NAME_WILDCARD = String.valueOf(FILE_NAME_WILDCARD_CHAR);
- String PARENT_FOLDER_SYMBOL = ".."; //$NON-NLS-1$
- }
-
- public static final char SEPARATOR = '/';
-
- public static int DEFAULT_BUFFER_SIZE = 2048;
- public static String TEMP_DIRECTORY;
- public static String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
- public static char[] LINE_SEPARATOR_CHARS = LINE_SEPARATOR.toCharArray();
-
- public final static String JAVA_IO_TEMP_DIR="java.io.tmpdir";//$NON-NLS-1$
- public final static char[] SUFFIX_class = ".class".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_CLASS = ".CLASS".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_java = ".java".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_JAVA = ".JAVA".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_jar = ".jar".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_JAR = ".JAR".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_zip = ".zip".toCharArray(); //$NON-NLS-1$
- public final static char[] SUFFIX_ZIP = ".ZIP".toCharArray(); //$NON-NLS-1$
-
-
- private static final String TEMP_FILE = "delete.me"; //$NON-NLS-1$
- private static final String TEMP_FILE_RENAMED = "delete.me.old"; //$NON-NLS-1$
-
-
-
- static {
- String tempDirPath = System.getProperty(JAVA_IO_TEMP_DIR);
- TEMP_DIRECTORY = (tempDirPath.endsWith(File.separator) ? tempDirPath : tempDirPath + File.separator);
- }
-
- private FileUtils() {}
-
- /**<p>
- * Convert the specified file name to end with the specified extension if it doesn't already end with an extension.
- * </p>
- * @param name
- * The file name.
- * @param extension
- * The extension to append to the file name.
- * @return The file name with an extension.
- * @since 4.0
- */
- public static String toFileNameWithExtension(final String name,
- final String extension) {
- return toFileNameWithExtension(name, extension, false);
- }
-
- /**<p>
- * Convert the specified file name to end with the specified extension if it doesn't already end with an extension. If force
- * is true, the specified extension will be appended to the name if the name doesn't end with that particular extension.
- * </p>
- * @param name
- * The file name.
- * @param extension
- * The extension to append to the file name.
- * @param force
- * Indicates whether to force the specified extension as the extension of the file name.
- * @return The file name with an extension.
- * @since 4.0
- */
- public static String toFileNameWithExtension(final String name,
- final String extension,
- final boolean force) {
- if (name == null) {
- final String msg = "FileUtils.The_name_of_the_file_may_not_be_null"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- if (extension == null) {
- final String msg = "FileUtils.The_file_extension_may_not_be_null"; //$NON-NLS-1$
- throw new IllegalArgumentException(msg);
- }
- if (name.endsWith(extension)) {
- return name;
- }
- if (!force && name.indexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR) >= 0) {
- return name;
- }
- final int nameLen = name.length() - 1;
- final int extLen = extension.length();
- final boolean nameEndsWithExtChr = (nameLen >= 0 && name.charAt(nameLen) == Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- final boolean extBeginsWithExtChr = (extLen > 0 && extension.charAt(0) == Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- if (nameEndsWithExtChr && extBeginsWithExtChr) {
- return name.substring(0, nameLen) + extension;
- }
- if (!nameEndsWithExtChr && !extBeginsWithExtChr) {
- return name + Constants.FILE_EXTENSION_SEPARATOR + extension;
- }
- return name + extension;
- }
-
- /**
- * Determine whether the specified name is valid for a file or folder on the current file system.
- * @param newName the new name to be checked
- * @return true if the name is null or contains no invalid characters for a folder or file, or false otherwise
- */
- public static boolean isFilenameValid( String newName ) {
- return true; //TODO: just catch an exception when the file is accessed or created
- }
-
- /**
- * Copy a file. Overwrites the destination file if it exists.
- * @param fromFileName
- * @param toFileName
- * @throws Exception
- * @since 4.3
- */
- public static void copy(String fromFileName, String toFileName) throws IOException {
- copy(fromFileName, toFileName, true);
- }
-
- /**
- * Copy a file
- * @param fromFileName
- * @param toFileName
- * @param overwrite whether to overwrite the destination file if it exists.
- * @throws MetaMatrixCoreException
- * @since 4.3
- */
- public static void copy(String fromFileName, String toFileName, boolean overwrite) throws IOException {
- File toFile = new File(toFileName);
-
- if (toFile.exists()) {
- if (overwrite) {
- toFile.delete();
- } else {
- final String msg = "FileUtils.File_already_exists " + toFileName; //$NON-NLS-1$
- throw new IOException(msg);
- }
- }
-
- File fromFile = new File(fromFileName);
- if (!fromFile.exists()) {
- throw new FileNotFoundException("FileUtils.File_does_not_exist " + fromFileName); //$NON-NLS-1$
- }
-
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(fromFile);
- write(fis, toFileName);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
-
- /**
- * Copy recursively the contents of <code>sourceDirectory</code> to
- * the <code>targetDirectory</code>. Note that <code>sourceDirectory</code>
- * will <b>NOT</b> be copied. If <code>targetDirectory</code> does not exist, it will be created.
- * @param sourceDirectory The source directory to copy
- * @param targetDirectory The target directory to copy to
- * @throws Exception If the source directory does not exist.
- * @since 4.3
- */
- public static void copyDirectoryContentsRecursively(File sourceDirectory, File targetDirectory) throws Exception {
- copyRecursively(sourceDirectory, targetDirectory, false);
- }
-
- /**
- * Copy file from orginating directory to the destination directory.
- *
- * @param orginDirectory
- * @param destDirectory
- * @param fileName
- * @throws Exception
- * @since 4.4
- */
- public static void copyFile(String orginDirectory,
- String destDirectory,
- String fileName) throws Exception {
-
- copyFile(orginDirectory, fileName, destDirectory, fileName);
- }
-
- /**
- * Copy file from orginating directory to the destination directory.
- *
- * @param orginDirectory
- * @param orginFileName
- * @param destDirectory
- * @param destFileName
- * @throws Exception
- * @since 4.4
- */
- public static void copyFile(String orginDirectory,
- String orginFileName,
- String destDirectory,
- String destFileName) throws Exception {
-
- FileUtils.copy(orginDirectory + File.separator + orginFileName, destDirectory + File.separator + destFileName);
- }
-
- /**
- * Copy recursively the <code>sourceDirectory</code> and all its contents
- * to the <code>targetDirectory</code>. If <code>targetDirectory</code>
- * does not exist, it will be created.
- * @param sourceDirectory The source directory to copy
- * @param targetDirectory The target directory to copy to
- * @throws Exception If the source directory does not exist.
- * @since 4.3
- */
- public static void copyDirectoriesRecursively(File sourceDirectory, File targetDirectory) throws Exception {
- copyRecursively(sourceDirectory, targetDirectory, true);
- }
-
- /**
- * Copy recursively from the <code>sourceDirectory</code> all its contents
- * to the <code>targetDirectory</code>. if
- * <code>includeSourceRoot<code> == <code>true</code>, copy <code>sourceDirectory</code>
- * itself, else only copy <code>sourceDirectory</code>'s contents.
- * If <code>targetDirectory</code> does not exist, it will be created.
- * @param sourceDirectory
- * @param targetDirectory
- * @throws FileNotFoundException
- * @throws Exception
- * @since 4.3
- */
- private static void copyRecursively(File sourceDirectory,
- File targetDirectory,
- boolean includeSourceRoot) throws FileNotFoundException,
- Exception {
- if (!sourceDirectory.exists()) {
- throw new FileNotFoundException("FileUtils.File_does_not_exist " + sourceDirectory); //$NON-NLS-1$
- }
-
- if (!sourceDirectory.isDirectory()) {
- throw new FileNotFoundException("FileUtils.Not_a_directory " + sourceDirectory); //$NON-NLS-1$
- }
-
- File targetDir = new File(targetDirectory.getAbsolutePath() + File.separatorChar + sourceDirectory.getName());
- if (includeSourceRoot) {
- // copy source directory
- targetDir.mkdir();
- } else {
- // copy only source directory contents
- targetDir = new File(targetDirectory.getAbsolutePath() + File.separatorChar);
- }
- File[] sourceFiles = sourceDirectory.listFiles();
- for (int i = 0; i < sourceFiles.length; i++) {
- File srcFile = sourceFiles[i];
- if (srcFile.isDirectory()) {
- File childTargetDir = new File(targetDir.getAbsolutePath());
- copyRecursively(srcFile, childTargetDir, true);
- } else {
- copy(srcFile.getAbsolutePath(), targetDir.getAbsolutePath() + File.separatorChar + srcFile.getName());
- }
- }
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, String fileName) throws IOException {
- File f = new File(fileName);
- write(is,f);
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, File f) throws IOException {
- write(is, f, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Write an InputStream to a file.
- */
- public static void write(InputStream is, File f, int bufferSize) throws IOException {
- f.delete();
- final File parentDir = f.getParentFile();
- if (parentDir !=null) {
- parentDir.mkdirs();
- }
-
- FileOutputStream fio = null;
- BufferedOutputStream bos = null;
- try {
- fio = new FileOutputStream(f);
- bos = new BufferedOutputStream(fio);
- if (bufferSize > 0) {
- byte[] buff = new byte[bufferSize];
- int bytesRead;
-
- // Simple read/write loop.
- while(-1 != (bytesRead = is.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- }
- bos.flush();
- } finally {
- if (bos != null) {
- bos.close();
- }
- if (fio != null) {
- fio.close();
- }
- }
- }
-
-
- /**
- * Write an File to an OutputStream
- * Note: this will not close the outputStream;
- */
- public static void write(File f, OutputStream outputStream) throws IOException {
- write(f, outputStream, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Write an File to an OutputStream
- * Note: this will not close the outputStream;
- */
- public static void write(File f, OutputStream outputStream, int bufferSize) throws IOException {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(f);
- write(fis, outputStream, bufferSize);
- } finally {
- if (fis != null) {
- fis.close();
- }
- }
- }
-
- /**
- * Write the given input stream to outputstream
- * Note: this will not close in/out streams
- */
- public static void write(InputStream fis, OutputStream outputStream, int bufferSize) throws IOException {
- byte[] buff = new byte[bufferSize];
- int bytesRead;
-
- // Simple read/write loop.
- while(-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
- outputStream.write(buff, 0, bytesRead);
- }
- outputStream.flush();
- }
-
- /**
- * Write a byte array to a file.
- */
- public static void write(byte[] data, String fileName) throws IOException {
- ByteArrayInputStream bais = null;
- InputStream is = null;
- try {
- bais = new ByteArrayInputStream(data);
- is = new BufferedInputStream(bais);
-
- write(is, fileName);
- } finally {
- if (is != null) {
- is.close();
- }
- if (bais != null) {
- bais.close();
- }
- }
- }
-
- /**
- * Write a byte array to a file.
- */
- public static void write(byte[] data, File file) throws IOException {
- ByteArrayInputStream bais = null;
- InputStream is = null;
- try {
- bais = new ByteArrayInputStream(data);
- is = new BufferedInputStream(bais);
-
- write(is, file);
- } finally {
- if (is != null) {
- is.close();
- }
- if (bais != null) {
- bais.close();
- }
- }
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files that
- * exist in the specified directory or any nested directories
- * @return File[] of files in the directory
- */
- public static File[] findAllFilesInDirectoryRecursively(final String dir) {
-
- // Recursively navigate through the contents of this directory
- // gathering up all the files
- List allFiles = new ArrayList();
- File directory = new File(dir);
- addFilesInDirectoryRecursively(directory, allFiles);
-
- return (File[])allFiles.toArray(new File[allFiles.size()]);
-
- }
-
- private static void addFilesInDirectoryRecursively(final File directory, final List allFiles) {
- File[] files = directory.listFiles();
- if (files != null) {
- for (int i=0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- addFilesInDirectoryRecursively(file, allFiles);
- } else {
- allFiles.add(file);
- }
- }
- }
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files that exist in the directory
- *
- * @return File[] of files in the directory
- */
- public static File[] findAllFilesInDirectory(String dir) {
-
- // Find all files in the specified directory
- File modelsDirFile = new File(dir);
- FileFilter fileFilter = new FileFilter() {
-
- public boolean accept(File file) {
- if (file.isDirectory()) {
- return false;
- }
-
- String fileName = file.getName();
-
- if (fileName == null || fileName.length() == 0) {
- return false;
- }
-
- return true;
-
- }
- };
-
- File[] modelFiles = modelsDirFile.listFiles(fileFilter);
-
- return modelFiles;
-
- }
-
- /**
- * Returns a <code>File</code> array that will contain all the files that
- * exist in the directory that have the specified extension.
- * @return File[] of files having a certain extension
- */
- public static File[] findAllFilesInDirectoryHavingExtension(String dir, final String extension) {
-
- // Find all files in that directory that end in XML and attempt to
- // load them into the runtime metadata database.
- File modelsDirFile = new File(dir);
- FileFilter fileFilter = new FileFilter() {
- public boolean accept(File file) {
- if(file.isDirectory()) {
- return false;
- }
-
-
- String fileName = file.getName();
-
- if (fileName==null || fileName.length()==0) {
- return false;
- }
-
- return (fileName.endsWith(extension));
- // here we check to see if the file is an .xml file...
-// int index = fileName.lastIndexOf("."); //$NON-NLS-1$
-//
-// if (index<0 || index==fileName.length()) {
-// return false;
-// }
-//
-// if (fileName.substring(index, fileName.length()).equalsIgnoreCase(extension)) {
-// return true;
-// }
-// return false;
- }
- };
-
- File[] modelFiles = modelsDirFile.listFiles(fileFilter);
-
- return modelFiles;
-
- }
-
- /**
- * @param string
- * @return
- */
- public static String getFilenameWithoutExtension( final String filename ) {
- if ( filename == null || filename.length() == 0 ) {
- return filename;
- }
- final int extensionIndex = filename.lastIndexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR);
- if ( extensionIndex == -1 ) {
- return filename; // not found
- }
- if ( extensionIndex == 0 ) {
- return ""; //$NON-NLS-1$
- }
- return filename.substring(0,extensionIndex);
- }
-
- public static String getBaseFileNameWithoutExtension(String path) {
- return StringUtil.getFirstToken(StringUtil.getLastToken(path, "/"), "."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Obtains the file extension of the specified <code>File</code>. The extension is considered to be all the
- * characters after the last occurrence of {@link Constants#FILE_EXTENSION_SEPARATOR_CHAR} in the pathname
- * of the input.
- * @param theFile the file whose extension is being requested
- * @return the extension or <code>null</code> if not found
- * @since 4.2
- */
- public static String getExtension(File theFile) {
- return getExtension(theFile.getPath());
- }
-
- /**
- * Obtains the file extension of the specified file name. The extension is considered to be all the
- * characters after the last occurrence of {@link Constants#FILE_EXTENSION_SEPARATOR_CHAR}.
- * @param theFileName the file whose extension is being requested
- * @return the extension or <code>null</code> if not found
- * @since 4.2
- */
- public static String getExtension(String theFileName) {
- String result = null;
- final int index = theFileName.lastIndexOf(Constants.FILE_EXTENSION_SEPARATOR_CHAR);
-
- // make sure extension char is found and is not the last char in the path
- if ((index != -1) && ((index + 1) != theFileName.length())) {
- result = theFileName.substring(index + 1);
- }
-
- return result;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".jar") || str.toLowerCase().endsWith(".zip")
- * implementation is not creating extra strings.
- */
- public final static boolean isArchiveFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAR.length;
- if (nameLength < suffixLength) return false;
-
- // try to match as JAR file
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_jar[suffixIndex] && c != SUFFIX_JAR[suffixIndex]) {
-
- // try to match as ZIP file
- suffixLength = SUFFIX_ZIP.length;
- if (nameLength < suffixLength) return false;
- for (int j = 0; j < suffixLength; j++) {
- c = name.charAt(nameLength - j - 1);
- suffixIndex = suffixLength - j - 1;
- if (c != SUFFIX_zip[suffixIndex] && c != SUFFIX_ZIP[suffixIndex]) return false;
- }
- return true;
- }
- }
- return true;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".class")
- * implementation is not creating extra strings.
- */
- public final static boolean isClassFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_CLASS.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex]) return false;
- }
- return true;
- }
-
- /**
- * Returns true iff str.toLowerCase().endsWith(".java")
- * implementation is not creating extra strings.
- */
- public final static boolean isJavaFileName(String name) {
- int nameLength = name == null ? 0 : name.length();
- int suffixLength = SUFFIX_JAVA.length;
- if (nameLength < suffixLength) return false;
-
- for (int i = 0; i < suffixLength; i++) {
- char c = name.charAt(nameLength - i - 1);
- int suffixIndex = suffixLength - i - 1;
- if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false;
- }
- return true;
- }
-
-
- public static File convertByteArrayToFile(final byte[] contents, final String parentDirectoryPath, final String fileName) {
- if (contents != null) {
- FileOutputStream os = null;
- try {
- final File temp = new File(parentDirectoryPath,fileName);
- os = new FileOutputStream(temp);
- os.write(contents);
- return temp;
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (os != null) {
- try {
- os.close();
- } catch (IOException e1) {
- // do nothing
- }
- }
- }
- }
- return null;
- }
-
- public static void removeDirectoryAndChildren(File directory) {
- removeChildrenRecursively(directory);
- if(!directory.delete()) {
- directory.deleteOnExit();
- }
- }
-
- public static void removeChildrenRecursively(File directory) {
- File[] files = directory.listFiles();
- if(files != null) {
- for(int i=0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- removeDirectoryAndChildren(file);
- } else {
- if(!file.delete()) {
- file.deleteOnExit();
- }
- }
- }
- }
- }
-
- /**
- * Builds a file directory path from a physical location and a location that needs
- * to be appended to the physical. This is used so that the correct File.separator
- * is used and that no additional separator is added when not needed.
- * @param physicalDirectory
- * @param appendLocation
- * @return
- * @since 4.3
- */
- public static String buildDirectoryPath(String[] paths) {
-// String physicalDirectory, String appendLocation) {
-
- if (paths == null || paths.length == 0) {
- return ""; //$NON-NLS-1$
- }
- if (paths.length == 1) {
- return (paths[0]!=null?paths[0]:"");//$NON-NLS-1$
- }
- int l = paths.length;
- StringBuffer sb = new StringBuffer();
- for (int cur=0;cur<l; cur++) {
- int next = cur+1;
-
- String value = paths[cur]!=null?paths[cur]:"";//$NON-NLS-1$
- if (value.equals("")) {//$NON-NLS-1$
- continue;
- }
- sb.append(value);
-
- if (next < l) {
- String nextValue = paths[next]!=null?paths[next]:"";//$NON-NLS-1$
- if (value.endsWith(File.separator)) {
-
- } else if (!nextValue.startsWith(File.separator)) {
- sb.append(File.separator);
- }
-
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Compute checksum for the given file.
- * @param f The file for which checksum needs to be computed
- * @return The checksum
- * @since 4.3
- */
- public static long getCheckSum(final File f) throws Exception {
- ArgCheck.isNotNull(f);
- FileInputStream is = null;
- try {
- is = new FileInputStream(f);
- return ChecksumUtil.computeChecksum(is).getValue();
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException err1) {
- }
- }
- }
- }
-
-
- /**
- * Test whether it's possible to read and write files in the specified directory.
- * @param dirPath Name of the directory to test
- * @throws MetaMatrixException
- * @since 4.3
- */
- public static void testDirectoryPermissions(String dirPath) throws Exception {
-
- //try to create a file
- File tmpFile = new File(dirPath + File.separatorChar + TEMP_FILE);
- boolean success = false;
- try {
- success = tmpFile.createNewFile();
- } catch (IOException e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_create_file_in " + dirPath; //$NON-NLS-1$
- throw new Exception(msg);
- }
-
-
- //test if file can be written to
- if (!tmpFile.canWrite()) {
- final String msg = "FileUtils.Unable_to_write_file_in " + dirPath; //$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be read
- if (!tmpFile.canRead()) {
- final String msg = "FileUtils.Unable_to_read_file_in " + dirPath; //$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be renamed
- File newFile = new File(dirPath + File.separatorChar + TEMP_FILE_RENAMED);
- success = false;
- try {
- success = tmpFile.renameTo(newFile);
- } catch (Exception e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_rename_file_in " + dirPath; //$NON-NLS-1$
- throw new Exception(msg);
- }
-
- //test if file can be deleted
- success = false;
- try {
- success = newFile.delete();
- } catch (Exception e) {
- }
- if (!success) {
- final String msg = "FileUtils.Unable_to_delete_file_in " + dirPath; //$NON-NLS-1$
- throw new Exception(msg);
- }
- }
-
- /**
- * Rename a file.
- * @param oldFilePath
- * @param newFilePath
- * @param overwrite If true, overwrite the old file if it exists. If false, throw an exception if the old file exists.
- * @throws MetaMatrixCoreException
- * @since 4.3
- */
- public static void rename(String oldFilePath, String newFilePath, boolean overwrite) throws IOException {
- File oldFile = new File(oldFilePath);
- File newFile = new File(newFilePath);
-
- if (newFile.exists()) {
- if (overwrite) {
- newFile.delete();
- } else {
- final String msg = "FileUtils.File_already_exists " + newFilePath; //$NON-NLS-1$
- throw new IOException(msg);
- }
- }
-
- boolean renamed = oldFile.renameTo(newFile);
-
- //Sometimes file.renameTo will silently fail, for example attempting to rename from different UNIX partitions.
- //Try to copy instead.
- if (!renamed) {
- copy(oldFilePath, newFilePath);
- oldFile.delete();
- }
- }
-
-
-
-
-
- public static void remove(String filePath) throws IOException {
- File file = new File(filePath);
- if (file.exists()) {
- file.delete();
- }
- }
-
-}
\ No newline at end of file
Deleted: trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java
===================================================================
--- trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java 2009-09-29 13:52:23 UTC (rev 1489)
+++ trunk/test-integration/db/src/main/java/org/teiid/test/util/StringUtil.java 2009-09-29 14:23:43 UTC (rev 1490)
@@ -1,906 +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.
- *
- * Copyright (c) 2000, 2008 IBM Corporation and others.
- * All rights reserved.
- * This code is made available under the terms of the Eclipse Public
- * License, version 1.0.
- */
-
-package org.teiid.test.util;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.regex.Pattern;
-
-/**
- * This is a common place to put String utility methods.
- */
-public final class StringUtil {
-
- public interface Constants {
- char CARRIAGE_RETURN_CHAR = '\r';
- char LINE_FEED_CHAR = '\n';
- char NEW_LINE_CHAR = LINE_FEED_CHAR;
- char SPACE_CHAR = ' ';
- char DOT_CHAR = '.';
- char TAB_CHAR = '\t';
-
- String CARRIAGE_RETURN = String.valueOf(CARRIAGE_RETURN_CHAR);
- String EMPTY_STRING = ""; //$NON-NLS-1$
- String DBL_SPACE = " "; //$NON-NLS-1$
- String LINE_FEED = String.valueOf(LINE_FEED_CHAR);
- String NEW_LINE = String.valueOf(NEW_LINE_CHAR);
- String SPACE = String.valueOf(SPACE_CHAR);
- String DOT = String.valueOf(DOT_CHAR);
- String TAB = String.valueOf(TAB_CHAR);
-
- String[] EMPTY_STRING_ARRAY = new String[0];
-
- // all patterns below copied from Eclipse's PatternConstructor class.
- final Pattern PATTERN_BACK_SLASH = Pattern.compile("\\\\"); //$NON-NLS-1$
- final Pattern PATTERN_QUESTION = Pattern.compile("\\?"); //$NON-NLS-1$
- final Pattern PATTERN_STAR = Pattern.compile("\\*"); //$NON-NLS-1$
- }
-
- /**
- * The String "'"
- */
- public static final String SINGLE_QUOTE = "'"; //$NON-NLS-1$
-
- /**
- * The name of the System property that specifies the string that should be used to separate
- * lines. This property is a standard environment property that is usually set automatically.
- */
- public static final String LINE_SEPARATOR_PROPERTY_NAME = "line.separator"; //$NON-NLS-1$
-
- /**
- * The String that should be used to separate lines; defaults to
- * {@link #NEW_LINE}
- */
- public static final String LINE_SEPARATOR = System.getProperty(LINE_SEPARATOR_PROPERTY_NAME, Constants.NEW_LINE);
-
- public static final Comparator CASE_INSENSITIVE_ORDER = String.CASE_INSENSITIVE_ORDER;
-
- public static final Comparator CASE_SENSITIVE_ORDER = new Comparator() {
- /**
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- * @since 4.2
- */
- public int compare(Object o1, Object o2) {
- if ( o1 == o2 ) {
- return 0;
- }
- return ((String)o1).compareTo((String)o2);
- }
- };
-
- public static String getLineSeparator() {
- return LINE_SEPARATOR;
- }
-
- /**
- * Utility to return a string enclosed in ''.
- * Creation date: (12/2/99 12:05:10 PM)
- */
- public static String enclosedInSingleQuotes(String aString) {
- StringBuffer sb = new StringBuffer();
- sb.append(SINGLE_QUOTE);
- sb.append(aString);
- sb.append(SINGLE_QUOTE);
- return sb.toString();
- }
-
- public static String removeChars(final String value, final char[] chars) {
- final StringBuffer result = new StringBuffer();
- if (value != null && chars != null && chars.length > 0) {
- final String removeChars = String.valueOf(chars);
- for (int i = 0; i < value.length(); i++) {
- final String character = value.substring(i, i + 1);
- if (removeChars.indexOf(character) == -1) {
- result.append(character);
- }
- }
- } else {
- result.append(value);
- }
- return result.toString();
- }
-
- /**
- * Join string pieces and separate with a delimiter. Similar to the perl function of
- * the same name. If strings or delimiter are null, null is returned. Otherwise, at
- * least an empty string will be returned.
- * @see #split
- *
- * @param strings String pieces to join
- * @param delimiter Delimiter to put between string pieces
- * @return One merged string
- */
- public static String join(List strings, String delimiter) {
- if(strings == null || delimiter == null) {
- return null;
- }
-
- StringBuffer str = new StringBuffer();
-
- // This is the standard problem of not putting a delimiter after the last
- // string piece but still handling the special cases. A typical way is to check every
- // iteration if it is the last one and skip the delimiter - this is avoided by
- // looping up to the last one, then appending just the last one.
-
- // First we loop through all but the last one (if there are at least 2) and
- // put the piece and a delimiter after it. An iterator is used to walk the list.
- int most = strings.size()-1;
- if(strings.size() > 1) {
- Iterator iter = strings.iterator();
- for(int i=0; i<most; i++) {
- str.append(iter.next());
- str.append(delimiter);
- }
- }
-
- // If there is at least one element, put the last one on with no delimiter after.
- if(strings.size() > 0) {
- str.append(strings.get(most));
- }
-
- return str.toString();
- }
-
- /**
- * Return a stringified version of the array.
- * @param array the array
- * @param delim the delimiter to use between array components
- * @return the string form of the array
- */
- public static String toString( final Object[] array, final String delim ) {
- if ( array == null ) {
- return ""; //$NON-NLS-1$
- }
- if ( array.length == 0 ) {
- return "[]"; //$NON-NLS-1$
- }
- final StringBuffer sb = new StringBuffer();
- sb.append('[');
- for (int i = 0; i < array.length; ++i) {
- if ( i != 0 ) {
- sb.append(delim);
- }
- sb.append(array[i]);
- }
- sb.append(']');
- return sb.toString();
- }
-
- /**
- * Return a stringified version of the array, using a ',' as a delimiter
- * @param array the array
- * @return the string form of the array
- * @see #toString(Object[], String)
- */
- public static String toString( final Object[] array ) {
- return toString(array,","); //$NON-NLS-1$
- }
-
- /**
- * Split a string into pieces based on delimiters. Similar to the perl function of
- * the same name. The delimiters are not included in the returned strings.
- * @see #join
- *
- * @param str Full string
- * @param splitter Characters to split on
- * @return List of String pieces from full string
- */
- public static List split(String str, String splitter) {
- StringTokenizer tokens = new StringTokenizer(str, splitter);
- ArrayList l = new ArrayList(tokens.countTokens());
- while(tokens.hasMoreTokens()) {
- l.add(tokens.nextToken());
- }
- return l;
- }
-
- /**
- * Break a string into pieces based on matching the full delimiter string in the text.
- * The delimiter is not included in the returned strings.
- * @param target The text to break up.
- * @param delimiter The sub-string which is used to break the target.
- * @return List of String from the target.
- */
- public static List splitOnEntireString(String target, String delimiter) {
- ArrayList result = new ArrayList();
- if (delimiter.length() > 0) {
- int index = 0;
- int indexOfNextMatch = target.indexOf(delimiter);
- while (indexOfNextMatch > -1) {
- result.add(target.substring(index, indexOfNextMatch));
- index = indexOfNextMatch + delimiter.length();
- indexOfNextMatch = target.indexOf(delimiter, index);
- }
- if (index <= target.length()) {
- result.add(target.substring(index));
- }
- } else {
- result.add(target);
- }
- return result;
- }
-
- /**
- * Split a string into pieces based on delimiters preserving spaces in
- * quoted substring as on element in the returned list. The delimiters are
- * not included in the returned strings.
- * @see #join
- *
- * @param str Full string
- * @param splitter Characters to split on
- * @return List of String pieces from full string
- */
- public static List splitPreservingQuotedSubstring(String str, String splitter) {
- ArrayList l = new ArrayList();
- StringTokenizer tokens = new StringTokenizer(str, splitter);
- StringBuffer token = new StringBuffer();
- while(tokens.hasMoreTokens()) {
- token.setLength(0);
- token.append(tokens.nextToken());
- if ( token.charAt(0) == '"' ) {
- token.deleteCharAt(0);
- while ( tokens.hasMoreTokens() ) {
- token.append(Constants.SPACE + tokens.nextToken());
- if ( token.charAt(token.length() -1) == '"' ) {
- token.deleteCharAt(token.length() - 1);
- break;
- }
- }
- }
- l.add(token.toString().trim());
- }
- return l;
- }
-
- /*
- * Replace a single occurrence of the search string with the replace string
- * in the source string. If any of the strings is null or the search string
- * is zero length, the source string is returned.
- * @param source the source string whose contents will be altered
- * @param search the string to search for in source
- * @param replace the string to substitute for search if present
- * @return source string with the *first* occurrence of the search string
- * replaced with the replace string
- */
- public static String replace(String source, String search, String replace) {
- if (source != null && search != null && search.length() > 0 && replace != null) {
- int start = source.indexOf(search);
- if (start > -1) {
- return new StringBuffer(source).replace(start, start + search.length(), replace).toString();
- }
- }
- return source;
- }
-
- /*
- * Replace all occurrences of the search string with the replace string
- * in the source string. If any of the strings is null or the search string
- * is zero length, the source string is returned.
- * @param source the source string whose contents will be altered
- * @param search the string to search for in source
- * @param replace the string to substitute for search if present
- * @return source string with *all* occurrences of the search string
- * replaced with the replace string
- */
- public static String replaceAll(String source, String search, String replace) {
- if (source != null && search != null && search.length() > 0 && replace != null) {
- int start = source.indexOf(search);
- if (start > -1) {
- StringBuffer newString = new StringBuffer(source);
- replaceAll(newString, search, replace);
- return newString.toString();
- }
- }
- return source;
- }
-
- public static void replaceAll(StringBuffer source, String search, String replace) {
- if (source != null && search != null && search.length() > 0 && replace != null) {
- int start = source.toString().indexOf(search);
- while (start > -1) {
- int end = start + search.length();
- source.replace(start, end, replace);
- start = source.toString().indexOf(search, start + replace.length());
- }
- }
- }
-
- /**
- * Simple static method to tuncate Strings to given length.
- * @param in the string that may need tuncating.
- * @param len the lenght that the string should be truncated to.
- * @return a new String containing chars with length <= len or <code>null</code>
- * if input String is <code>null</code>.
- */
- public static String truncString(String in, int len) {
- String out = in;
- if ( in != null && len > 0 && in.length() > len ) {
- out = in.substring(0, len);
- }
- return out;
- }
-
- /**
- * Simple utility method to wrap a string by inserting line separators creating
- * multiple lines each with length no greater than the user specified maximum.
- * The method parses the given string into tokens using a space delimiter then
- * reassembling the tokens into the resulting string while inserting separators
- * when required. If the number of characters in a single token is greater
- * than the specified maximum, the token will not be split but instead the
- * maximum will be exceeded.
- * @param str the string that may need tuncating.
- * @param maxCharPerLine the max number of characters per line
- * @return a new String containing line separators or the original string
- * if its length was less than the maximum.
- */
- public static String wrap(String str, int maxCharPerLine) {
- int strLength = str.length();
- if (strLength > maxCharPerLine) {
- StringBuffer sb = new StringBuffer(str.length()+(strLength/maxCharPerLine)+1);
- strLength = 0;
- List tokens = StringUtil.split(str,Constants.SPACE);
- Iterator itr = tokens.iterator();
- while (itr.hasNext()) {
- String token = (String) itr.next();
- if ( strLength+token.length() > maxCharPerLine ) {
-// sb.append(getLineSeparator());
- sb.append(Constants.NEW_LINE);
- strLength = 0;
- }
- sb.append(token);
- sb.append(Constants.SPACE);
- strLength += token.length()+1;
- }
- return sb.toString();
- }
- return str;
- }
-
- /**
- * Return the tokens in a string in a list. This is particularly
- * helpful if the tokens need to be processed in reverse order. In that case,
- * a list iterator can be acquired from the list for reverse order traversal.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return List of string tokens contained in the tokenized string
- */
- public static List getTokens(String str, String delimiter) {
- ArrayList l = new ArrayList();
- StringTokenizer tokens = new StringTokenizer(str, delimiter);
- while(tokens.hasMoreTokens()) {
- l.add(tokens.nextToken());
- }
- return l;
- }
-
- /**
- * Return the number of tokens in a string that are seperated by the delimiter.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return Number of tokens seperated by the delimiter
- */
- public static int getTokenCount(String str, String delimiter) {
- StringTokenizer tokens = new StringTokenizer(str, delimiter);
- return tokens.countTokens();
- }
-
- /**
- * Return the number of occurrences of token string that occurs in input string.
- * Note: token is case sensitive.
- *
- * @param input
- * @param token
- * @return int
- */
- public static int occurrences(String input, String token) {
- int num = 0;
- int index = input.indexOf(token);
- while (index >= 0) {
- num++;
- index = input.indexOf(token, index+1);
- }
- return num;
- }
-
- /**
- * Return the last token in the string.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return the last token contained in the tokenized string
- */
- public static String getLastToken(String str, String delimiter) {
- if (str == null) {
- return Constants.EMPTY_STRING;
- }
- int beginIndex = 0;
- if (str.lastIndexOf(delimiter) > 0) {
- beginIndex = str.lastIndexOf(delimiter)+1;
- }
- return str.substring(beginIndex,str.length());
- }
-
-
- /**
- * Return the first token in the string.
- *
- * @param str String to be tokenized
- * @param delimiter Characters which are delimit tokens
- * @return the first token contained in the tokenized string
- */
- public static String getFirstToken(String str, String delimiter) {
- if (str == null) {
- return Constants.EMPTY_STRING;
- }
- int endIndex = str.indexOf(delimiter);
- if (endIndex < 0) {
- endIndex = str.length();
- }
- return str.substring(0,endIndex);
- }
-
-
- public static String computePluralForm(String str) {
- return computePluralForm(str, Constants.EMPTY_STRING);
- }
-
- public static String computePluralForm(String str, String defaultValue ) {
- if ( str == null || str.length() == 0 ) {
- return defaultValue;
- }
- String result = str;
- if ( result.endsWith("es") ) { //$NON-NLS-1$
- // do nothing
- } else if ( result.endsWith("ss") || //$NON-NLS-1$
- result.endsWith("x") || //$NON-NLS-1$
- result.endsWith("ch") || //$NON-NLS-1$
- result.endsWith("sh") ) { //$NON-NLS-1$
- result = result + "es"; //$NON-NLS-1$
- } else if ( result.endsWith("y") && ! ( //$NON-NLS-1$
- result.endsWith("ay") || //$NON-NLS-1$
- result.endsWith("ey") || //$NON-NLS-1$
- result.endsWith("iy") || //$NON-NLS-1$
- result.endsWith("oy") || //$NON-NLS-1$
- result.endsWith("uy") || //$NON-NLS-1$
- result.equalsIgnoreCase("any") ) ) { //$NON-NLS-1$
- result = result.substring(0, result.length()-1) + "ies"; //$NON-NLS-1$
- } else {
- result += "s"; //$NON-NLS-1$
- }
- return result;
- }
-
- public static String getStackTrace( final Throwable t ) {
- final ByteArrayOutputStream bas = new ByteArrayOutputStream();
- final PrintWriter pw = new PrintWriter(bas);
- t.printStackTrace(pw);
- pw.close();
- return bas.toString();
- }
-
- /**
- * Returns whether the specified text represents a boolean value, i.e., whether it equals "true" or "false"
- * (case-insensitive).
- * @since 4.0
- */
- public static boolean isBoolean(final String text) {
- return (Boolean.TRUE.toString().equalsIgnoreCase(text) || Boolean.FALSE.toString().equalsIgnoreCase(text));
- }
-
- /**<p>
- * Returns whether the specified text is either empty or null.
- * </p>
- * @param text The text to check; may be null;
- * @return True if the specified text is either empty or null.
- * @since 4.0
- */
- public static boolean isEmpty(final String text) {
- return (text == null || text.length() == 0);
- }
-
- /**
- * Returns the index within this string of the first occurrence of the
- * specified substring. The integer returned is the smallest value
- * <i>k</i> such that:
- * <blockquote><pre>
- * this.startsWith(str, <i>k</i>)
- * </pre></blockquote>
- * is <code>true</code>.
- *
- * @param text any string.
- * @param str any string.
- * @return if the str argument occurs as a substring within text,
- * then the index of the first character of the first
- * such substring is returned; if it does not occur as a
- * substring, <code>-1</code> is returned. If the text or
- * str argument is null or empty then <code>-1</code> is returned.
- */
- public static int indexOfIgnoreCase(final String text, final String str) {
- if (isEmpty(text)) {
- return -1;
- }
- if (isEmpty(str)) {
- return -1;
- }
- final String lowerText = text.toLowerCase();
- final String lowerStr = str.toLowerCase();
- return lowerText.indexOf(lowerStr);
- }
-
- /**
- * Tests if the string starts with the specified prefix.
- *
- * @param text the string to test.
- * @param prefix the prefix.
- * @return <code>true</code> if the character sequence represented by the
- * argument is a prefix of the character sequence represented by
- * this string; <code>false</code> otherwise.
- * Note also that <code>true</code> will be returned if the
- * prefix is an empty string or is equal to the text
- * <code>String</code> object as determined by the
- * {@link #equals(Object)} method. If the text or
- * prefix argument is null <code>false</code> is returned.
- * @since JDK1. 0
- */
- public static boolean startsWithIgnoreCase(final String text, final String prefix) {
- if (isEmpty(text)) {
- return false;
- }
- if (prefix == null) {
- return false;
- }
- int textLength = text.length();
- int prefixLength = prefix.length();
- if (prefixLength == 0) {
- return true;
- }
- if (prefixLength > textLength) {
- return false;
- }
- char[] chArray = prefix.toCharArray();
- for (int i = 0; i != chArray.length; ++i) {
- char ch1 = chArray[i];
- char ch2 = text.charAt(i);
- if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2)) {
- // continue
- } else {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Tests if the string ends with the specified suffix.
- *
- * @param text the string to test.
- * @param suffix the suffix.
- * @return <code>true</code> if the character sequence represented by the
- * argument is a suffix of the character sequence represented by
- * this object; <code>false</code> otherwise. Note that the
- * result will be <code>true</code> if the suffix is the
- * empty string or is equal to this <code>String</code> object
- * as determined by the {@link #equals(Object)} method. If the text or
- * suffix argument is null <code>false</code> is returned.
- */
- public static boolean endsWithIgnoreCase(final String text, final String suffix) {
- if (isEmpty(text)) {
- return false;
- }
- if (suffix == null) {
- return false;
- }
- int textLength = text.length();
- int suffixLength = suffix.length();
- if (suffixLength == 0) {
- return true;
- }
- if (suffixLength > textLength) {
- return false;
- }
- int offset = textLength - suffixLength;
- char[] chArray = suffix.toCharArray();
- for (int i = 0; i != chArray.length; ++i) {
- char ch1 = chArray[i];
- char ch2 = text.charAt(offset + i);
- if (ch1 == ch2 || Character.toLowerCase(ch1) == Character.toLowerCase(ch2)) {
- // continue
- } else {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Determine if the string passed in has all digits as its contents
- * @param str
- * @return true if digits; false otherwise
- */
- public static boolean isDigits(String str) {
- for(int i=0; i<str.length(); i++) {
- if(!StringUtil.isDigit(str.charAt(i))) {
- return false;
- }
- }
- return true;
- }
- //============================================================================================================================
- // Constructors
-
- /**<p>
- * Prevents instantiation.
- * </p>
- * @since 4.0
- */
- private StringUtil() {
- }
-
- /*
- * Converts user string to regular expres '*' and '?' to regEx variables.
- * copied from eclipse's PatternConstructor
- */
- static String asRegEx(String pattern) {
- // Replace \ with \\, * with .* and ? with .
- // Quote remaining characters
- String result1 = Constants.PATTERN_BACK_SLASH.matcher(pattern).replaceAll(
- "\\\\E\\\\\\\\\\\\Q"); //$NON-NLS-1$
- String result2 = Constants.PATTERN_STAR.matcher(result1).replaceAll(
- "\\\\E.*\\\\Q"); //$NON-NLS-1$
- String result3 = Constants.PATTERN_QUESTION.matcher(result2).replaceAll(
- "\\\\E.\\\\Q"); //$NON-NLS-1$
- return "\\Q" + result3 + "\\E"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Creates a regular expression pattern from the pattern string (which is
- * our old 'StringMatcher' format). Copied from Eclipse's PatternConstructor class.
- *
- * @param pattern
- * The search pattern
- * @param isCaseSensitive
- * Set to <code>true</code> to create a case insensitve pattern
- * @return The created pattern
- */
- public static Pattern createPattern(String pattern, boolean isCaseSensitive) {
- if (isCaseSensitive)
- return Pattern.compile(asRegEx(pattern));
- return Pattern.compile(asRegEx(pattern), Pattern.CASE_INSENSITIVE
- | Pattern.UNICODE_CASE);
- }
-
- /**
- * Removes extraneous whitespace from a string. By it's nature, it will be trimmed also.
- * @param raw
- * @return
- * @since 5.0
- */
- public static String collapseWhitespace(String raw) {
- StringBuffer rv = new StringBuffer(raw.length());
-
- StringTokenizer izer = new StringTokenizer(raw, " "); //$NON-NLS-1$
- while (izer.hasMoreTokens()) {
- String tok = izer.nextToken();
- // Added one last check here so we don't append a "space" on the end of the string
- rv.append(tok);
- if( izer.hasMoreTokens() ) {
- rv.append(' ');
- }
- } // endwhile
-
- return rv.toString();
- }
-
- /**
- * If input == null OR input.length() < desiredLength, pad to desiredLength with spaces.
- * If input.length() > desiredLength, chop at desiredLength.
- * @param input Input text
- * @param desiredLength Desired length
- * @return
- * @since 5.0
- */
- public static String toFixedLength(String input, int desiredLength) {
- if(input == null) {
- input = ""; //$NON-NLS-1$
- }
-
- if(input.length() == desiredLength) {
- return input;
- }
-
- if(input.length() < desiredLength) {
- StringBuffer str = new StringBuffer(input);
- int needSpaces = desiredLength - input.length();
- for(int i=0; i<needSpaces; i++) {
- str.append(' ');
- }
- return str.toString();
- }
-
- // Else too long - chop
- return input.substring(0, desiredLength);
- }
-
-
- public static boolean isLetter(char c) {
- return isBasicLatinLetter(c) || Character.isLetter(c);
- }
- public static boolean isDigit(char c) {
- return isBasicLatinDigit(c) || Character.isDigit(c);
- }
- public static boolean isLetterOrDigit(char c) {
- return isBasicLatinLetter(c) || isBasicLatinDigit(c) || Character.isLetterOrDigit(c);
- }
-
- public static String toUpperCase(String str) {
- String newStr = convertBasicLatinToUpper(str);
- if (newStr == null) {
- return str.toUpperCase();
- }
- return newStr;
- }
-
- public static String toLowerCase(String str) {
- String newStr = convertBasicLatinToLower(str);
- if (newStr == null) {
- return str.toLowerCase();
- }
- return newStr;
- }
-
- /**
- * Create a valid filename from the given String.
- *
- * @param str The String to convert to a valid filename.
- * @param defaultName The default name to use if only special characters exist.
- * @return String A valid filename.
- */
- public static String createFileName(String str) {
-
- /** Replace some special chars */
- str = str.replaceAll(" \\| ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll(">", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll(": ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll(" ", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll("\\?", "_"); //$NON-NLS-1$ //$NON-NLS-2$
- str = str.replaceAll("/", "_"); //$NON-NLS-1$ //$NON-NLS-2$
-
- /** If filename only contains of special chars */
- if (str.matches("[_]+")) //$NON-NLS-1$
- str = "file"; //$NON-NLS-1$
-
- return str;
- }
-
-
- /**
- * Make the first letter uppercase
- * @param str
- * @return The string with the first letter being changed to uppercase
- * @since 5.5
- */
- public static String firstLetterUppercase(String str) {
- if(str == null || str.length() == 0) {
- return null;
- }
- if(str.length() == 1) {
- return str.toUpperCase();
- }
- return str.substring(0, 1).toUpperCase() + str.substring(1);
- }
-
- private static String convertBasicLatinToUpper(String str) {
- char[] chars = str.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (isBasicLatinLowerCase(chars[i])) {
- chars[i] = (char)('A' + (chars[i] - 'a'));
- } else if (!isBasicLatinChar(chars[i])) {
- return null;
- }
- }
- return new String(chars);
- }
-
- private static String convertBasicLatinToLower(String str) {
- char[] chars = str.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (isBasicLatinUpperCase(chars[i])) {
- chars[i] = (char)('a' + (chars[i] - 'A'));
- } else if (!isBasicLatinChar(chars[i])) {
- return null;
- }
- }
- return new String(chars);
- }
-
- private static boolean isBasicLatinUpperCase(char c) {
- return c >= 'A' && c <= 'Z';
- }
- private static boolean isBasicLatinLowerCase(char c) {
- return c >= 'a' && c <= 'z';
- }
- private static boolean isBasicLatinLetter(char c) {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
- }
- private static boolean isBasicLatinDigit(char c) {
- return c >= '0' && c <= '9';
- }
- private static boolean isBasicLatinChar(char c) {
- return c <= '\u007F';
- }
-
- /**
- * Convert the given value to specified type.
- * @param value
- * @param type
- * @return
- */
- @SuppressWarnings("unchecked")
- public static <T> T valueOf(String value, Class type){
-
- if(type == String.class) {
- return (T) value;
- }
- else if(type == Boolean.class || type == Boolean.TYPE) {
- return (T) Boolean.valueOf(value);
- }
- else if (type == Integer.class || type == Integer.TYPE) {
- return (T) Integer.decode(value);
- }
- else if (type == Float.class || type == Float.TYPE) {
- return (T) Float.valueOf(value);
- }
- else if (type == Double.class || type == Double.TYPE) {
- return (T) Double.valueOf(value);
- }
- else if (type == Long.class || type == Long.TYPE) {
- return (T) Long.decode(value);
- }
- else if (type == Short.class || type == Short.TYPE) {
- return (T) Short.decode(value);
- }
- else if (type.isAssignableFrom(List.class)) {
- return (T)new ArrayList<String>(Arrays.asList(value.split(","))); //$NON-NLS-1$
- }
- else if (type == Void.class) {
- return null;
- }
- else if (type.isEnum()) {
- return (T)Enum.valueOf(type, value);
- }
-
- else if (type.isAssignableFrom(Map.class)) {
- List<String> l = Arrays.asList(value.split(",")); //$NON-NLS-1$
- Map m = new HashMap<String, String>();
- for(String key: l) {
- int index = key.indexOf('=');
- if (index != -1) {
- m.put(key.substring(0, index), key.substring(index+1));
- }
- }
- return (T)m;
- }
-
- throw new IllegalArgumentException("Conversion from String to "+ type.getName() + " is not supported"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
15 years, 3 months
teiid SVN: r1489 - in trunk/engine/src: main/java/com/metamatrix/query/optimizer/relational and 8 other directories.
by teiid-commits@lists.jboss.org
Author: shawkins
Date: 2009-09-29 09:52:23 -0400 (Tue, 29 Sep 2009)
New Revision: 1489
Modified:
trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/PlanToProcessConverter.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePushSelectCriteria.java
trunk/engine/src/main/java/com/metamatrix/query/processor/relational/DependentAccessNode.java
trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
trunk/engine/src/main/java/com/metamatrix/query/sql/lang/Query.java
trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java
trunk/engine/src/test/java/com/metamatrix/query/processor/relational/TestAccessNode.java
Log:
TEIID-858 fix for dependentsetcriteria not being replaced
Modified: trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/eval/Evaluator.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -317,7 +317,13 @@
valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
} else if (criteria instanceof DependentSetCriteria){
ContextReference ref = (ContextReference)criteria;
- HashSet<Object> values = getValues(getContext(criteria), ref);
+ ValueIteratorSource vis = (ValueIteratorSource)getContext(criteria).getVariableContext().getGlobalValue(ref.getContextSymbol());
+ HashSet<Object> values;
+ try {
+ values = vis.getCachedSet(ref.getValueExpression());
+ } catch (MetaMatrixProcessingException e) {
+ throw new CriteriaEvaluationException(e, e.getMessage());
+ }
if (values != null) {
return values.contains(leftValue);
}
@@ -362,19 +368,6 @@
return Boolean.valueOf(criteria.isNegated());
}
- public static HashSet<Object> getValues(CommandContext context,
- ContextReference ref) throws MetaMatrixComponentException,
- CriteriaEvaluationException {
- ValueIteratorSource vis = (ValueIteratorSource)context.getVariableContext().getGlobalValue(ref.getContextSymbol());
- HashSet<Object> values;
- try {
- values = vis.getCachedSet(ref.getValueExpression());
- } catch (MetaMatrixProcessingException e) {
- throw new CriteriaEvaluationException(e, e.getMessage());
- }
- return values;
- }
-
public boolean evaluate(IsNullCriteria criteria, List tuple)
throws CriteriaEvaluationException, BlockedException, MetaMatrixComponentException {
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/PlanToProcessConverter.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/PlanToProcessConverter.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/PlanToProcessConverter.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -82,7 +82,6 @@
import com.metamatrix.query.sql.util.SymbolMap;
import com.metamatrix.query.sql.visitor.EvaluatableVisitor;
import com.metamatrix.query.sql.visitor.GroupCollectorVisitor;
-import com.metamatrix.query.util.CommandContext;
import com.metamatrix.query.util.ErrorMessageKeys;
public class PlanToProcessConverter {
@@ -90,14 +89,12 @@
private IDGenerator idGenerator;
private AnalysisRecord analysisRecord;
private CapabilitiesFinder capFinder;
- private CommandContext context;
- public PlanToProcessConverter(QueryMetadataInterface metadata, IDGenerator idGenerator, AnalysisRecord analysisRecord, CapabilitiesFinder capFinder, CommandContext context) {
+ public PlanToProcessConverter(QueryMetadataInterface metadata, IDGenerator idGenerator, AnalysisRecord analysisRecord, CapabilitiesFinder capFinder) {
this.metadata = metadata;
this.idGenerator = idGenerator;
this.analysisRecord = analysisRecord;
this.capFinder = capFinder;
- this.context = context;
}
public RelationalPlan convert(PlanNode planNode)
@@ -275,16 +272,9 @@
//create dependent access node
DependentAccessNode depAccessNode = new DependentAccessNode(getID());
- int maxSetSize = -1;
if(modelID != null){
- try {
- // set the max set size for the access node
- maxSetSize = CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder);
- }catch(QueryMetadataException e) {
- throw new QueryPlannerException(e, QueryExecPlugin.Util.getString(ErrorMessageKeys.OPTIMIZER_0006, modelID));
- }
+ depAccessNode.setMaxSetSize(CapabilitiesUtil.getMaxInCriteriaSize(modelID, metadata, capFinder));
}
- depAccessNode.setMaxSetSize(maxSetSize);
processNode = depAccessNode;
aNode = depAccessNode;
}
@@ -298,8 +288,7 @@
//-- special handling for temp tables. currently they cannot perform projection
try {
if (command instanceof Query) {
- processNode = correctProjectionForTempTable(node,
- aNode);
+ processNode = correctProjectionForTempTable(node, aNode);
}
} catch (QueryMetadataException err) {
throw new MetaMatrixComponentException(err);
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/RelationalPlanner.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -53,7 +53,6 @@
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
import com.metamatrix.query.sql.util.SymbolMap;
import com.metamatrix.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
-import com.metamatrix.query.sql.visitor.GroupCollectorVisitor;
import com.metamatrix.query.sql.visitor.GroupsUsedByElementsVisitor;
import com.metamatrix.query.util.CommandContext;
import com.metamatrix.query.util.ErrorMessageKeys;
@@ -146,7 +145,7 @@
planToProcessConverter = context.getPlanToProcessConverter();
}
if (planToProcessConverter == null) {
- planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder, context);
+ planToProcessConverter = new PlanToProcessConverter(metadata, idGenerator, analysisRecord, capFinder);
}
RelationalPlan result = planToProcessConverter.convert(plan);
Modified: trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePushSelectCriteria.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePushSelectCriteria.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/optimizer/relational/rules/RulePushSelectCriteria.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -282,8 +282,9 @@
}
satisfyAccessPatterns(critNode, currentNode);
-
- if (critNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)) {
+
+ if (critNode.hasBooleanProperty(NodeConstants.Info.IS_DEPENDENT_SET)
+ && CapabilitiesUtil.getMaxInCriteriaSize(RuleRaiseAccess.getModelIDFromAccess(currentNode, metadata), metadata, capFinder) > 0) {
//once a dependent crit node is pushed, don't bother pushing it further into the command
//dependent access node will use this as an assumption for where dependent sets can appear in the command
critNode.setProperty(NodeConstants.Info.IS_PUSHED, Boolean.TRUE);
Modified: trunk/engine/src/main/java/com/metamatrix/query/processor/relational/DependentAccessNode.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/processor/relational/DependentAccessNode.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/processor/relational/DependentAccessNode.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -114,10 +114,6 @@
Query query = (Query)atomicCommand;
- if (query.getCriteria() == null || maxSetSize < 1) {
- return super.prepareNextCommand(atomicCommand);
- }
-
if (this.criteriaProcessor == null) {
this.criteriaProcessor = new DependentCriteriaProcessor(this.maxSetSize, this, query.getCriteria());
}
Modified: trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/rewriter/QueryRewriter.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -69,6 +69,7 @@
import com.metamatrix.query.metadata.TempMetadataID;
import com.metamatrix.query.metadata.TempMetadataStore;
import com.metamatrix.query.processor.ProcessorDataManager;
+import com.metamatrix.query.processor.relational.DependentValueSource;
import com.metamatrix.query.resolver.QueryResolver;
import com.metamatrix.query.resolver.util.ResolverUtil;
import com.metamatrix.query.resolver.util.ResolverVisitor;
@@ -144,6 +145,7 @@
import com.metamatrix.query.sql.symbol.SearchedCaseExpression;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
import com.metamatrix.query.sql.util.SymbolMap;
+import com.metamatrix.query.sql.util.ValueIterator;
import com.metamatrix.query.sql.visitor.AggregateSymbolCollectorVisitor;
import com.metamatrix.query.sql.visitor.CriteriaTranslatorVisitor;
import com.metamatrix.query.sql.visitor.ElementCollectorVisitor;
@@ -1085,11 +1087,36 @@
}
rewriteSubqueryContainer((SubqueryContainer)criteria, true);
} else if (criteria instanceof DependentSetCriteria) {
- criteria = rewriteCriteria((AbstractSetCriteria)criteria);
+ criteria = rewriteDependentSetCriteria((DependentSetCriteria)criteria);
}
return evaluateCriteria(criteria);
}
+
+ private Criteria rewriteDependentSetCriteria(DependentSetCriteria dsc)
+ throws QueryValidatorException {
+ if (dataMgr == null) {
+ return rewriteCriteria(dsc);
+ }
+ SetCriteria setCrit = new SetCriteria();
+ setCrit.setExpression(dsc.getExpression());
+ HashSet<Object> values = new HashSet<Object>();
+ try {
+ DependentValueSource dvs = (DependentValueSource)this.context.getVariableContext().getGlobalValue(dsc.getContextSymbol());
+ ValueIterator iter = dvs.getValueIterator(dsc.getValueExpression());
+ while (iter.hasNext()) {
+ values.add(iter.next());
+ }
+ } catch (MetaMatrixComponentException e) {
+ throw new MetaMatrixRuntimeException(e);
+ }
+ List<Constant> constants = new ArrayList<Constant>(values.size());
+ for (Object value : values) {
+ constants.add(new Constant(value, setCrit.getExpression().getType()));
+ }
+ setCrit.setValues(constants);
+ return rewriteCriteria(setCrit);
+ }
/**
* Performs simple expression flattening
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/lang/Query.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/lang/Query.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/lang/Query.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -34,7 +34,6 @@
import com.metamatrix.query.metadata.QueryMetadataInterface;
import com.metamatrix.query.sql.LanguageVisitor;
import com.metamatrix.query.sql.symbol.ElementSymbol;
-import com.metamatrix.query.sql.symbol.GroupSymbol;
import com.metamatrix.query.sql.symbol.SelectSymbol;
import com.metamatrix.query.sql.symbol.SingleElementSymbol;
/**
Modified: trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java
===================================================================
--- trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/com/metamatrix/query/sql/visitor/EvaluatableVisitor.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -133,7 +133,7 @@
}
public void visit(DependentSetCriteria obj) {
- evaluationNotPossible(EvaluationLevel.PUSH_DOWN);
+ evaluationNotPossible(EvaluationLevel.PROCESSING);
}
public void visit(ExistsCriteria obj) {
Modified: trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
===================================================================
--- trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -59,7 +59,7 @@
IDGenerator idGenerator, AnalysisRecord analysisRecord,
CapabilitiesFinder capFinder, Set<String> multiSourceModels,
String vdbName, VDBService vdbService, String vdbVersion, CommandContext context) {
- super(metadata, idGenerator, analysisRecord, capFinder, context);
+ super(metadata, idGenerator, analysisRecord, capFinder);
this.multiSourceModels = multiSourceModels;
this.vdbName = vdbName;
this.vdbService = vdbService;
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/TestDependentJoins.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -25,6 +25,10 @@
import java.util.Arrays;
import java.util.List;
+import com.metamatrix.api.exception.MetaMatrixComponentException;
+import com.metamatrix.api.exception.query.QueryParserException;
+import com.metamatrix.api.exception.query.QueryResolverException;
+import com.metamatrix.api.exception.query.QueryValidatorException;
import com.metamatrix.query.optimizer.TestOptimizer;
import com.metamatrix.query.optimizer.capabilities.BasicSourceCapabilities;
import com.metamatrix.query.optimizer.capabilities.FakeCapabilitiesFinder;
@@ -498,9 +502,24 @@
}
public void testCase5130a() throws Exception {
- FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+ HardcodedDataManager dataManager = helpTestDependentJoin(false);
+
+ assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt2.smalla AS a WHERE (concat(a.stringkey, 't') IN ('1t', '2')) AND (a.intkey IN (1))")); //$NON-NLS-1$
+ }
+
+ public void testUnlimitedIn() throws Exception {
+ helpTestDependentJoin(true);
+ }
+
+ private HardcodedDataManager helpTestDependentJoin(boolean unlimitIn)
+ throws QueryParserException, QueryResolverException,
+ QueryValidatorException, MetaMatrixComponentException {
+ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+ if (unlimitIn) {
+ caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, -1);
+ }
capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
@@ -511,8 +530,8 @@
new String[] {"SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0 WHERE g_0.intkey IN (<dependent values>)", "SELECT g_0.stringkey, g_0.intkey FROM bqt2.smallb AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
TestOptimizer.checkNodeTypes(plan, new int[] {
- 1, // Access
- 1, // DependentAccess
+ unlimitIn?2:1, // Access
+ unlimitIn?0:1, // DependentAccess
0, // DependentSelect
0, // DependentProject
0, // DupRemove
@@ -540,9 +559,8 @@
};
TestProcessor.helpProcess(plan, dataManager, expected);
-
- assertFalse(dataManager.getCommandHistory().contains("SELECT a.stringkey, a.intkey FROM bqt2.smalla AS a WHERE (concat(a.stringkey, 't') IN ('1t', '2')) AND (a.intkey IN (1))")); //$NON-NLS-1$
- }
+ return dataManager;
+ }
static void sampleData4(FakeDataManager dataMgr) throws Exception {
FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
Modified: trunk/engine/src/test/java/com/metamatrix/query/processor/relational/TestAccessNode.java
===================================================================
--- trunk/engine/src/test/java/com/metamatrix/query/processor/relational/TestAccessNode.java 2009-09-28 21:11:23 UTC (rev 1488)
+++ trunk/engine/src/test/java/com/metamatrix/query/processor/relational/TestAccessNode.java 2009-09-29 13:52:23 UTC (rev 1489)
@@ -22,15 +22,15 @@
package com.metamatrix.query.processor.relational;
+import java.util.Arrays;
+
import junit.framework.TestCase;
-import com.metamatrix.api.exception.MetaMatrixComponentException;
-import com.metamatrix.common.buffer.BlockedException;
import com.metamatrix.common.buffer.BufferManager;
import com.metamatrix.common.buffer.BufferManagerFactory;
-import com.metamatrix.common.buffer.TupleSource;
import com.metamatrix.query.parser.QueryParser;
-import com.metamatrix.query.processor.ProcessorDataManager;
+import com.metamatrix.query.processor.FakeDataManager;
+import com.metamatrix.query.processor.TestProcessor;
import com.metamatrix.query.resolver.TestResolver;
import com.metamatrix.query.sql.lang.Command;
import com.metamatrix.query.sql.lang.CompoundCriteria;
@@ -57,14 +57,18 @@
CommandContext context = new CommandContext();
context.setProcessorID("processorID"); //$NON-NLS-1$
BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
- FakePDM dataManager = new FakePDM(expectedCommand);
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
node.initialize(context, bm, dataManager);
node.setShouldEvaluateExpressions(true);
// Call open()
node.open();
-
- assertEquals(shouldRegisterRequest, dataManager.registerRequestCalled);
+ if (shouldRegisterRequest) {
+ assertEquals(Arrays.asList(expectedCommand), dataManager.getQueries());
+ } else {
+ assertEquals(0, dataManager.getQueries().size());
+ }
}
public void testOpen_Defect16059() throws Exception {
@@ -91,31 +95,14 @@
CommandContext context = new CommandContext();
context.setProcessorID("processorID"); //$NON-NLS-1$
BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
- FakePDM dataManager = new FakePDM("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5"); //$NON-NLS-1$
+ FakeDataManager dataManager = new FakeDataManager();
+ TestProcessor.sampleData1(dataManager);
node.initialize(context, bm, dataManager);
// Call open()
node.open();
- assertTrue(dataManager.registerRequestCalled);
+ assertEquals(Arrays.asList("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5"), dataManager.getQueries()); //$NON-NLS-1$
}
- private final static class FakePDM implements ProcessorDataManager {
- private String expectedCommand;
- private boolean registerRequestCalled = false;
- private FakePDM(String command) {
- this.expectedCommand = command;
- }
- public Object lookupCodeValue(CommandContext context,String codeTableName,String returnElementName,String keyElementName,Object keyValue) throws BlockedException,MetaMatrixComponentException {return null;}
- public TupleSource registerRequest(Object processorID,Command command,String modelName,String connectorBindingId, int nodeID) throws MetaMatrixComponentException {
- registerRequestCalled = true;
- assertEquals(expectedCommand, command.toString());
- return null;
- }
- @Override
- public void clearCodeTables() {
-
- }
- }
-
public void testShouldExecuteUpdate() throws Exception {
Update update = new Update();
15 years, 3 months